diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0cffcb3 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +config.json \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cde4ac6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,10 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. + +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 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. + +For more information, please refer to diff --git a/commands/ping.js b/commands/ping.js new file mode 100644 index 0000000..64e2ba6 --- /dev/null +++ b/commands/ping.js @@ -0,0 +1,10 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName('ping') + .setDescription('Replies with Pong!'), + async execute(interaction) { + await interaction.reply('Pong!'); + }, +}; diff --git a/commands/server.js b/commands/server.js new file mode 100644 index 0000000..67411cf --- /dev/null +++ b/commands/server.js @@ -0,0 +1,11 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName('server') + .setDescription('Provides information about the server.'), + async execute(interaction) { + // interaction.guild is the object representing the Guild in which the command was run + await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`); + }, +}; diff --git a/commands/user.js b/commands/user.js new file mode 100644 index 0000000..6ef0ba8 --- /dev/null +++ b/commands/user.js @@ -0,0 +1,12 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName('user') + .setDescription('Provides information about the user.'), + async execute(interaction) { + // interaction.user is the object representing the User who ran the command + // interaction.member is the GuildMember object, which represents the user in the specific guild + await interaction.reply(`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`); + }, +}; diff --git a/deploy-commands.js b/deploy-commands.js new file mode 100644 index 0000000..0cf3c76 --- /dev/null +++ b/deploy-commands.js @@ -0,0 +1,36 @@ +const { REST, Routes } = require('discord.js'); +const { clientId, guildId, token } = require('./config.json'); +const fs = require('node:fs'); +const path = require('node:path'); + +const commands = []; +// Grab all the command files from the commands directory you created earlier +const commandsPath = path.join(__dirname, 'commands'); +const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); + +// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment +for (const file of commandFiles) { + const command = require(`./commands/${file}`); + commands.push(command.data.toJSON()); +} + +// Construct and prepare an instance of the REST module +const rest = new REST({ version: '10' }).setToken(token); + +// and deploy your commands! +(async () => { + try { + console.log(`Started refreshing ${commands.length} application (/) commands.`); + + // The put method is used to fully refresh all commands in the guild with the current set + const data = await rest.put( + Routes.applicationCommands(clientId), + { body: commands }, + ); + + console.log(`Successfully reloaded ${data.length} application (/) commands.`); + } catch (error) { + // And of course, make sure you catch and log any errors! + console.error(error); + } +})(); diff --git a/discordbot.sh b/discordbot.sh new file mode 100755 index 0000000..d1f4fdf --- /dev/null +++ b/discordbot.sh @@ -0,0 +1,2 @@ +#!/bin/bash +node index.js \ No newline at end of file diff --git a/img_input.txt b/img_input.txt new file mode 100644 index 0000000..525aec9 --- /dev/null +++ b/img_input.txt @@ -0,0 +1 @@ +fuckery \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..a9c1dd3 --- /dev/null +++ b/index.js @@ -0,0 +1,62 @@ +const { Client, Collection, Events, GatewayIntentBits, ActivityType } = require('discord.js'); +const fs = require('node:fs'); +const path = require('node:path'); +const { token } = require('./config.json'); + + +const client = new Client({ intents: [GatewayIntentBits.Guilds] }); + +//COMMANDS +client.commands = new Collection(); + +const commandsPath = path.join(__dirname, 'commands'); +const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); + +for (const file of commandFiles) { + const filePath = path.join(commandsPath, file); + const command = require(filePath); + // 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.`); + } +} + +client.on(Events.InteractionCreate, async interaction => { + if (!interaction.isChatInputCommand()) return; + const command = interaction.client.commands.get(interaction.commandName); + + if (!command) { + console.error(`No command matching ${interaction.commandName} was found.`); + return; + } + + try { + await command.execute(interaction); + } catch (error) { + console.error(error); + if (interaction.replied || interaction.deferred) { + await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true }); + } else { + await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true }); + } + } + + console.log(interaction); +}); + + +//COMMANDS + +//CLIENT READY +client.once(Events.ClientReady, c => { + client.user.setPresence({ activities: [{ name: `The Multiverse`, type: ActivityType.Watching }], + status: 'online',}); + console.log(`Ready! Logged in as ${c.user.tag}`); +}); +//CLIENT READY + + +//Login to bot +client.login(token); \ No newline at end of file diff --git a/node_modules/.bin/is-ci b/node_modules/.bin/is-ci new file mode 120000 index 0000000..fe6aca6 --- /dev/null +++ b/node_modules/.bin/is-ci @@ -0,0 +1 @@ +../is-ci/bin.js \ No newline at end of file diff --git a/node_modules/.bin/nodemon b/node_modules/.bin/nodemon new file mode 120000 index 0000000..1056ddc --- /dev/null +++ b/node_modules/.bin/nodemon @@ -0,0 +1 @@ +../nodemon/bin/nodemon.js \ No newline at end of file diff --git a/node_modules/.bin/nodetouch b/node_modules/.bin/nodetouch new file mode 120000 index 0000000..3409fdb --- /dev/null +++ b/node_modules/.bin/nodetouch @@ -0,0 +1 @@ +../touch/bin/nodetouch.js \ No newline at end of file diff --git a/node_modules/.bin/nopt b/node_modules/.bin/nopt new file mode 120000 index 0000000..6b6566e --- /dev/null +++ b/node_modules/.bin/nopt @@ -0,0 +1 @@ +../nopt/bin/nopt.js \ No newline at end of file diff --git a/node_modules/.bin/rc b/node_modules/.bin/rc new file mode 120000 index 0000000..48b3cda --- /dev/null +++ b/node_modules/.bin/rc @@ -0,0 +1 @@ +../rc/cli.js \ No newline at end of file diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 120000 index 0000000..317eb29 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..7e08ee0 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,2106 @@ +{ + "name": "discord_bot", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@babel/runtime": { + "version": "7.15.3", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.15.3.tgz", + "integrity": "sha512-OvwMLqNXkCXSz1kSm58sEsNuhqOx/fKpnUnKnFB5v8uDda5bLNEHNgKPvhDN6IU0LDcnHQ90LlJ0Q6jnyBSIBA==", + "dependencies": { + "regenerator-runtime": "^0.13.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@discordjs/builders": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.5.0.tgz", + "integrity": "sha512-7XxT78mnNBPigHn2y6KAXkicxIBFtZREGWaRZ249EC1l6gBUEP8IyVY5JTciIjJArxkF+tg675aZvsTNTKBpmA==", + "dependencies": { + "@discordjs/formatters": "^0.2.0", + "@discordjs/util": "^0.2.0", + "@sapphire/shapeshift": "^3.8.1", + "discord-api-types": "^0.37.35", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.3", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/collection": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.4.0.tgz", + "integrity": "sha512-hiOJyk2CPFf1+FL3a4VKCuu1f448LlROVuu8nLz1+jCOAPokUcdFAV+l4pd3B3h6uJlJQSASoZzrdyNdjdtfzQ==", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.2.0.tgz", + "integrity": "sha512-vn4oMSXuMZUm8ITqVOtvE7/fMMISj4cI5oLsR09PEQXHKeKDAMLltG/DWeeIs7Idfy6V8Fk3rn1e69h7NfzuNA==", + "dependencies": { + "discord-api-types": "^0.37.35" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/rest": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.6.0.tgz", + "integrity": "sha512-HGvqNCZ5Z5j0tQHjmT1lFvE5ETO4hvomJ1r0cbnpC1zM23XhCpZ9wgTCiEmaxKz05cyf2CI9p39+9LL+6Yz1bA==", + "dependencies": { + "@discordjs/collection": "^1.4.0", + "@discordjs/util": "^0.2.0", + "@sapphire/async-queue": "^1.5.0", + "@sapphire/snowflake": "^3.4.0", + "discord-api-types": "^0.37.35", + "file-type": "^18.2.1", + "tslib": "^2.5.0", + "undici": "^5.20.0" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/util": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.2.0.tgz", + "integrity": "sha512-/8qNbebFzLWKOOg+UV+RB8itp4SmU5jw0tBUD3ifElW6rYNOj1Ku5JaSW7lLl/WgjjxF01l/1uQPCzkwr110vg==", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/voice": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@discordjs/voice/-/voice-0.15.0.tgz", + "integrity": "sha512-YEvrRchDhjB0QbI9QYOF/qgDwvGb9sNGUyks5d3Srl+VRoMoKkMzWY+wcEfVbAgdMIAdLi5vyrTKP/gLND26jA==", + "dependencies": { + "@types/ws": "^8.5.4", + "discord-api-types": "^0.37.35", + "prism-media": "^1.3.5", + "tslib": "^2.5.0", + "ws": "^8.12.1" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.0.tgz", + "integrity": "sha512-JkLdIsP8fPAdh9ZZjrbHWR/+mZj0wvKS5ICibcLrRI1j84UmLMshx5n9QmL8b95d4onJ2xxiyugTgSAX7AalmA==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.8.1.tgz", + "integrity": "sha512-xG1oXXBhCjPKbxrRTlox9ddaZTvVpOhYLmKmApD/vIWOV1xEYXnpoFs68zHIZBGbqztq6FrUPNPerIrO1Hqeaw==", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.4.0.tgz", + "integrity": "sha512-zZxymtVO6zeXVMPds+6d7gv/OfnCc25M1Z+7ZLB0oPmeMTPeRWVPQSS16oDJy5ZsyCOLj7M6mbZml5gWXcVRNw==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sindresorhus/is": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", + "integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/@szmarczak/http-timer": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-1.1.2.tgz", + "integrity": "sha512-XIB2XbzHTN6ieIjfIMV9hlVcfPU26s2vafYWQcZHWXHOxiaRZYEDKEwdl129Zyg50+foYV2jCgtrqSA6qNuNSA==", + "dependencies": { + "defer-to-connect": "^1.0.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==" + }, + "node_modules/@types/jsonwebtoken": { + "version": "8.5.4", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-8.5.4.tgz", + "integrity": "sha512-4L8msWK31oXwdtC81RmRBAULd0ShnAHjBuKT9MRQpjP0piNrZdXyTRcKY9/UIfhGeKIT4PvF5amOOUbbT/9Wpg==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/jwt-decode": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@types/jwt-decode/-/jwt-decode-2.2.1.tgz", + "integrity": "sha512-aWw2YTtAdT7CskFyxEX2K21/zSDStuf/ikI3yBqmwpwJF0pS+/IX5DWv+1UFffZIbruP6cnT9/LAJV1gFwAT1A==" + }, + "node_modules/@types/node": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.6.1.tgz", + "integrity": "sha512-Sr7BhXEAer9xyGuCN3Ek9eg9xPviCF2gfu9kTfuU2HkTVAMYSDeX40fvpmo72n5nansg3nsBjuQBrsS28r+NUw==" + }, + "node_modules/@types/qs": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.7.tgz", + "integrity": "sha512-FGa1F62FT09qcrueBA6qYTrJPVDzah9a+493+o2PCXsesWHIn27G98TsSMs3WPNbZIEj4+VJf6saSFpvD+3Zsw==" + }, + "node_modules/@types/ws": { + "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/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, + "node_modules/ansi-align": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.0.tgz", + "integrity": "sha512-ZpClVKqXN3RGBmKibdfWzqCY4lnjEuoNzU5T0oEFpfd/z5qJHVarukridD4juLO2FXMiwUQxr9WqQtaYa8XRYw==", + "dependencies": { + "string-width": "^3.0.0" + } + }, + "node_modules/ansi-align/node_modules/ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-align/node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, + "node_modules/ansi-align/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "engines": { + "node": ">=4" + } + }, + "node_modules/ansi-align/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-align/node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "node_modules/axios": { + "version": "0.21.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", + "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", + "dependencies": { + "follow-redirects": "^1.14.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/boxen": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/boxen/-/boxen-5.1.2.tgz", + "integrity": "sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==", + "dependencies": { + "ansi-align": "^3.0.0", + "camelcase": "^6.2.0", + "chalk": "^4.1.0", + "cli-boxes": "^2.2.1", + "string-width": "^4.2.2", + "type-fest": "^0.20.2", + "widest-line": "^3.1.0", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, + "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" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/cacheable-request": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-6.1.0.tgz", + "integrity": "sha512-Oj3cAGPCqOZX7Rz64Uny2GYAZNliQSqfbePrgAQ1wKAihYmCUnraBtJtKcGR4xz7wF+LoJC+ssFZvv5BgF9Igg==", + "dependencies": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^3.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^4.1.0", + "responselike": "^1.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cacheable-request/node_modules/get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cacheable-request/node_modules/lowercase-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camelcase": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz", + "integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==" + }, + "node_modules/cli-boxes": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-2.2.1.tgz", + "integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clone-response": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", + "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", + "dependencies": { + "mimic-response": "^1.0.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "node_modules/configstore": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/configstore/-/configstore-5.0.1.tgz", + "integrity": "sha512-aMKprgk5YhBNyH25hj8wGt2+D52Sw1DRRIzqBwLp2Ya9mFmY8KPvvtvmna8SxVR9JMZ4kzMD68N22vlaRpkeFA==", + "dependencies": { + "dot-prop": "^5.2.0", + "graceful-fs": "^4.1.2", + "make-dir": "^3.0.0", + "unique-string": "^2.0.0", + "write-file-atomic": "^3.0.0", + "xdg-basedir": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/crypto-random-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", + "integrity": "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/csprng": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/csprng/-/csprng-0.1.2.tgz", + "integrity": "sha1-S8aPEvo2jSUqWYQcusqXSxirReI=", + "dependencies": { + "sequin": "*" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/decompress-response": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", + "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", + "dependencies": { + "mimic-response": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/defer-to-connect": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-1.1.3.tgz", + "integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/discord-api-types": { + "version": "0.37.37", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.37.tgz", + "integrity": "sha512-LDMBKzl/zbvHO/yCzno5hevuA6lFIXJwdKSJZQrB+1ToDpFfN9thK+xxgZNR4aVkI7GHRDja0p4Sl2oYVPnHYg==" + }, + "node_modules/discord.js": { + "version": "14.8.0", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.8.0.tgz", + "integrity": "sha512-UOxYtc/YnV7jAJ2gISluJyYeBw4e+j8gWn+IoqG8unaHAVuvZ13DdYN0M1f9fbUgUvSarV798inIrYFtDNDjwQ==", + "dependencies": { + "@discordjs/builders": "^1.5.0", + "@discordjs/collection": "^1.4.0", + "@discordjs/formatters": "^0.2.0", + "@discordjs/rest": "^1.6.0", + "@discordjs/util": "^0.2.0", + "@sapphire/snowflake": "^3.4.0", + "@types/ws": "^8.5.4", + "discord-api-types": "^0.37.35", + "fast-deep-equal": "^3.1.3", + "lodash.snakecase": "^4.1.1", + "tslib": "^2.5.0", + "undici": "^5.20.0", + "ws": "^8.12.1" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/dot-prop": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", + "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/duplexer3": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", + "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=" + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/escape-goat": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/escape-goat/-/escape-goat-2.1.1.tgz", + "integrity": "sha512-8/uIhbG12Csjy2JEW7D9pHbreaVaS/OpN3ycnyvElTdwM5n6GY6W6e2IPemfvGZeUMqZ9A/3GqIZMgKnBhAw/Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/faye": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/faye/-/faye-1.4.0.tgz", + "integrity": "sha512-kRrIg4be8VNYhycS2PY//hpBJSzZPr/DBbcy9VWelhZMW3KhyLkQR0HL0k0MNpmVoNFF4EdfMFkNAWjTP65g6w==", + "dependencies": { + "asap": "*", + "csprng": "*", + "faye-websocket": ">=0.9.1", + "safe-buffer": "*", + "tough-cookie": "*", + "tunnel-agent": "*" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/file-type": { + "version": "18.2.1", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-18.2.1.tgz", + "integrity": "sha512-Yw5MtnMv7vgD2/6Bjmmuegc8bQEVA9GmAyaR18bMYWKqsWDG9wgYZ1j4I6gNMF5Y5JBDcUcjRQqNQx7Y8uotcg==", + "dependencies": { + "readable-web-to-node-stream": "^3.0.2", + "strtok3": "^7.0.0", + "token-types": "^5.0.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", + "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "node_modules/get-intrinsic": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", + "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-stream": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", + "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/getstream": { + "version": "7.2.10", + "resolved": "https://registry.npmjs.org/getstream/-/getstream-7.2.10.tgz", + "integrity": "sha512-cSUBxZ8JiTyfTXwiYl6vwqrg1XTOR0YGA+sYSODtuxGBgAsBZIUWWA9mvWgbmWnzRNboL52+bhwyisvaZhxDAA==", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@types/jsonwebtoken": "^8.5.0", + "@types/jwt-decode": "^2.2.1", + "@types/qs": "^6.9.6", + "axios": "^0.21.1", + "faye": "^1.4.0", + "form-data": "^4.0.0", + "jsonwebtoken": "^8.5.1", + "jwt-decode": "^3.1.2", + "qs": "^6.9.6" + }, + "engines": { + "node": "10 || 12 || >=14" + }, + "peerDependencies": { + "@types/node": ">=10" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/global-dirs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-3.0.0.tgz", + "integrity": "sha512-v8ho2DS5RiCjftj1nD9NmnfaOzTdud7RRnVd9kFNOjqZbISlx5DQ+OrTkywgd0dIt7oFCvKetZSHoHcP3sDdiA==", + "dependencies": { + "ini": "2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/global-dirs/node_modules/ini": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-2.0.0.tgz", + "integrity": "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/got": { + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/got/-/got-9.6.0.tgz", + "integrity": "sha512-R7eWptXuGYxwijs0eV+v3o6+XH1IqVK8dJOEecQfTmkncw9AV4dcw/Dhxi8MdlqPthxxpZyizMzyg8RTmEsG+Q==", + "dependencies": { + "@sindresorhus/is": "^0.14.0", + "@szmarczak/http-timer": "^1.1.2", + "cacheable-request": "^6.0.0", + "decompress-response": "^3.3.0", + "duplexer3": "^0.1.4", + "get-stream": "^4.1.0", + "lowercase-keys": "^1.0.1", + "mimic-response": "^1.0.1", + "p-cancelable": "^1.0.0", + "to-readable-stream": "^1.0.0", + "url-parse-lax": "^3.0.0" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz", + "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==" + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-yarn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/has-yarn/-/has-yarn-2.1.0.tgz", + "integrity": "sha512-UqBRqi4ju7T+TqGNdqAO0PaSVGsDGJUBQvk9eUWNGRY1CFGDzYhLWoM7JQEemnlvVcv/YEmc2wNW8BC24EnUsw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", + "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==" + }, + "node_modules/http-parser-js": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.3.tgz", + "integrity": "sha512-t7hjvef/5HEK7RWTdUzVUhl8zkEu+LlaE0IYzdMuvbSDipxBRpOn4Uhw8ZyECEa808iVT8XCjzo6xmYt4CiLZg==" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "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/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==" + }, + "node_modules/import-lazy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", + "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=", + "engines": { + "node": ">=4" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ini": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.7.tgz", + "integrity": "sha512-iKpRpXP+CrP2jyrxvg1kMUpXDyRUFDWurxbnVT1vQPx+Wz9uCYsMIqYuSBLV+PAaZG/d7kRLKRFc9oDMsH+mFQ==" + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", + "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "dependencies": { + "ci-info": "^2.0.0" + }, + "bin": { + "is-ci": "bin.js" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-installed-globally": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/is-installed-globally/-/is-installed-globally-0.4.0.tgz", + "integrity": "sha512-iwGqO3J21aaSkC7jWnHP/difazwS7SFeIqxv6wEtLU8Y5KlzFTjyqcSIT0d8s4+dDhKytsk9PJZ2BkS5eZwQRQ==", + "dependencies": { + "global-dirs": "^3.0.0", + "is-path-inside": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-npm": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-5.0.0.tgz", + "integrity": "sha512-WW/rQLOazUq+ST/bCAVBp/2oMERWLsR7OrKyt052dNDk4DHcDE0/7QSXITlmi+VBcV13DfIbysG3tZJm5RfdBA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", + "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "node_modules/is-yarn-global": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz", + "integrity": "sha512-VjSeb/lHmkoyd8ryPVIKvOCn4D1koMqY+vqyjjUfc3xyKtP4dYOxM44sZrnqQSzSds3xyOrUTLTC9LVCVgLngw==" + }, + "node_modules/json-buffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.0.tgz", + "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=" + }, + "node_modules/jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=4", + "npm": ">=1.4.28" + } + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jwt-decode": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-3.1.2.tgz", + "integrity": "sha512-UfpWE/VZn0iP50d8cz9NrZLM9lSWhcJ+0Gt/nm4by88UL+J1SiKN8/5dkjMmbEzwL2CAe+67GsegCbIKtbp75A==" + }, + "node_modules/keyv": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", + "integrity": "sha512-9ykJ/46SN/9KPM/sichzQ7OvXyGDYKGTaDlKMGCAlg2UK8KRy4jb0d8sFc+0Tt0YYnThq8X2RZgCg74RPxgcVA==", + "dependencies": { + "json-buffer": "3.0.0" + } + }, + "node_modules/latest-version": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-5.1.0.tgz", + "integrity": "sha512-weT+r0kTkRQdCdYCNtkMwWXQTMEswKrFBkm4ckQOMVhhqhIMI1UT2hMj+1iigIhgSZm5gTmrRXBNoGUgaTY1xA==", + "dependencies": { + "package-json": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==" + }, + "node_modules/lowercase-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", + "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==", + "engines": { + "node": ">=0.10.0" + } + }, + "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/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/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/mime-db": { + "version": "1.46.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.46.0.tgz", + "integrity": "sha512-svXaP8UQRZ5K7or+ZmfNhg2xX3yKDMUzqadsSqi4NCH/KomcH75MAMYAGVlvXn4+b/xOPhS3I2uHKRUzvjY7BQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.29", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.29.tgz", + "integrity": "sha512-Y/jMt/S5sR9OaqteJtslsFZKWOIIqMACsJSiHghlCAyhf7jfVYjKBmLiX8OgpWeW+fjJ2b+Az69aPFPkUOY6xQ==", + "dependencies": { + "mime-db": "1.46.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", + "engines": { + "node": ">=4" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/node-fetch": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", + "integrity": "sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/nodemon": { + "version": "2.0.22", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.22.tgz", + "integrity": "sha512-B8YqaKMmyuCO7BowF1Z1/mkPqLk6cs/l63Ojtd6otKjMx47Dq1utxfRxcavH1I7VSaL8n5BUaoutadnsX3AAVQ==", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^3.2.7", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^5.7.1", + "simple-update-notifier": "^1.0.7", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=8.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nopt": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", + "integrity": "sha512-NWmpvLSqUrgrAC9HCuxEvb+PSloHpqVu+FqcO4eeF2h5qYRhA7ev6KvelyQAKtegUbC6RypJnlEOhd8vloNKYg==", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "*" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/normalize-url": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-4.5.1.tgz", + "integrity": "sha512-9UZCFRHQdNrfTpGg8+1INIg93B6zE0aXMVFkw1WFwvO4SlZywU6aLg5Of0Ap/PgcbSw4LNxvMWXMeugwMCX0AA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/object-inspect": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.0.tgz", + "integrity": "sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-cancelable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", + "integrity": "sha512-s73XxOZ4zpt1edZYZzvhqFa6uvQc1vwUa0K0BdtIZgQMAJj9IbebH+JkgKZc9h+B05PKHLOTl4ajG1BmNrVZlw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/package-json": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/package-json/-/package-json-6.5.0.tgz", + "integrity": "sha512-k3bdm2n25tkyxcjSKzB5x8kfVxlMdgsbPr0GkZcwHsLpba6cBjqCt1KlcChKEvxHIcTB1FVMuwoijZ26xex5MQ==", + "dependencies": { + "got": "^9.6.0", + "registry-auth-token": "^4.0.0", + "registry-url": "^5.0.0", + "semver": "^6.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/package-json/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/peek-readable": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-5.0.0.tgz", + "integrity": "sha512-YtCKvLUOvwtMGmrniQPdO7MwPjgkFBtFIrmfSbYmYuq3tKDV/mcfAhBth1+C3ru7uXIZasc/pHnb+YDYNkkj4A==", + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/picomatch": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", + "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prepend-http": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-2.0.0.tgz", + "integrity": "sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=", + "engines": { + "node": ">=4" + } + }, + "node_modules/prism-media": { + "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 <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" + }, + "peerDependenciesMeta": { + "@discordjs/opus": { + "optional": true + }, + "ffmpeg-static": { + "optional": true + }, + "node-opus": { + "optional": true + }, + "opusscript": { + "optional": true + } + } + }, + "node_modules/psl": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==" + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==" + }, + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/pupa": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/pupa/-/pupa-2.1.1.tgz", + "integrity": "sha512-l1jNAspIBSFqbT+y+5FosojNpVpF94nlI+wDUpqP9enwOTfHx9f0gh5nB96vl+6yTpsJsypeNrwfzPrKuHB41A==", + "dependencies": { + "escape-goat": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qs": { + "version": "6.11.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.1.tgz", + "integrity": "sha512-0wsrzgTz/kAVIeuxSjnpGC56rzYtr6JT/2BwEvMaPhFIoYa1aGO8LbzuU1R0uUYQkLpWBTOj0l/CLAJB64J6nQ==", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "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", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readable-web-to-node-stream": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/readable-web-to-node-stream/-/readable-web-to-node-stream-3.0.2.tgz", + "integrity": "sha512-ePeK6cc1EcKLEhJFt/AebMCLL+GgSKhuygrZ/GLaKZYEecIgIECf4UaUuaByiGtzckwR4ain9VzUh95T1exYGw==", + "dependencies": { + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==" + }, + "node_modules/registry-auth-token": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-4.2.1.tgz", + "integrity": "sha512-6gkSb4U6aWJB4SF2ZvLb76yCBjcvufXBqvvEx1HbmKPkutswjW1xNVRY0+daljIYRbogN7O0etYSlbiaEQyMyw==", + "dependencies": { + "rc": "^1.2.8" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/registry-url": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-5.1.0.tgz", + "integrity": "sha512-8acYXXTI0AkQv6RAOjE3vOaIXZkT9wo4LOFbBKYQEEnnMNBpKqdUrI6S4NT0KPIo/WVvJ5tE/X5LF/TQUf0ekw==", + "dependencies": { + "rc": "^1.2.8" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/responselike": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-1.0.2.tgz", + "integrity": "sha1-kYcg7ztjHFZCvgaPFa3lpG9Loec=", + "dependencies": { + "lowercase-keys": "^1.0.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "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/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/semver-diff": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-3.1.1.tgz", + "integrity": "sha512-GX0Ix/CJcHyB8c4ykpHGIAvLyOwOobtM/8d+TQkAd81/bEjgPHrfba41Vpesr7jX/t8Uh+R3EX9eAS5be+jQYg==", + "dependencies": { + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/semver-diff/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/sequin": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/sequin/-/sequin-0.1.1.tgz", + "integrity": "sha1-XC04nWajg3NOqvvEXt6ywcsb5wE=", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==" + }, + "node_modules/simple-update-notifier": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-1.1.0.tgz", + "integrity": "sha512-VpsrsJSUcJEseSbMHkrsrAVSdvVS5I96Qo1QAQ4FxQ9wXFcB+pjj7FB7/us9+GcgfW4ziHtYMc1J0PLczb55mg==", + "dependencies": { + "semver": "~7.0.0" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/simple-update-notifier/node_modules/semver": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz", + "integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", + "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dependencies": { + "ansi-regex": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strtok3": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-7.0.0.tgz", + "integrity": "sha512-pQ+V+nYQdC5H3Q7qBZAz/MO6lwGhoC2gOAjuouGf/VO0m7vQRh8QNMl2Uf6SwAtzZ9bOw3UIeBukEGNJl5dtXQ==", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^5.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-readable-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/to-readable-stream/-/to-readable-stream-1.0.0.tgz", + "integrity": "sha512-Iq25XBt6zD5npPhlLVXGFN3/gyR2/qODcKNNyTMd4vbm39HUaOiAM4PMq0eMVC/Tkxz+Zjdsc55g9yyz+Yq00Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/token-types": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-5.0.1.tgz", + "integrity": "sha512-Y2fmSnZjQdDb9W4w4r1tswlMHylzWIeOKpx0aZH9BgGtACHhrk3OkT52AzwcuqTRBZtvvnTjDBh8eynMulu8Vg==", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/touch": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz", + "integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==", + "dependencies": { + "nopt": "~1.0.10" + }, + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tough-cookie": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", + "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.1.2" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/ts-mixer": { + "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.5.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz", + "integrity": "sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dependencies": { + "is-typedarray": "^1.0.0" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==" + }, + "node_modules/undici": { + "version": "5.21.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.21.0.tgz", + "integrity": "sha512-HOjK8l6a57b2ZGXOcUsI5NLfoTrfmbOl90ixJDl0AEFG4wgHNDQxtZy15/ZQp7HhjkpaGlp/eneMgtsu1dIlUA==", + "dependencies": { + "busboy": "^1.6.0" + }, + "engines": { + "node": ">=12.18" + } + }, + "node_modules/unique-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", + "integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", + "dependencies": { + "crypto-random-string": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/update-notifier": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-5.1.0.tgz", + "integrity": "sha512-ItnICHbeMh9GqUy31hFPrD1kcuZ3rpxDZbf4KUDavXwS0bW5m7SLbDQpGX3UYr072cbrF5hFUs3r5tUsPwjfHw==", + "dependencies": { + "boxen": "^5.0.0", + "chalk": "^4.1.0", + "configstore": "^5.0.1", + "has-yarn": "^2.1.0", + "import-lazy": "^2.1.0", + "is-ci": "^2.0.0", + "is-installed-globally": "^0.4.0", + "is-npm": "^5.0.0", + "is-yarn-global": "^0.3.0", + "latest-version": "^5.1.0", + "pupa": "^2.1.1", + "semver": "^7.3.4", + "semver-diff": "^3.1.1", + "xdg-basedir": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/yeoman/update-notifier?sponsor=1" + } + }, + "node_modules/update-notifier/node_modules/semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/url-parse-lax": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-3.0.0.tgz", + "integrity": "sha1-FrXK/Afb42dsGxmZF3gj1lA6yww=", + "dependencies": { + "prepend-http": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "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==" + }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "engines": { + "node": ">=0.8.0" + } + }, + "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==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/widest-line": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz", + "integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==", + "dependencies": { + "string-width": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "node_modules/write-file-atomic": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dependencies": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } + }, + "node_modules/ws": { + "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" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xdg-basedir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", + "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + } + } +} diff --git a/node_modules/@babel/runtime/LICENSE b/node_modules/@babel/runtime/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/runtime/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2014-present Sebastian McKenzie and other contributors + +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/@babel/runtime/README.md b/node_modules/@babel/runtime/README.md new file mode 100644 index 0000000..119c99d --- /dev/null +++ b/node_modules/@babel/runtime/README.md @@ -0,0 +1,19 @@ +# @babel/runtime + +> babel's modular runtime helpers + +See our website [@babel/runtime](https://babeljs.io/docs/en/babel-runtime) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/runtime +``` + +or using yarn: + +```sh +yarn add @babel/runtime +``` diff --git a/node_modules/@babel/runtime/helpers/AsyncGenerator.js b/node_modules/@babel/runtime/helpers/AsyncGenerator.js new file mode 100644 index 0000000..cdca7f5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/AsyncGenerator.js @@ -0,0 +1,99 @@ +var AwaitValue = require("./AwaitValue.js"); + +function AsyncGenerator(gen) { + var front, back; + + function send(key, arg) { + return new Promise(function (resolve, reject) { + var request = { + key: key, + arg: arg, + resolve: resolve, + reject: reject, + next: null + }; + + if (back) { + back = back.next = request; + } else { + front = back = request; + resume(key, arg); + } + }); + } + + function resume(key, arg) { + try { + var result = gen[key](arg); + var value = result.value; + var wrappedAwait = value instanceof AwaitValue; + Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { + if (wrappedAwait) { + resume(key === "return" ? "return" : "next", arg); + return; + } + + settle(result.done ? "return" : "normal", arg); + }, function (err) { + resume("throw", err); + }); + } catch (err) { + settle("throw", err); + } + } + + function settle(type, value) { + switch (type) { + case "return": + front.resolve({ + value: value, + done: true + }); + break; + + case "throw": + front.reject(value); + break; + + default: + front.resolve({ + value: value, + done: false + }); + break; + } + + front = front.next; + + if (front) { + resume(front.key, front.arg); + } else { + back = null; + } + } + + this._invoke = send; + + if (typeof gen["return"] !== "function") { + this["return"] = undefined; + } +} + +AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () { + return this; +}; + +AsyncGenerator.prototype.next = function (arg) { + return this._invoke("next", arg); +}; + +AsyncGenerator.prototype["throw"] = function (arg) { + return this._invoke("throw", arg); +}; + +AsyncGenerator.prototype["return"] = function (arg) { + return this._invoke("return", arg); +}; + +module.exports = AsyncGenerator; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/AwaitValue.js b/node_modules/@babel/runtime/helpers/AwaitValue.js new file mode 100644 index 0000000..d36df6e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/AwaitValue.js @@ -0,0 +1,6 @@ +function _AwaitValue(value) { + this.wrapped = value; +} + +module.exports = _AwaitValue; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js b/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js new file mode 100644 index 0000000..feaeab8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/applyDecoratedDescriptor.js @@ -0,0 +1,31 @@ +function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object.keys(descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object.defineProperty(target, property, desc); + desc = null; + } + + return desc; +} + +module.exports = _applyDecoratedDescriptor; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayLikeToArray.js b/node_modules/@babel/runtime/helpers/arrayLikeToArray.js new file mode 100644 index 0000000..a459c8e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayLikeToArray.js @@ -0,0 +1,12 @@ +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; +} + +module.exports = _arrayLikeToArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayWithHoles.js b/node_modules/@babel/runtime/helpers/arrayWithHoles.js new file mode 100644 index 0000000..9a36e2a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayWithHoles.js @@ -0,0 +1,6 @@ +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} + +module.exports = _arrayWithHoles; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js b/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js new file mode 100644 index 0000000..aac913f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js @@ -0,0 +1,8 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); +} + +module.exports = _arrayWithoutHoles; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/assertThisInitialized.js b/node_modules/@babel/runtime/helpers/assertThisInitialized.js new file mode 100644 index 0000000..352e1e6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/assertThisInitialized.js @@ -0,0 +1,10 @@ +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +module.exports = _assertThisInitialized; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js b/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js new file mode 100644 index 0000000..91f6d61 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncGeneratorDelegate.js @@ -0,0 +1,57 @@ +function _asyncGeneratorDelegate(inner, awaitWrap) { + var iter = {}, + waiting = false; + + function pump(key, value) { + waiting = true; + value = new Promise(function (resolve) { + resolve(inner[key](value)); + }); + return { + done: false, + value: awaitWrap(value) + }; + } + + ; + + iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function () { + return this; + }; + + iter.next = function (value) { + if (waiting) { + waiting = false; + return value; + } + + return pump("next", value); + }; + + if (typeof inner["throw"] === "function") { + iter["throw"] = function (value) { + if (waiting) { + waiting = false; + throw value; + } + + return pump("throw", value); + }; + } + + if (typeof inner["return"] === "function") { + iter["return"] = function (value) { + if (waiting) { + waiting = false; + return value; + } + + return pump("return", value); + }; + } + + return iter; +} + +module.exports = _asyncGeneratorDelegate; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncIterator.js b/node_modules/@babel/runtime/helpers/asyncIterator.js new file mode 100644 index 0000000..d59aa99 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncIterator.js @@ -0,0 +1,16 @@ +function _asyncIterator(iterable) { + var method; + + if (typeof Symbol !== "undefined") { + if (Symbol.asyncIterator) method = iterable[Symbol.asyncIterator]; + if (method == null && Symbol.iterator) method = iterable[Symbol.iterator]; + } + + if (method == null) method = iterable["@@asyncIterator"]; + if (method == null) method = iterable["@@iterator"]; + if (method == null) throw new TypeError("Object is not async iterable"); + return method.call(iterable); +} + +module.exports = _asyncIterator; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/asyncToGenerator.js b/node_modules/@babel/runtime/helpers/asyncToGenerator.js new file mode 100644 index 0000000..ec5daa8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/asyncToGenerator.js @@ -0,0 +1,38 @@ +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } +} + +function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; +} + +module.exports = _asyncToGenerator; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js b/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js new file mode 100644 index 0000000..c338fee --- /dev/null +++ b/node_modules/@babel/runtime/helpers/awaitAsyncGenerator.js @@ -0,0 +1,8 @@ +var AwaitValue = require("./AwaitValue.js"); + +function _awaitAsyncGenerator(value) { + return new AwaitValue(value); +} + +module.exports = _awaitAsyncGenerator; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js new file mode 100644 index 0000000..521c1e0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorDestructureSet.js @@ -0,0 +1,23 @@ +function _classApplyDescriptorDestructureSet(receiver, descriptor) { + if (descriptor.set) { + if (!("__destrObj" in descriptor)) { + descriptor.__destrObj = { + set value(v) { + descriptor.set.call(receiver, v); + } + + }; + } + + return descriptor.__destrObj; + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + + return descriptor; + } +} + +module.exports = _classApplyDescriptorDestructureSet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js new file mode 100644 index 0000000..f750596 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorGet.js @@ -0,0 +1,10 @@ +function _classApplyDescriptorGet(receiver, descriptor) { + if (descriptor.get) { + return descriptor.get.call(receiver); + } + + return descriptor.value; +} + +module.exports = _classApplyDescriptorGet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js b/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js new file mode 100644 index 0000000..997b264 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classApplyDescriptorSet.js @@ -0,0 +1,14 @@ +function _classApplyDescriptorSet(receiver, descriptor, value) { + if (descriptor.set) { + descriptor.set.call(receiver, value); + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + + descriptor.value = value; + } +} + +module.exports = _classApplyDescriptorSet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCallCheck.js b/node_modules/@babel/runtime/helpers/classCallCheck.js new file mode 100644 index 0000000..026da41 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCallCheck.js @@ -0,0 +1,8 @@ +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +module.exports = _classCallCheck; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js new file mode 100644 index 0000000..67373aa --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticAccess.js @@ -0,0 +1,8 @@ +function _classCheckPrivateStaticAccess(receiver, classConstructor) { + if (receiver !== classConstructor) { + throw new TypeError("Private static access of wrong provenance"); + } +} + +module.exports = _classCheckPrivateStaticAccess; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js new file mode 100644 index 0000000..3b93472 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classCheckPrivateStaticFieldDescriptor.js @@ -0,0 +1,8 @@ +function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { + if (descriptor === undefined) { + throw new TypeError("attempted to " + action + " private static field before its declaration"); + } +} + +module.exports = _classCheckPrivateStaticFieldDescriptor; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js b/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js new file mode 100644 index 0000000..aaaac8c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classExtractFieldDescriptor.js @@ -0,0 +1,10 @@ +function _classExtractFieldDescriptor(receiver, privateMap, action) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to " + action + " private field on non-instance"); + } + + return privateMap.get(receiver); +} + +module.exports = _classExtractFieldDescriptor; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classNameTDZError.js b/node_modules/@babel/runtime/helpers/classNameTDZError.js new file mode 100644 index 0000000..bf740fa --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classNameTDZError.js @@ -0,0 +1,6 @@ +function _classNameTDZError(name) { + throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); +} + +module.exports = _classNameTDZError; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js new file mode 100644 index 0000000..50b9fb0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldDestructureSet.js @@ -0,0 +1,11 @@ +var classApplyDescriptorDestructureSet = require("./classApplyDescriptorDestructureSet.js"); + +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); + +function _classPrivateFieldDestructureSet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} + +module.exports = _classPrivateFieldDestructureSet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js new file mode 100644 index 0000000..df55969 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldGet.js @@ -0,0 +1,11 @@ +var classApplyDescriptorGet = require("./classApplyDescriptorGet.js"); + +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); + +function _classPrivateFieldGet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} + +module.exports = _classPrivateFieldGet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js new file mode 100644 index 0000000..3acdb7b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseBase.js @@ -0,0 +1,10 @@ +function _classPrivateFieldBase(receiver, privateKey) { + if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { + throw new TypeError("attempted to use private field on non-instance"); + } + + return receiver; +} + +module.exports = _classPrivateFieldBase; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js new file mode 100644 index 0000000..3c0c552 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldLooseKey.js @@ -0,0 +1,8 @@ +var id = 0; + +function _classPrivateFieldKey(name) { + return "__private_" + id++ + "_" + name; +} + +module.exports = _classPrivateFieldKey; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js b/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js new file mode 100644 index 0000000..d4a59b0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateFieldSet.js @@ -0,0 +1,12 @@ +var classApplyDescriptorSet = require("./classApplyDescriptorSet.js"); + +var classExtractFieldDescriptor = require("./classExtractFieldDescriptor.js"); + +function _classPrivateFieldSet(receiver, privateMap, value) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} + +module.exports = _classPrivateFieldSet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js new file mode 100644 index 0000000..d2f8ab1 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateMethodGet.js @@ -0,0 +1,10 @@ +function _classPrivateMethodGet(receiver, privateSet, fn) { + if (!privateSet.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + + return fn; +} + +module.exports = _classPrivateMethodGet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js new file mode 100644 index 0000000..f500d16 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classPrivateMethodSet.js @@ -0,0 +1,6 @@ +function _classPrivateMethodSet() { + throw new TypeError("attempted to reassign private method"); +} + +module.exports = _classPrivateMethodSet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js new file mode 100644 index 0000000..57e2c7f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldDestructureSet.js @@ -0,0 +1,14 @@ +var classApplyDescriptorDestructureSet = require("./classApplyDescriptorDestructureSet.js"); + +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); + +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); + +function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} + +module.exports = _classStaticPrivateFieldDestructureSet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js new file mode 100644 index 0000000..136c1f6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecGet.js @@ -0,0 +1,14 @@ +var classApplyDescriptorGet = require("./classApplyDescriptorGet.js"); + +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); + +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); + +function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} + +module.exports = _classStaticPrivateFieldSpecGet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js new file mode 100644 index 0000000..e6ecfa4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateFieldSpecSet.js @@ -0,0 +1,15 @@ +var classApplyDescriptorSet = require("./classApplyDescriptorSet.js"); + +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); + +var classCheckPrivateStaticFieldDescriptor = require("./classCheckPrivateStaticFieldDescriptor.js"); + +function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} + +module.exports = _classStaticPrivateFieldSpecSet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js new file mode 100644 index 0000000..5bc41fc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodGet.js @@ -0,0 +1,9 @@ +var classCheckPrivateStaticAccess = require("./classCheckPrivateStaticAccess.js"); + +function _classStaticPrivateMethodGet(receiver, classConstructor, method) { + classCheckPrivateStaticAccess(receiver, classConstructor); + return method; +} + +module.exports = _classStaticPrivateMethodGet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js new file mode 100644 index 0000000..06cfcc1 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/classStaticPrivateMethodSet.js @@ -0,0 +1,6 @@ +function _classStaticPrivateMethodSet() { + throw new TypeError("attempted to set read only static private field"); +} + +module.exports = _classStaticPrivateMethodSet; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/construct.js b/node_modules/@babel/runtime/helpers/construct.js new file mode 100644 index 0000000..108b39a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/construct.js @@ -0,0 +1,26 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); + +var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); + +function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + module.exports = _construct = Reflect.construct; + module.exports["default"] = module.exports, module.exports.__esModule = true; + } else { + module.exports = _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } + + return _construct.apply(null, arguments); +} + +module.exports = _construct; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createClass.js b/node_modules/@babel/runtime/helpers/createClass.js new file mode 100644 index 0000000..293bd61 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createClass.js @@ -0,0 +1,18 @@ +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} + +module.exports = _createClass; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js b/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js new file mode 100644 index 0000000..9098865 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createForOfIteratorHelper.js @@ -0,0 +1,61 @@ +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + + if (!it) { + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + + var F = function F() {}; + + return { + s: F, + n: function n() { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function e(_e) { + throw _e; + }, + f: F + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var normalCompletion = true, + didErr = false, + err; + return { + s: function s() { + it = it.call(o); + }, + n: function n() { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function e(_e2) { + didErr = true; + err = _e2; + }, + f: function f() { + try { + if (!normalCompletion && it["return"] != null) it["return"](); + } finally { + if (didErr) throw err; + } + } + }; +} + +module.exports = _createForOfIteratorHelper; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js b/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js new file mode 100644 index 0000000..2dedbc9 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createForOfIteratorHelperLoose.js @@ -0,0 +1,25 @@ +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (it) return (it = it.call(o)).next.bind(it); + + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _createForOfIteratorHelperLoose; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/createSuper.js b/node_modules/@babel/runtime/helpers/createSuper.js new file mode 100644 index 0000000..0acdd51 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/createSuper.js @@ -0,0 +1,25 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); + +var isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); + +var possibleConstructorReturn = require("./possibleConstructorReturn.js"); + +function _createSuper(Derived) { + var hasNativeReflectConstruct = isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = getPrototypeOf(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return possibleConstructorReturn(this, result); + }; +} + +module.exports = _createSuper; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/decorate.js b/node_modules/@babel/runtime/helpers/decorate.js new file mode 100644 index 0000000..80d1751 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/decorate.js @@ -0,0 +1,401 @@ +var toArray = require("./toArray.js"); + +var toPropertyKey = require("./toPropertyKey.js"); + +function _decorate(decorators, factory, superClass, mixins) { + var api = _getDecoratorsApi(); + + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + api = mixins[i](api); + } + } + + var r = factory(function initialize(O) { + api.initializeInstanceElements(O, decorated.elements); + }, superClass); + var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); + api.initializeClassElements(r.F, decorated.elements); + return api.runClassFinishers(r.F, decorated.finishers); +} + +function _getDecoratorsApi() { + _getDecoratorsApi = function _getDecoratorsApi() { + return api; + }; + + var api = { + elementsDefinitionOrder: [["method"], ["field"]], + initializeInstanceElements: function initializeInstanceElements(O, elements) { + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + if (element.kind === kind && element.placement === "own") { + this.defineClassElement(O, element); + } + }, this); + }, this); + }, + initializeClassElements: function initializeClassElements(F, elements) { + var proto = F.prototype; + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + var placement = element.placement; + + if (element.kind === kind && (placement === "static" || placement === "prototype")) { + var receiver = placement === "static" ? F : proto; + this.defineClassElement(receiver, element); + } + }, this); + }, this); + }, + defineClassElement: function defineClassElement(receiver, element) { + var descriptor = element.descriptor; + + if (element.kind === "field") { + var initializer = element.initializer; + descriptor = { + enumerable: descriptor.enumerable, + writable: descriptor.writable, + configurable: descriptor.configurable, + value: initializer === void 0 ? void 0 : initializer.call(receiver) + }; + } + + Object.defineProperty(receiver, element.key, descriptor); + }, + decorateClass: function decorateClass(elements, decorators) { + var newElements = []; + var finishers = []; + var placements = { + "static": [], + prototype: [], + own: [] + }; + elements.forEach(function (element) { + this.addElementPlacement(element, placements); + }, this); + elements.forEach(function (element) { + if (!_hasDecorators(element)) return newElements.push(element); + var elementFinishersExtras = this.decorateElement(element, placements); + newElements.push(elementFinishersExtras.element); + newElements.push.apply(newElements, elementFinishersExtras.extras); + finishers.push.apply(finishers, elementFinishersExtras.finishers); + }, this); + + if (!decorators) { + return { + elements: newElements, + finishers: finishers + }; + } + + var result = this.decorateConstructor(newElements, decorators); + finishers.push.apply(finishers, result.finishers); + result.finishers = finishers; + return result; + }, + addElementPlacement: function addElementPlacement(element, placements, silent) { + var keys = placements[element.placement]; + + if (!silent && keys.indexOf(element.key) !== -1) { + throw new TypeError("Duplicated element (" + element.key + ")"); + } + + keys.push(element.key); + }, + decorateElement: function decorateElement(element, placements) { + var extras = []; + var finishers = []; + + for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { + var keys = placements[element.placement]; + keys.splice(keys.indexOf(element.key), 1); + var elementObject = this.fromElementDescriptor(element); + var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); + element = elementFinisherExtras.element; + this.addElementPlacement(element, placements); + + if (elementFinisherExtras.finisher) { + finishers.push(elementFinisherExtras.finisher); + } + + var newExtras = elementFinisherExtras.extras; + + if (newExtras) { + for (var j = 0; j < newExtras.length; j++) { + this.addElementPlacement(newExtras[j], placements); + } + + extras.push.apply(extras, newExtras); + } + } + + return { + element: element, + finishers: finishers, + extras: extras + }; + }, + decorateConstructor: function decorateConstructor(elements, decorators) { + var finishers = []; + + for (var i = decorators.length - 1; i >= 0; i--) { + var obj = this.fromClassDescriptor(elements); + var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); + + if (elementsAndFinisher.finisher !== undefined) { + finishers.push(elementsAndFinisher.finisher); + } + + if (elementsAndFinisher.elements !== undefined) { + elements = elementsAndFinisher.elements; + + for (var j = 0; j < elements.length - 1; j++) { + for (var k = j + 1; k < elements.length; k++) { + if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { + throw new TypeError("Duplicated element (" + elements[j].key + ")"); + } + } + } + } + } + + return { + elements: elements, + finishers: finishers + }; + }, + fromElementDescriptor: function fromElementDescriptor(element) { + var obj = { + kind: element.kind, + key: element.key, + placement: element.placement, + descriptor: element.descriptor + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + if (element.kind === "field") obj.initializer = element.initializer; + return obj; + }, + toElementDescriptors: function toElementDescriptors(elementObjects) { + if (elementObjects === undefined) return; + return toArray(elementObjects).map(function (elementObject) { + var element = this.toElementDescriptor(elementObject); + this.disallowProperty(elementObject, "finisher", "An element descriptor"); + this.disallowProperty(elementObject, "extras", "An element descriptor"); + return element; + }, this); + }, + toElementDescriptor: function toElementDescriptor(elementObject) { + var kind = String(elementObject.kind); + + if (kind !== "method" && kind !== "field") { + throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); + } + + var key = toPropertyKey(elementObject.key); + var placement = String(elementObject.placement); + + if (placement !== "static" && placement !== "prototype" && placement !== "own") { + throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); + } + + var descriptor = elementObject.descriptor; + this.disallowProperty(elementObject, "elements", "An element descriptor"); + var element = { + kind: kind, + key: key, + placement: placement, + descriptor: Object.assign({}, descriptor) + }; + + if (kind !== "field") { + this.disallowProperty(elementObject, "initializer", "A method descriptor"); + } else { + this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); + element.initializer = elementObject.initializer; + } + + return element; + }, + toElementFinisherExtras: function toElementFinisherExtras(elementObject) { + var element = this.toElementDescriptor(elementObject); + + var finisher = _optionalCallableProperty(elementObject, "finisher"); + + var extras = this.toElementDescriptors(elementObject.extras); + return { + element: element, + finisher: finisher, + extras: extras + }; + }, + fromClassDescriptor: function fromClassDescriptor(elements) { + var obj = { + kind: "class", + elements: elements.map(this.fromElementDescriptor, this) + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + return obj; + }, + toClassDescriptor: function toClassDescriptor(obj) { + var kind = String(obj.kind); + + if (kind !== "class") { + throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); + } + + this.disallowProperty(obj, "key", "A class descriptor"); + this.disallowProperty(obj, "placement", "A class descriptor"); + this.disallowProperty(obj, "descriptor", "A class descriptor"); + this.disallowProperty(obj, "initializer", "A class descriptor"); + this.disallowProperty(obj, "extras", "A class descriptor"); + + var finisher = _optionalCallableProperty(obj, "finisher"); + + var elements = this.toElementDescriptors(obj.elements); + return { + elements: elements, + finisher: finisher + }; + }, + runClassFinishers: function runClassFinishers(constructor, finishers) { + for (var i = 0; i < finishers.length; i++) { + var newConstructor = (0, finishers[i])(constructor); + + if (newConstructor !== undefined) { + if (typeof newConstructor !== "function") { + throw new TypeError("Finishers must return a constructor."); + } + + constructor = newConstructor; + } + } + + return constructor; + }, + disallowProperty: function disallowProperty(obj, name, objectType) { + if (obj[name] !== undefined) { + throw new TypeError(objectType + " can't have a ." + name + " property."); + } + } + }; + return api; +} + +function _createElementDescriptor(def) { + var key = toPropertyKey(def.key); + var descriptor; + + if (def.kind === "method") { + descriptor = { + value: def.value, + writable: true, + configurable: true, + enumerable: false + }; + } else if (def.kind === "get") { + descriptor = { + get: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "set") { + descriptor = { + set: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "field") { + descriptor = { + configurable: true, + writable: true, + enumerable: true + }; + } + + var element = { + kind: def.kind === "field" ? "field" : "method", + key: key, + placement: def["static"] ? "static" : def.kind === "field" ? "own" : "prototype", + descriptor: descriptor + }; + if (def.decorators) element.decorators = def.decorators; + if (def.kind === "field") element.initializer = def.value; + return element; +} + +function _coalesceGetterSetter(element, other) { + if (element.descriptor.get !== undefined) { + other.descriptor.get = element.descriptor.get; + } else { + other.descriptor.set = element.descriptor.set; + } +} + +function _coalesceClassElements(elements) { + var newElements = []; + + var isSameElement = function isSameElement(other) { + return other.kind === "method" && other.key === element.key && other.placement === element.placement; + }; + + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + var other; + + if (element.kind === "method" && (other = newElements.find(isSameElement))) { + if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { + if (_hasDecorators(element) || _hasDecorators(other)) { + throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); + } + + other.descriptor = element.descriptor; + } else { + if (_hasDecorators(element)) { + if (_hasDecorators(other)) { + throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); + } + + other.decorators = element.decorators; + } + + _coalesceGetterSetter(element, other); + } + } else { + newElements.push(element); + } + } + + return newElements; +} + +function _hasDecorators(element) { + return element.decorators && element.decorators.length; +} + +function _isDataDescriptor(desc) { + return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); +} + +function _optionalCallableProperty(obj, name) { + var value = obj[name]; + + if (value !== undefined && typeof value !== "function") { + throw new TypeError("Expected '" + name + "' to be a function"); + } + + return value; +} + +module.exports = _decorate; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defaults.js b/node_modules/@babel/runtime/helpers/defaults.js new file mode 100644 index 0000000..576c5a4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defaults.js @@ -0,0 +1,17 @@ +function _defaults(obj, defaults) { + var keys = Object.getOwnPropertyNames(defaults); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = Object.getOwnPropertyDescriptor(defaults, key); + + if (value && value.configurable && obj[key] === undefined) { + Object.defineProperty(obj, key, value); + } + } + + return obj; +} + +module.exports = _defaults; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js b/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js new file mode 100644 index 0000000..4fe90c3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defineEnumerableProperties.js @@ -0,0 +1,25 @@ +function _defineEnumerableProperties(obj, descs) { + for (var key in descs) { + var desc = descs[key]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, key, desc); + } + + if (Object.getOwnPropertySymbols) { + var objectSymbols = Object.getOwnPropertySymbols(descs); + + for (var i = 0; i < objectSymbols.length; i++) { + var sym = objectSymbols[i]; + var desc = descs[sym]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, sym, desc); + } + } + + return obj; +} + +module.exports = _defineEnumerableProperties; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/defineProperty.js b/node_modules/@babel/runtime/helpers/defineProperty.js new file mode 100644 index 0000000..1cd65ac --- /dev/null +++ b/node_modules/@babel/runtime/helpers/defineProperty.js @@ -0,0 +1,17 @@ +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +module.exports = _defineProperty; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js new file mode 100644 index 0000000..919aab8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/AsyncGenerator.js @@ -0,0 +1,95 @@ +import AwaitValue from "./AwaitValue.js"; +export default function AsyncGenerator(gen) { + var front, back; + + function send(key, arg) { + return new Promise(function (resolve, reject) { + var request = { + key: key, + arg: arg, + resolve: resolve, + reject: reject, + next: null + }; + + if (back) { + back = back.next = request; + } else { + front = back = request; + resume(key, arg); + } + }); + } + + function resume(key, arg) { + try { + var result = gen[key](arg); + var value = result.value; + var wrappedAwait = value instanceof AwaitValue; + Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { + if (wrappedAwait) { + resume(key === "return" ? "return" : "next", arg); + return; + } + + settle(result.done ? "return" : "normal", arg); + }, function (err) { + resume("throw", err); + }); + } catch (err) { + settle("throw", err); + } + } + + function settle(type, value) { + switch (type) { + case "return": + front.resolve({ + value: value, + done: true + }); + break; + + case "throw": + front.reject(value); + break; + + default: + front.resolve({ + value: value, + done: false + }); + break; + } + + front = front.next; + + if (front) { + resume(front.key, front.arg); + } else { + back = null; + } + } + + this._invoke = send; + + if (typeof gen["return"] !== "function") { + this["return"] = undefined; + } +} + +AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () { + return this; +}; + +AsyncGenerator.prototype.next = function (arg) { + return this._invoke("next", arg); +}; + +AsyncGenerator.prototype["throw"] = function (arg) { + return this._invoke("throw", arg); +}; + +AsyncGenerator.prototype["return"] = function (arg) { + return this._invoke("return", arg); +}; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/AwaitValue.js b/node_modules/@babel/runtime/helpers/esm/AwaitValue.js new file mode 100644 index 0000000..5237e18 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/AwaitValue.js @@ -0,0 +1,3 @@ +export default function _AwaitValue(value) { + this.wrapped = value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js b/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js new file mode 100644 index 0000000..84b5961 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/applyDecoratedDescriptor.js @@ -0,0 +1,28 @@ +export default function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { + var desc = {}; + Object.keys(descriptor).forEach(function (key) { + desc[key] = descriptor[key]; + }); + desc.enumerable = !!desc.enumerable; + desc.configurable = !!desc.configurable; + + if ('value' in desc || desc.initializer) { + desc.writable = true; + } + + desc = decorators.slice().reverse().reduce(function (desc, decorator) { + return decorator(target, property, desc) || desc; + }, desc); + + if (context && desc.initializer !== void 0) { + desc.value = desc.initializer ? desc.initializer.call(context) : void 0; + desc.initializer = undefined; + } + + if (desc.initializer === void 0) { + Object.defineProperty(target, property, desc); + desc = null; + } + + return desc; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js b/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js new file mode 100644 index 0000000..edbeb8e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js @@ -0,0 +1,9 @@ +export default function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js b/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js new file mode 100644 index 0000000..be734fc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js @@ -0,0 +1,3 @@ +export default function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js b/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js new file mode 100644 index 0000000..f7d8dc7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js @@ -0,0 +1,4 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js b/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js new file mode 100644 index 0000000..bbf849c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js @@ -0,0 +1,7 @@ +export default function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js b/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js new file mode 100644 index 0000000..a7ccd67 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncGeneratorDelegate.js @@ -0,0 +1,54 @@ +export default function _asyncGeneratorDelegate(inner, awaitWrap) { + var iter = {}, + waiting = false; + + function pump(key, value) { + waiting = true; + value = new Promise(function (resolve) { + resolve(inner[key](value)); + }); + return { + done: false, + value: awaitWrap(value) + }; + } + + ; + + iter[typeof Symbol !== "undefined" && Symbol.iterator || "@@iterator"] = function () { + return this; + }; + + iter.next = function (value) { + if (waiting) { + waiting = false; + return value; + } + + return pump("next", value); + }; + + if (typeof inner["throw"] === "function") { + iter["throw"] = function (value) { + if (waiting) { + waiting = false; + throw value; + } + + return pump("throw", value); + }; + } + + if (typeof inner["return"] === "function") { + iter["return"] = function (value) { + if (waiting) { + waiting = false; + return value; + } + + return pump("return", value); + }; + } + + return iter; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncIterator.js b/node_modules/@babel/runtime/helpers/esm/asyncIterator.js new file mode 100644 index 0000000..91ddb42 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncIterator.js @@ -0,0 +1,13 @@ +export default function _asyncIterator(iterable) { + var method; + + if (typeof Symbol !== "undefined") { + if (Symbol.asyncIterator) method = iterable[Symbol.asyncIterator]; + if (method == null && Symbol.iterator) method = iterable[Symbol.iterator]; + } + + if (method == null) method = iterable["@@asyncIterator"]; + if (method == null) method = iterable["@@iterator"]; + if (method == null) throw new TypeError("Object is not async iterable"); + return method.call(iterable); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js b/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js new file mode 100644 index 0000000..2a25f54 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js @@ -0,0 +1,35 @@ +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } +} + +export default function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js new file mode 100644 index 0000000..ccca65e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/awaitAsyncGenerator.js @@ -0,0 +1,4 @@ +import AwaitValue from "./AwaitValue.js"; +export default function _awaitAsyncGenerator(value) { + return new AwaitValue(value); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js new file mode 100644 index 0000000..4472adc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorDestructureSet.js @@ -0,0 +1,20 @@ +export default function _classApplyDescriptorDestructureSet(receiver, descriptor) { + if (descriptor.set) { + if (!("__destrObj" in descriptor)) { + descriptor.__destrObj = { + set value(v) { + descriptor.set.call(receiver, v); + } + + }; + } + + return descriptor.__destrObj; + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + + return descriptor; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js new file mode 100644 index 0000000..0fad169 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorGet.js @@ -0,0 +1,7 @@ +export default function _classApplyDescriptorGet(receiver, descriptor) { + if (descriptor.get) { + return descriptor.get.call(receiver); + } + + return descriptor.value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js new file mode 100644 index 0000000..f295f3e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classApplyDescriptorSet.js @@ -0,0 +1,11 @@ +export default function _classApplyDescriptorSet(receiver, descriptor, value) { + if (descriptor.set) { + descriptor.set.call(receiver, value); + } else { + if (!descriptor.writable) { + throw new TypeError("attempted to set read only private field"); + } + + descriptor.value = value; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCallCheck.js b/node_modules/@babel/runtime/helpers/esm/classCallCheck.js new file mode 100644 index 0000000..2f1738a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCallCheck.js @@ -0,0 +1,5 @@ +export default function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js new file mode 100644 index 0000000..098ed30 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticAccess.js @@ -0,0 +1,5 @@ +export default function _classCheckPrivateStaticAccess(receiver, classConstructor) { + if (receiver !== classConstructor) { + throw new TypeError("Private static access of wrong provenance"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js new file mode 100644 index 0000000..0ef34b8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classCheckPrivateStaticFieldDescriptor.js @@ -0,0 +1,5 @@ +export default function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { + if (descriptor === undefined) { + throw new TypeError("attempted to " + action + " private static field before its declaration"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js b/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js new file mode 100644 index 0000000..8dabe9a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classExtractFieldDescriptor.js @@ -0,0 +1,7 @@ +export default function _classExtractFieldDescriptor(receiver, privateMap, action) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to " + action + " private field on non-instance"); + } + + return privateMap.get(receiver); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js b/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js new file mode 100644 index 0000000..f7b6dd5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classNameTDZError.js @@ -0,0 +1,3 @@ +export default function _classNameTDZError(name) { + throw new Error("Class \"" + name + "\" cannot be referenced in computed property keys."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js new file mode 100644 index 0000000..fb58833 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldDestructureSet.js @@ -0,0 +1,6 @@ +import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldDestructureSet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js new file mode 100644 index 0000000..53cd137 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldGet.js @@ -0,0 +1,6 @@ +import classApplyDescriptorGet from "./classApplyDescriptorGet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldGet(receiver, privateMap) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js new file mode 100644 index 0000000..5b10916 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseBase.js @@ -0,0 +1,7 @@ +export default function _classPrivateFieldBase(receiver, privateKey) { + if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { + throw new TypeError("attempted to use private field on non-instance"); + } + + return receiver; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js new file mode 100644 index 0000000..5b7e5ac --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldLooseKey.js @@ -0,0 +1,4 @@ +var id = 0; +export default function _classPrivateFieldKey(name) { + return "__private_" + id++ + "_" + name; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js new file mode 100644 index 0000000..ad91be4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateFieldSet.js @@ -0,0 +1,7 @@ +import classApplyDescriptorSet from "./classApplyDescriptorSet.js"; +import classExtractFieldDescriptor from "./classExtractFieldDescriptor.js"; +export default function _classPrivateFieldSet(receiver, privateMap, value) { + var descriptor = classExtractFieldDescriptor(receiver, privateMap, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js new file mode 100644 index 0000000..38b9d58 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodGet.js @@ -0,0 +1,7 @@ +export default function _classPrivateMethodGet(receiver, privateSet, fn) { + if (!privateSet.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + + return fn; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js new file mode 100644 index 0000000..2bbaf3a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classPrivateMethodSet.js @@ -0,0 +1,3 @@ +export default function _classPrivateMethodSet() { + throw new TypeError("attempted to reassign private method"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js new file mode 100644 index 0000000..77afcfb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldDestructureSet.js @@ -0,0 +1,8 @@ +import classApplyDescriptorDestructureSet from "./classApplyDescriptorDestructureSet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldDestructureSet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + return classApplyDescriptorDestructureSet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js new file mode 100644 index 0000000..d253d31 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecGet.js @@ -0,0 +1,8 @@ +import classApplyDescriptorGet from "./classApplyDescriptorGet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "get"); + return classApplyDescriptorGet(receiver, descriptor); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js new file mode 100644 index 0000000..b0b0cc6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateFieldSpecSet.js @@ -0,0 +1,9 @@ +import classApplyDescriptorSet from "./classApplyDescriptorSet.js"; +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +import classCheckPrivateStaticFieldDescriptor from "./classCheckPrivateStaticFieldDescriptor.js"; +export default function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { + classCheckPrivateStaticAccess(receiver, classConstructor); + classCheckPrivateStaticFieldDescriptor(descriptor, "set"); + classApplyDescriptorSet(receiver, descriptor, value); + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js new file mode 100644 index 0000000..fddc7b2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodGet.js @@ -0,0 +1,5 @@ +import classCheckPrivateStaticAccess from "./classCheckPrivateStaticAccess.js"; +export default function _classStaticPrivateMethodGet(receiver, classConstructor, method) { + classCheckPrivateStaticAccess(receiver, classConstructor); + return method; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js new file mode 100644 index 0000000..d5ab60a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/classStaticPrivateMethodSet.js @@ -0,0 +1,3 @@ +export default function _classStaticPrivateMethodSet() { + throw new TypeError("attempted to set read only static private field"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/construct.js b/node_modules/@babel/runtime/helpers/esm/construct.js new file mode 100644 index 0000000..0c39835 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/construct.js @@ -0,0 +1,18 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +import isNativeReflectConstruct from "./isNativeReflectConstruct.js"; +export default function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + _construct = Reflect.construct; + } else { + _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + } + + return _construct.apply(null, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createClass.js b/node_modules/@babel/runtime/helpers/esm/createClass.js new file mode 100644 index 0000000..d6cf412 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createClass.js @@ -0,0 +1,15 @@ +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +export default function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js new file mode 100644 index 0000000..a7a2a50 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelper.js @@ -0,0 +1,57 @@ +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +export default function _createForOfIteratorHelper(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + + if (!it) { + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + + var F = function F() {}; + + return { + s: F, + n: function n() { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }, + e: function e(_e) { + throw _e; + }, + f: F + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var normalCompletion = true, + didErr = false, + err; + return { + s: function s() { + it = it.call(o); + }, + n: function n() { + var step = it.next(); + normalCompletion = step.done; + return step; + }, + e: function e(_e2) { + didErr = true; + err = _e2; + }, + f: function f() { + try { + if (!normalCompletion && it["return"] != null) it["return"](); + } finally { + if (didErr) throw err; + } + } + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js new file mode 100644 index 0000000..640ec68 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createForOfIteratorHelperLoose.js @@ -0,0 +1,21 @@ +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +export default function _createForOfIteratorHelperLoose(o, allowArrayLike) { + var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; + if (it) return (it = it.call(o)).next.bind(it); + + if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { + if (it) o = it; + var i = 0; + return function () { + if (i >= o.length) return { + done: true + }; + return { + done: false, + value: o[i++] + }; + }; + } + + throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/createSuper.js b/node_modules/@babel/runtime/helpers/esm/createSuper.js new file mode 100644 index 0000000..ea5ea99 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/createSuper.js @@ -0,0 +1,19 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +import isNativeReflectConstruct from "./isNativeReflectConstruct.js"; +import possibleConstructorReturn from "./possibleConstructorReturn.js"; +export default function _createSuper(Derived) { + var hasNativeReflectConstruct = isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = getPrototypeOf(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return possibleConstructorReturn(this, result); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/decorate.js b/node_modules/@babel/runtime/helpers/esm/decorate.js new file mode 100644 index 0000000..daf56da --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/decorate.js @@ -0,0 +1,396 @@ +import toArray from "./toArray.js"; +import toPropertyKey from "./toPropertyKey.js"; +export default function _decorate(decorators, factory, superClass, mixins) { + var api = _getDecoratorsApi(); + + if (mixins) { + for (var i = 0; i < mixins.length; i++) { + api = mixins[i](api); + } + } + + var r = factory(function initialize(O) { + api.initializeInstanceElements(O, decorated.elements); + }, superClass); + var decorated = api.decorateClass(_coalesceClassElements(r.d.map(_createElementDescriptor)), decorators); + api.initializeClassElements(r.F, decorated.elements); + return api.runClassFinishers(r.F, decorated.finishers); +} + +function _getDecoratorsApi() { + _getDecoratorsApi = function _getDecoratorsApi() { + return api; + }; + + var api = { + elementsDefinitionOrder: [["method"], ["field"]], + initializeInstanceElements: function initializeInstanceElements(O, elements) { + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + if (element.kind === kind && element.placement === "own") { + this.defineClassElement(O, element); + } + }, this); + }, this); + }, + initializeClassElements: function initializeClassElements(F, elements) { + var proto = F.prototype; + ["method", "field"].forEach(function (kind) { + elements.forEach(function (element) { + var placement = element.placement; + + if (element.kind === kind && (placement === "static" || placement === "prototype")) { + var receiver = placement === "static" ? F : proto; + this.defineClassElement(receiver, element); + } + }, this); + }, this); + }, + defineClassElement: function defineClassElement(receiver, element) { + var descriptor = element.descriptor; + + if (element.kind === "field") { + var initializer = element.initializer; + descriptor = { + enumerable: descriptor.enumerable, + writable: descriptor.writable, + configurable: descriptor.configurable, + value: initializer === void 0 ? void 0 : initializer.call(receiver) + }; + } + + Object.defineProperty(receiver, element.key, descriptor); + }, + decorateClass: function decorateClass(elements, decorators) { + var newElements = []; + var finishers = []; + var placements = { + "static": [], + prototype: [], + own: [] + }; + elements.forEach(function (element) { + this.addElementPlacement(element, placements); + }, this); + elements.forEach(function (element) { + if (!_hasDecorators(element)) return newElements.push(element); + var elementFinishersExtras = this.decorateElement(element, placements); + newElements.push(elementFinishersExtras.element); + newElements.push.apply(newElements, elementFinishersExtras.extras); + finishers.push.apply(finishers, elementFinishersExtras.finishers); + }, this); + + if (!decorators) { + return { + elements: newElements, + finishers: finishers + }; + } + + var result = this.decorateConstructor(newElements, decorators); + finishers.push.apply(finishers, result.finishers); + result.finishers = finishers; + return result; + }, + addElementPlacement: function addElementPlacement(element, placements, silent) { + var keys = placements[element.placement]; + + if (!silent && keys.indexOf(element.key) !== -1) { + throw new TypeError("Duplicated element (" + element.key + ")"); + } + + keys.push(element.key); + }, + decorateElement: function decorateElement(element, placements) { + var extras = []; + var finishers = []; + + for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) { + var keys = placements[element.placement]; + keys.splice(keys.indexOf(element.key), 1); + var elementObject = this.fromElementDescriptor(element); + var elementFinisherExtras = this.toElementFinisherExtras((0, decorators[i])(elementObject) || elementObject); + element = elementFinisherExtras.element; + this.addElementPlacement(element, placements); + + if (elementFinisherExtras.finisher) { + finishers.push(elementFinisherExtras.finisher); + } + + var newExtras = elementFinisherExtras.extras; + + if (newExtras) { + for (var j = 0; j < newExtras.length; j++) { + this.addElementPlacement(newExtras[j], placements); + } + + extras.push.apply(extras, newExtras); + } + } + + return { + element: element, + finishers: finishers, + extras: extras + }; + }, + decorateConstructor: function decorateConstructor(elements, decorators) { + var finishers = []; + + for (var i = decorators.length - 1; i >= 0; i--) { + var obj = this.fromClassDescriptor(elements); + var elementsAndFinisher = this.toClassDescriptor((0, decorators[i])(obj) || obj); + + if (elementsAndFinisher.finisher !== undefined) { + finishers.push(elementsAndFinisher.finisher); + } + + if (elementsAndFinisher.elements !== undefined) { + elements = elementsAndFinisher.elements; + + for (var j = 0; j < elements.length - 1; j++) { + for (var k = j + 1; k < elements.length; k++) { + if (elements[j].key === elements[k].key && elements[j].placement === elements[k].placement) { + throw new TypeError("Duplicated element (" + elements[j].key + ")"); + } + } + } + } + } + + return { + elements: elements, + finishers: finishers + }; + }, + fromElementDescriptor: function fromElementDescriptor(element) { + var obj = { + kind: element.kind, + key: element.key, + placement: element.placement, + descriptor: element.descriptor + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + if (element.kind === "field") obj.initializer = element.initializer; + return obj; + }, + toElementDescriptors: function toElementDescriptors(elementObjects) { + if (elementObjects === undefined) return; + return toArray(elementObjects).map(function (elementObject) { + var element = this.toElementDescriptor(elementObject); + this.disallowProperty(elementObject, "finisher", "An element descriptor"); + this.disallowProperty(elementObject, "extras", "An element descriptor"); + return element; + }, this); + }, + toElementDescriptor: function toElementDescriptor(elementObject) { + var kind = String(elementObject.kind); + + if (kind !== "method" && kind !== "field") { + throw new TypeError('An element descriptor\'s .kind property must be either "method" or' + ' "field", but a decorator created an element descriptor with' + ' .kind "' + kind + '"'); + } + + var key = toPropertyKey(elementObject.key); + var placement = String(elementObject.placement); + + if (placement !== "static" && placement !== "prototype" && placement !== "own") { + throw new TypeError('An element descriptor\'s .placement property must be one of "static",' + ' "prototype" or "own", but a decorator created an element descriptor' + ' with .placement "' + placement + '"'); + } + + var descriptor = elementObject.descriptor; + this.disallowProperty(elementObject, "elements", "An element descriptor"); + var element = { + kind: kind, + key: key, + placement: placement, + descriptor: Object.assign({}, descriptor) + }; + + if (kind !== "field") { + this.disallowProperty(elementObject, "initializer", "A method descriptor"); + } else { + this.disallowProperty(descriptor, "get", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "set", "The property descriptor of a field descriptor"); + this.disallowProperty(descriptor, "value", "The property descriptor of a field descriptor"); + element.initializer = elementObject.initializer; + } + + return element; + }, + toElementFinisherExtras: function toElementFinisherExtras(elementObject) { + var element = this.toElementDescriptor(elementObject); + + var finisher = _optionalCallableProperty(elementObject, "finisher"); + + var extras = this.toElementDescriptors(elementObject.extras); + return { + element: element, + finisher: finisher, + extras: extras + }; + }, + fromClassDescriptor: function fromClassDescriptor(elements) { + var obj = { + kind: "class", + elements: elements.map(this.fromElementDescriptor, this) + }; + var desc = { + value: "Descriptor", + configurable: true + }; + Object.defineProperty(obj, Symbol.toStringTag, desc); + return obj; + }, + toClassDescriptor: function toClassDescriptor(obj) { + var kind = String(obj.kind); + + if (kind !== "class") { + throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator' + ' created a class descriptor with .kind "' + kind + '"'); + } + + this.disallowProperty(obj, "key", "A class descriptor"); + this.disallowProperty(obj, "placement", "A class descriptor"); + this.disallowProperty(obj, "descriptor", "A class descriptor"); + this.disallowProperty(obj, "initializer", "A class descriptor"); + this.disallowProperty(obj, "extras", "A class descriptor"); + + var finisher = _optionalCallableProperty(obj, "finisher"); + + var elements = this.toElementDescriptors(obj.elements); + return { + elements: elements, + finisher: finisher + }; + }, + runClassFinishers: function runClassFinishers(constructor, finishers) { + for (var i = 0; i < finishers.length; i++) { + var newConstructor = (0, finishers[i])(constructor); + + if (newConstructor !== undefined) { + if (typeof newConstructor !== "function") { + throw new TypeError("Finishers must return a constructor."); + } + + constructor = newConstructor; + } + } + + return constructor; + }, + disallowProperty: function disallowProperty(obj, name, objectType) { + if (obj[name] !== undefined) { + throw new TypeError(objectType + " can't have a ." + name + " property."); + } + } + }; + return api; +} + +function _createElementDescriptor(def) { + var key = toPropertyKey(def.key); + var descriptor; + + if (def.kind === "method") { + descriptor = { + value: def.value, + writable: true, + configurable: true, + enumerable: false + }; + } else if (def.kind === "get") { + descriptor = { + get: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "set") { + descriptor = { + set: def.value, + configurable: true, + enumerable: false + }; + } else if (def.kind === "field") { + descriptor = { + configurable: true, + writable: true, + enumerable: true + }; + } + + var element = { + kind: def.kind === "field" ? "field" : "method", + key: key, + placement: def["static"] ? "static" : def.kind === "field" ? "own" : "prototype", + descriptor: descriptor + }; + if (def.decorators) element.decorators = def.decorators; + if (def.kind === "field") element.initializer = def.value; + return element; +} + +function _coalesceGetterSetter(element, other) { + if (element.descriptor.get !== undefined) { + other.descriptor.get = element.descriptor.get; + } else { + other.descriptor.set = element.descriptor.set; + } +} + +function _coalesceClassElements(elements) { + var newElements = []; + + var isSameElement = function isSameElement(other) { + return other.kind === "method" && other.key === element.key && other.placement === element.placement; + }; + + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + var other; + + if (element.kind === "method" && (other = newElements.find(isSameElement))) { + if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) { + if (_hasDecorators(element) || _hasDecorators(other)) { + throw new ReferenceError("Duplicated methods (" + element.key + ") can't be decorated."); + } + + other.descriptor = element.descriptor; + } else { + if (_hasDecorators(element)) { + if (_hasDecorators(other)) { + throw new ReferenceError("Decorators can't be placed on different accessors with for " + "the same property (" + element.key + ")."); + } + + other.decorators = element.decorators; + } + + _coalesceGetterSetter(element, other); + } + } else { + newElements.push(element); + } + } + + return newElements; +} + +function _hasDecorators(element) { + return element.decorators && element.decorators.length; +} + +function _isDataDescriptor(desc) { + return desc !== undefined && !(desc.value === undefined && desc.writable === undefined); +} + +function _optionalCallableProperty(obj, name) { + var value = obj[name]; + + if (value !== undefined && typeof value !== "function") { + throw new TypeError("Expected '" + name + "' to be a function"); + } + + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defaults.js b/node_modules/@babel/runtime/helpers/esm/defaults.js new file mode 100644 index 0000000..3de1d8e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defaults.js @@ -0,0 +1,14 @@ +export default function _defaults(obj, defaults) { + var keys = Object.getOwnPropertyNames(defaults); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = Object.getOwnPropertyDescriptor(defaults, key); + + if (value && value.configurable && obj[key] === undefined) { + Object.defineProperty(obj, key, value); + } + } + + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js b/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js new file mode 100644 index 0000000..7981acd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defineEnumerableProperties.js @@ -0,0 +1,22 @@ +export default function _defineEnumerableProperties(obj, descs) { + for (var key in descs) { + var desc = descs[key]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, key, desc); + } + + if (Object.getOwnPropertySymbols) { + var objectSymbols = Object.getOwnPropertySymbols(descs); + + for (var i = 0; i < objectSymbols.length; i++) { + var sym = objectSymbols[i]; + var desc = descs[sym]; + desc.configurable = desc.enumerable = true; + if ("value" in desc) desc.writable = true; + Object.defineProperty(obj, sym, desc); + } + } + + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/defineProperty.js b/node_modules/@babel/runtime/helpers/esm/defineProperty.js new file mode 100644 index 0000000..7cf6e59 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/defineProperty.js @@ -0,0 +1,14 @@ +export default function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/extends.js b/node_modules/@babel/runtime/helpers/esm/extends.js new file mode 100644 index 0000000..b9b138d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/extends.js @@ -0,0 +1,17 @@ +export default function _extends() { + _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + return _extends.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/get.js b/node_modules/@babel/runtime/helpers/esm/get.js new file mode 100644 index 0000000..1bce020 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/get.js @@ -0,0 +1,20 @@ +import superPropBase from "./superPropBase.js"; +export default function _get(target, property, receiver) { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(receiver); + } + + return desc.value; + }; + } + + return _get(target, property, receiver || target); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js b/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js new file mode 100644 index 0000000..5abafe3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js @@ -0,0 +1,6 @@ +export default function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/inherits.js b/node_modules/@babel/runtime/helpers/esm/inherits.js new file mode 100644 index 0000000..aee0f10 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/inherits.js @@ -0,0 +1,15 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +export default function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) setPrototypeOf(subClass, superClass); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js b/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js new file mode 100644 index 0000000..90bb796 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js @@ -0,0 +1,6 @@ +import setPrototypeOf from "./setPrototypeOf.js"; +export default function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + setPrototypeOf(subClass, superClass); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js b/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js new file mode 100644 index 0000000..26fdea0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/initializerDefineProperty.js @@ -0,0 +1,9 @@ +export default function _initializerDefineProperty(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js b/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js new file mode 100644 index 0000000..30d518c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/initializerWarningHelper.js @@ -0,0 +1,3 @@ +export default function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/instanceof.js b/node_modules/@babel/runtime/helpers/esm/instanceof.js new file mode 100644 index 0000000..8c43b71 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/instanceof.js @@ -0,0 +1,7 @@ +export default function _instanceof(left, right) { + if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { + return !!right[Symbol.hasInstance](left); + } else { + return left instanceof right; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js b/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js new file mode 100644 index 0000000..c2df7b6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/interopRequireDefault.js @@ -0,0 +1,5 @@ +export default function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js b/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js new file mode 100644 index 0000000..662ff7e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/interopRequireWildcard.js @@ -0,0 +1,51 @@ +import _typeof from "@babel/runtime/helpers/typeof"; + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +export default function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + + if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { + return { + "default": obj + }; + } + + var cache = _getRequireWildcardCache(nodeInterop); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + + newObj["default"] = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js b/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js new file mode 100644 index 0000000..7b1bc82 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/isNativeFunction.js @@ -0,0 +1,3 @@ +export default function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js b/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js new file mode 100644 index 0000000..0da1624 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js @@ -0,0 +1,12 @@ +export default function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArray.js b/node_modules/@babel/runtime/helpers/esm/iterableToArray.js new file mode 100644 index 0000000..cfe9fbd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArray.js @@ -0,0 +1,3 @@ +export default function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js new file mode 100644 index 0000000..c72ca94 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js @@ -0,0 +1,29 @@ +export default function _iterableToArrayLimit(arr, i) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; + + if (_i == null) return; + var _arr = []; + var _n = true; + var _d = false; + + var _s, _e; + + try { + for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js new file mode 100644 index 0000000..27c15e0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimitLoose.js @@ -0,0 +1,14 @@ +export default function _iterableToArrayLimitLoose(arr, i) { + var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); + + if (_i == null) return; + var _arr = []; + + for (_i = _i.call(arr), _step; !(_step = _i.next()).done;) { + _arr.push(_step.value); + + if (i && _arr.length === i) break; + } + + return _arr; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/jsx.js b/node_modules/@babel/runtime/helpers/esm/jsx.js new file mode 100644 index 0000000..328fadf --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/jsx.js @@ -0,0 +1,46 @@ +var REACT_ELEMENT_TYPE; +export default function _createRawReactElement(type, props, key, children) { + if (!REACT_ELEMENT_TYPE) { + REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; + } + + var defaultProps = type && type.defaultProps; + var childrenLength = arguments.length - 3; + + if (!props && childrenLength !== 0) { + props = { + children: void 0 + }; + } + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = new Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 3]; + } + + props.children = childArray; + } + + if (props && defaultProps) { + for (var propName in defaultProps) { + if (props[propName] === void 0) { + props[propName] = defaultProps[propName]; + } + } + } else if (!props) { + props = defaultProps || {}; + } + + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key === undefined ? null : "" + key, + ref: null, + props: props, + _owner: null + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js b/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js new file mode 100644 index 0000000..f687959 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/maybeArrayLike.js @@ -0,0 +1,9 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _maybeArrayLike(next, arr, i) { + if (arr && !Array.isArray(arr) && typeof arr.length === "number") { + var len = arr.length; + return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); + } + + return next(arr, i); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js b/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js new file mode 100644 index 0000000..d6cd864 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/newArrowCheck.js @@ -0,0 +1,5 @@ +export default function _newArrowCheck(innerThis, boundThis) { + if (innerThis !== boundThis) { + throw new TypeError("Cannot instantiate an arrow function"); + } +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js b/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js new file mode 100644 index 0000000..b349d00 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js @@ -0,0 +1,3 @@ +export default function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js b/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js new file mode 100644 index 0000000..82d8296 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js @@ -0,0 +1,3 @@ +export default function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js b/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js new file mode 100644 index 0000000..82b67d2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectDestructuringEmpty.js @@ -0,0 +1,3 @@ +export default function _objectDestructuringEmpty(obj) { + if (obj == null) throw new TypeError("Cannot destructure undefined"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectSpread.js b/node_modules/@babel/runtime/helpers/esm/objectSpread.js new file mode 100644 index 0000000..8c38ca7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectSpread.js @@ -0,0 +1,19 @@ +import defineProperty from "./defineProperty.js"; +export default function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? Object(arguments[i]) : {}; + var ownKeys = Object.keys(source); + + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + + ownKeys.forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectSpread2.js b/node_modules/@babel/runtime/helpers/esm/objectSpread2.js new file mode 100644 index 0000000..be42b4d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectSpread2.js @@ -0,0 +1,39 @@ +import defineProperty from "./defineProperty.js"; + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + + keys.push.apply(keys, symbols); + } + + return keys; +} + +export default function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js b/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js new file mode 100644 index 0000000..0fef321 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js @@ -0,0 +1,19 @@ +import objectWithoutPropertiesLoose from "./objectWithoutPropertiesLoose.js"; +export default function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = objectWithoutPropertiesLoose(source, excluded); + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js b/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js new file mode 100644 index 0000000..c36815c --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js @@ -0,0 +1,14 @@ +export default function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/package.json b/node_modules/@babel/runtime/helpers/esm/package.json new file mode 100644 index 0000000..aead43d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js b/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js new file mode 100644 index 0000000..8566e11 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js @@ -0,0 +1,11 @@ +import _typeof from "@babel/runtime/helpers/typeof"; +import assertThisInitialized from "./assertThisInitialized.js"; +export default function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + + return assertThisInitialized(self); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/readOnlyError.js b/node_modules/@babel/runtime/helpers/esm/readOnlyError.js new file mode 100644 index 0000000..166e40e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/readOnlyError.js @@ -0,0 +1,3 @@ +export default function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/set.js b/node_modules/@babel/runtime/helpers/esm/set.js new file mode 100644 index 0000000..9c54773 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/set.js @@ -0,0 +1,51 @@ +import superPropBase from "./superPropBase.js"; +import defineProperty from "./defineProperty.js"; + +function set(target, property, value, receiver) { + if (typeof Reflect !== "undefined" && Reflect.set) { + set = Reflect.set; + } else { + set = function set(target, property, value, receiver) { + var base = superPropBase(target, property); + var desc; + + if (base) { + desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.set) { + desc.set.call(receiver, value); + return true; + } else if (!desc.writable) { + return false; + } + } + + desc = Object.getOwnPropertyDescriptor(receiver, property); + + if (desc) { + if (!desc.writable) { + return false; + } + + desc.value = value; + Object.defineProperty(receiver, property, desc); + } else { + defineProperty(receiver, property, value); + } + + return true; + }; + } + + return set(target, property, value, receiver); +} + +export default function _set(target, property, value, receiver, isStrict) { + var s = set(target, property, value, receiver || target); + + if (!s && isStrict) { + throw new Error('failed to set property'); + } + + return value; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js b/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js new file mode 100644 index 0000000..e6ef03e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js @@ -0,0 +1,8 @@ +export default function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js b/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js new file mode 100644 index 0000000..cadd9bb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/skipFirstGeneratorNext.js @@ -0,0 +1,7 @@ +export default function _skipFirstGeneratorNext(fn) { + return function () { + var it = fn.apply(this, arguments); + it.next(); + return it; + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/slicedToArray.js b/node_modules/@babel/runtime/helpers/esm/slicedToArray.js new file mode 100644 index 0000000..618200b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/slicedToArray.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArrayLimit from "./iterableToArrayLimit.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js b/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js new file mode 100644 index 0000000..efc7429 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/slicedToArrayLoose.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArrayLimitLoose from "./iterableToArrayLimitLoose.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _slicedToArrayLoose(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/superPropBase.js b/node_modules/@babel/runtime/helpers/esm/superPropBase.js new file mode 100644 index 0000000..feffe6f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/superPropBase.js @@ -0,0 +1,9 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +export default function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + + return object; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js new file mode 100644 index 0000000..421f18a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js @@ -0,0 +1,11 @@ +export default function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js new file mode 100644 index 0000000..c8f081e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteralLoose.js @@ -0,0 +1,8 @@ +export default function _taggedTemplateLiteralLoose(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + strings.raw = raw; + return strings; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/tdz.js b/node_modules/@babel/runtime/helpers/esm/tdz.js new file mode 100644 index 0000000..d5d0adc --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/tdz.js @@ -0,0 +1,3 @@ +export default function _tdzError(name) { + throw new ReferenceError(name + " is not defined - temporal dead zone"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/temporalRef.js b/node_modules/@babel/runtime/helpers/esm/temporalRef.js new file mode 100644 index 0000000..b25f7c4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/temporalRef.js @@ -0,0 +1,5 @@ +import undef from "./temporalUndefined.js"; +import err from "./tdz.js"; +export default function _temporalRef(val, name) { + return val === undef ? err(name) : val; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js b/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js new file mode 100644 index 0000000..1a35717 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/temporalUndefined.js @@ -0,0 +1 @@ +export default function _temporalUndefined() {} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toArray.js b/node_modules/@babel/runtime/helpers/esm/toArray.js new file mode 100644 index 0000000..ad7c871 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toArray.js @@ -0,0 +1,7 @@ +import arrayWithHoles from "./arrayWithHoles.js"; +import iterableToArray from "./iterableToArray.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableRest from "./nonIterableRest.js"; +export default function _toArray(arr) { + return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js b/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js new file mode 100644 index 0000000..bd91285 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js @@ -0,0 +1,7 @@ +import arrayWithoutHoles from "./arrayWithoutHoles.js"; +import iterableToArray from "./iterableToArray.js"; +import unsupportedIterableToArray from "./unsupportedIterableToArray.js"; +import nonIterableSpread from "./nonIterableSpread.js"; +export default function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toPrimitive.js b/node_modules/@babel/runtime/helpers/esm/toPrimitive.js new file mode 100644 index 0000000..4cb70a5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toPrimitive.js @@ -0,0 +1,13 @@ +import _typeof from "@babel/runtime/helpers/typeof"; +export default function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + + return (hint === "string" ? String : Number)(input); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js b/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js new file mode 100644 index 0000000..f1ba8a2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js @@ -0,0 +1,6 @@ +import _typeof from "@babel/runtime/helpers/typeof"; +import toPrimitive from "./toPrimitive.js"; +export default function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/typeof.js b/node_modules/@babel/runtime/helpers/esm/typeof.js new file mode 100644 index 0000000..eb444f7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/typeof.js @@ -0,0 +1,15 @@ +export default function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function _typeof(obj) { + return typeof obj; + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js b/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js new file mode 100644 index 0000000..c0f63bd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js @@ -0,0 +1,9 @@ +import arrayLikeToArray from "./arrayLikeToArray.js"; +export default function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js b/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js new file mode 100644 index 0000000..723b2dd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapAsyncGenerator.js @@ -0,0 +1,6 @@ +import AsyncGenerator from "./AsyncGenerator.js"; +export default function _wrapAsyncGenerator(fn) { + return function () { + return new AsyncGenerator(fn.apply(this, arguments)); + }; +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js b/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js new file mode 100644 index 0000000..512630d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapNativeSuper.js @@ -0,0 +1,37 @@ +import getPrototypeOf from "./getPrototypeOf.js"; +import setPrototypeOf from "./setPrototypeOf.js"; +import isNativeFunction from "./isNativeFunction.js"; +import construct from "./construct.js"; +export default function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }; + + return _wrapNativeSuper(Class); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js b/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js new file mode 100644 index 0000000..4d65336 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/wrapRegExp.js @@ -0,0 +1,65 @@ +import _typeof from "@babel/runtime/helpers/typeof"; +import setPrototypeOf from "./setPrototypeOf.js"; +import inherits from "./inherits.js"; +export default function _wrapRegExp() { + _wrapRegExp = function _wrapRegExp(re, groups) { + return new BabelRegExp(re, undefined, groups); + }; + + var _super = RegExp.prototype; + + var _groups = new WeakMap(); + + function BabelRegExp(re, flags, groups) { + var _this = new RegExp(re, flags); + + _groups.set(_this, groups || _groups.get(re)); + + return setPrototypeOf(_this, BabelRegExp.prototype); + } + + inherits(BabelRegExp, RegExp); + + BabelRegExp.prototype.exec = function (str) { + var result = _super.exec.call(this, str); + + if (result) result.groups = buildGroups(result, this); + return result; + }; + + BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { + if (typeof substitution === "string") { + var groups = _groups.get(this); + + return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { + return "$" + groups[name]; + })); + } else if (typeof substitution === "function") { + var _this = this; + + return _super[Symbol.replace].call(this, str, function () { + var args = arguments; + + if (_typeof(args[args.length - 1]) !== "object") { + args = [].slice.call(args); + args.push(buildGroups(args, _this)); + } + + return substitution.apply(this, args); + }); + } else { + return _super[Symbol.replace].call(this, str, substitution); + } + }; + + function buildGroups(result, re) { + var g = _groups.get(re); + + return Object.keys(g).reduce(function (groups, name) { + groups[name] = result[g[name]]; + return groups; + }, Object.create(null)); + } + + return _wrapRegExp.apply(this, arguments); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js b/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js new file mode 100644 index 0000000..9170bd4 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/esm/writeOnlyError.js @@ -0,0 +1,3 @@ +export default function _writeOnlyError(name) { + throw new TypeError("\"" + name + "\" is write-only"); +} \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/extends.js b/node_modules/@babel/runtime/helpers/extends.js new file mode 100644 index 0000000..eaf9547 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/extends.js @@ -0,0 +1,21 @@ +function _extends() { + module.exports = _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _extends.apply(this, arguments); +} + +module.exports = _extends; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/get.js b/node_modules/@babel/runtime/helpers/get.js new file mode 100644 index 0000000..3ed600f --- /dev/null +++ b/node_modules/@babel/runtime/helpers/get.js @@ -0,0 +1,27 @@ +var superPropBase = require("./superPropBase.js"); + +function _get(target, property, receiver) { + if (typeof Reflect !== "undefined" && Reflect.get) { + module.exports = _get = Reflect.get; + module.exports["default"] = module.exports, module.exports.__esModule = true; + } else { + module.exports = _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(receiver); + } + + return desc.value; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } + + return _get(target, property, receiver || target); +} + +module.exports = _get; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/getPrototypeOf.js b/node_modules/@babel/runtime/helpers/getPrototypeOf.js new file mode 100644 index 0000000..a6916eb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/getPrototypeOf.js @@ -0,0 +1,10 @@ +function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _getPrototypeOf(o); +} + +module.exports = _getPrototypeOf; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/inherits.js b/node_modules/@babel/runtime/helpers/inherits.js new file mode 100644 index 0000000..3003e01 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/inherits.js @@ -0,0 +1,19 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); + +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) setPrototypeOf(subClass, superClass); +} + +module.exports = _inherits; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/inheritsLoose.js b/node_modules/@babel/runtime/helpers/inheritsLoose.js new file mode 100644 index 0000000..93e4305 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/inheritsLoose.js @@ -0,0 +1,10 @@ +var setPrototypeOf = require("./setPrototypeOf.js"); + +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + setPrototypeOf(subClass, superClass); +} + +module.exports = _inheritsLoose; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/initializerDefineProperty.js b/node_modules/@babel/runtime/helpers/initializerDefineProperty.js new file mode 100644 index 0000000..6b1069e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/initializerDefineProperty.js @@ -0,0 +1,12 @@ +function _initializerDefineProperty(target, property, descriptor, context) { + if (!descriptor) return; + Object.defineProperty(target, property, { + enumerable: descriptor.enumerable, + configurable: descriptor.configurable, + writable: descriptor.writable, + value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 + }); +} + +module.exports = _initializerDefineProperty; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/initializerWarningHelper.js b/node_modules/@babel/runtime/helpers/initializerWarningHelper.js new file mode 100644 index 0000000..9d02886 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/initializerWarningHelper.js @@ -0,0 +1,6 @@ +function _initializerWarningHelper(descriptor, context) { + throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and runs after the decorators transform.'); +} + +module.exports = _initializerWarningHelper; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/instanceof.js b/node_modules/@babel/runtime/helpers/instanceof.js new file mode 100644 index 0000000..654ebc8 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/instanceof.js @@ -0,0 +1,10 @@ +function _instanceof(left, right) { + if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { + return !!right[Symbol.hasInstance](left); + } else { + return left instanceof right; + } +} + +module.exports = _instanceof; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/interopRequireDefault.js b/node_modules/@babel/runtime/helpers/interopRequireDefault.js new file mode 100644 index 0000000..6a21368 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/interopRequireDefault.js @@ -0,0 +1,8 @@ +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} + +module.exports = _interopRequireDefault; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/interopRequireWildcard.js b/node_modules/@babel/runtime/helpers/interopRequireWildcard.js new file mode 100644 index 0000000..635f8bb --- /dev/null +++ b/node_modules/@babel/runtime/helpers/interopRequireWildcard.js @@ -0,0 +1,54 @@ +var _typeof = require("@babel/runtime/helpers/typeof")["default"]; + +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} + +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + + if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { + return { + "default": obj + }; + } + + var cache = _getRequireWildcardCache(nodeInterop); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + + newObj["default"] = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; +} + +module.exports = _interopRequireWildcard; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/isNativeFunction.js b/node_modules/@babel/runtime/helpers/isNativeFunction.js new file mode 100644 index 0000000..50eb8f5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/isNativeFunction.js @@ -0,0 +1,6 @@ +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} + +module.exports = _isNativeFunction; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js b/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js new file mode 100644 index 0000000..3a201a6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js @@ -0,0 +1,15 @@ +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +module.exports = _isNativeReflectConstruct; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArray.js b/node_modules/@babel/runtime/helpers/iterableToArray.js new file mode 100644 index 0000000..03f955d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArray.js @@ -0,0 +1,6 @@ +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} + +module.exports = _iterableToArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js b/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js new file mode 100644 index 0000000..da9cee0 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArrayLimit.js @@ -0,0 +1,32 @@ +function _iterableToArrayLimit(arr, i) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; + + if (_i == null) return; + var _arr = []; + var _n = true; + var _d = false; + + var _s, _e; + + try { + for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} + +module.exports = _iterableToArrayLimit; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js b/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js new file mode 100644 index 0000000..fb05b12 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js @@ -0,0 +1,17 @@ +function _iterableToArrayLimitLoose(arr, i) { + var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); + + if (_i == null) return; + var _arr = []; + + for (_i = _i.call(arr), _step; !(_step = _i.next()).done;) { + _arr.push(_step.value); + + if (i && _arr.length === i) break; + } + + return _arr; +} + +module.exports = _iterableToArrayLimitLoose; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/jsx.js b/node_modules/@babel/runtime/helpers/jsx.js new file mode 100644 index 0000000..21ac847 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/jsx.js @@ -0,0 +1,50 @@ +var REACT_ELEMENT_TYPE; + +function _createRawReactElement(type, props, key, children) { + if (!REACT_ELEMENT_TYPE) { + REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol["for"] && Symbol["for"]("react.element") || 0xeac7; + } + + var defaultProps = type && type.defaultProps; + var childrenLength = arguments.length - 3; + + if (!props && childrenLength !== 0) { + props = { + children: void 0 + }; + } + + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = new Array(childrenLength); + + for (var i = 0; i < childrenLength; i++) { + childArray[i] = arguments[i + 3]; + } + + props.children = childArray; + } + + if (props && defaultProps) { + for (var propName in defaultProps) { + if (props[propName] === void 0) { + props[propName] = defaultProps[propName]; + } + } + } else if (!props) { + props = defaultProps || {}; + } + + return { + $$typeof: REACT_ELEMENT_TYPE, + type: type, + key: key === undefined ? null : "" + key, + ref: null, + props: props, + _owner: null + }; +} + +module.exports = _createRawReactElement; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/maybeArrayLike.js b/node_modules/@babel/runtime/helpers/maybeArrayLike.js new file mode 100644 index 0000000..3ab618b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/maybeArrayLike.js @@ -0,0 +1,13 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); + +function _maybeArrayLike(next, arr, i) { + if (arr && !Array.isArray(arr) && typeof arr.length === "number") { + var len = arr.length; + return arrayLikeToArray(arr, i !== void 0 && i < len ? i : len); + } + + return next(arr, i); +} + +module.exports = _maybeArrayLike; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/newArrowCheck.js b/node_modules/@babel/runtime/helpers/newArrowCheck.js new file mode 100644 index 0000000..8d7570b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/newArrowCheck.js @@ -0,0 +1,8 @@ +function _newArrowCheck(innerThis, boundThis) { + if (innerThis !== boundThis) { + throw new TypeError("Cannot instantiate an arrow function"); + } +} + +module.exports = _newArrowCheck; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/nonIterableRest.js b/node_modules/@babel/runtime/helpers/nonIterableRest.js new file mode 100644 index 0000000..22be4f5 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/nonIterableRest.js @@ -0,0 +1,6 @@ +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _nonIterableRest; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/nonIterableSpread.js b/node_modules/@babel/runtime/helpers/nonIterableSpread.js new file mode 100644 index 0000000..4ba722d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/nonIterableSpread.js @@ -0,0 +1,6 @@ +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _nonIterableSpread; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js b/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js new file mode 100644 index 0000000..1bb88ac --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectDestructuringEmpty.js @@ -0,0 +1,6 @@ +function _objectDestructuringEmpty(obj) { + if (obj == null) throw new TypeError("Cannot destructure undefined"); +} + +module.exports = _objectDestructuringEmpty; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectSpread.js b/node_modules/@babel/runtime/helpers/objectSpread.js new file mode 100644 index 0000000..00af209 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectSpread.js @@ -0,0 +1,23 @@ +var defineProperty = require("./defineProperty.js"); + +function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? Object(arguments[i]) : {}; + var ownKeys = Object.keys(source); + + if (typeof Object.getOwnPropertySymbols === 'function') { + ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { + return Object.getOwnPropertyDescriptor(source, sym).enumerable; + })); + } + + ownKeys.forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } + + return target; +} + +module.exports = _objectSpread; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectSpread2.js b/node_modules/@babel/runtime/helpers/objectSpread2.js new file mode 100644 index 0000000..337d30e --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectSpread2.js @@ -0,0 +1,42 @@ +var defineProperty = require("./defineProperty.js"); + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +module.exports = _objectSpread2; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectWithoutProperties.js b/node_modules/@babel/runtime/helpers/objectWithoutProperties.js new file mode 100644 index 0000000..c000db7 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectWithoutProperties.js @@ -0,0 +1,23 @@ +var objectWithoutPropertiesLoose = require("./objectWithoutPropertiesLoose.js"); + +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = objectWithoutPropertiesLoose(source, excluded); + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + + return target; +} + +module.exports = _objectWithoutProperties; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js b/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js new file mode 100644 index 0000000..d9a73de --- /dev/null +++ b/node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js @@ -0,0 +1,17 @@ +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} + +module.exports = _objectWithoutPropertiesLoose; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js b/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js new file mode 100644 index 0000000..21455d3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js @@ -0,0 +1,16 @@ +var _typeof = require("@babel/runtime/helpers/typeof")["default"]; + +var assertThisInitialized = require("./assertThisInitialized.js"); + +function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + + return assertThisInitialized(self); +} + +module.exports = _possibleConstructorReturn; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/readOnlyError.js b/node_modules/@babel/runtime/helpers/readOnlyError.js new file mode 100644 index 0000000..e805f89 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/readOnlyError.js @@ -0,0 +1,6 @@ +function _readOnlyError(name) { + throw new TypeError("\"" + name + "\" is read-only"); +} + +module.exports = _readOnlyError; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/set.js b/node_modules/@babel/runtime/helpers/set.js new file mode 100644 index 0000000..b7d184d --- /dev/null +++ b/node_modules/@babel/runtime/helpers/set.js @@ -0,0 +1,55 @@ +var superPropBase = require("./superPropBase.js"); + +var defineProperty = require("./defineProperty.js"); + +function set(target, property, value, receiver) { + if (typeof Reflect !== "undefined" && Reflect.set) { + set = Reflect.set; + } else { + set = function set(target, property, value, receiver) { + var base = superPropBase(target, property); + var desc; + + if (base) { + desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.set) { + desc.set.call(receiver, value); + return true; + } else if (!desc.writable) { + return false; + } + } + + desc = Object.getOwnPropertyDescriptor(receiver, property); + + if (desc) { + if (!desc.writable) { + return false; + } + + desc.value = value; + Object.defineProperty(receiver, property, desc); + } else { + defineProperty(receiver, property, value); + } + + return true; + }; + } + + return set(target, property, value, receiver); +} + +function _set(target, property, value, receiver, isStrict) { + var s = set(target, property, value, receiver || target); + + if (!s && isStrict) { + throw new Error('failed to set property'); + } + + return value; +} + +module.exports = _set; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/setPrototypeOf.js b/node_modules/@babel/runtime/helpers/setPrototypeOf.js new file mode 100644 index 0000000..415797b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/setPrototypeOf.js @@ -0,0 +1,12 @@ +function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _setPrototypeOf(o, p); +} + +module.exports = _setPrototypeOf; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js b/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js new file mode 100644 index 0000000..ed60585 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/skipFirstGeneratorNext.js @@ -0,0 +1,10 @@ +function _skipFirstGeneratorNext(fn) { + return function () { + var it = fn.apply(this, arguments); + it.next(); + return it; + }; +} + +module.exports = _skipFirstGeneratorNext; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/slicedToArray.js b/node_modules/@babel/runtime/helpers/slicedToArray.js new file mode 100644 index 0000000..101f404 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/slicedToArray.js @@ -0,0 +1,14 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); + +var iterableToArrayLimit = require("./iterableToArrayLimit.js"); + +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +var nonIterableRest = require("./nonIterableRest.js"); + +function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} + +module.exports = _slicedToArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js b/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js new file mode 100644 index 0000000..188db63 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/slicedToArrayLoose.js @@ -0,0 +1,14 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); + +var iterableToArrayLimitLoose = require("./iterableToArrayLimitLoose.js"); + +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +var nonIterableRest = require("./nonIterableRest.js"); + +function _slicedToArrayLoose(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimitLoose(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} + +module.exports = _slicedToArrayLoose; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/superPropBase.js b/node_modules/@babel/runtime/helpers/superPropBase.js new file mode 100644 index 0000000..ce12a88 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/superPropBase.js @@ -0,0 +1,13 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); + +function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + + return object; +} + +module.exports = _superPropBase; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js b/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js new file mode 100644 index 0000000..1a524b3 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/taggedTemplateLiteral.js @@ -0,0 +1,14 @@ +function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); +} + +module.exports = _taggedTemplateLiteral; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js b/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js new file mode 100644 index 0000000..ab78e62 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/taggedTemplateLiteralLoose.js @@ -0,0 +1,11 @@ +function _taggedTemplateLiteralLoose(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + strings.raw = raw; + return strings; +} + +module.exports = _taggedTemplateLiteralLoose; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/tdz.js b/node_modules/@babel/runtime/helpers/tdz.js new file mode 100644 index 0000000..a5b35a6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/tdz.js @@ -0,0 +1,6 @@ +function _tdzError(name) { + throw new ReferenceError(name + " is not defined - temporal dead zone"); +} + +module.exports = _tdzError; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/temporalRef.js b/node_modules/@babel/runtime/helpers/temporalRef.js new file mode 100644 index 0000000..d4e9460 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/temporalRef.js @@ -0,0 +1,10 @@ +var temporalUndefined = require("./temporalUndefined.js"); + +var tdz = require("./tdz.js"); + +function _temporalRef(val, name) { + return val === temporalUndefined ? tdz(name) : val; +} + +module.exports = _temporalRef; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/temporalUndefined.js b/node_modules/@babel/runtime/helpers/temporalUndefined.js new file mode 100644 index 0000000..aeae645 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/temporalUndefined.js @@ -0,0 +1,4 @@ +function _temporalUndefined() {} + +module.exports = _temporalUndefined; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toArray.js b/node_modules/@babel/runtime/helpers/toArray.js new file mode 100644 index 0000000..3b911bd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toArray.js @@ -0,0 +1,14 @@ +var arrayWithHoles = require("./arrayWithHoles.js"); + +var iterableToArray = require("./iterableToArray.js"); + +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +var nonIterableRest = require("./nonIterableRest.js"); + +function _toArray(arr) { + return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest(); +} + +module.exports = _toArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toConsumableArray.js b/node_modules/@babel/runtime/helpers/toConsumableArray.js new file mode 100644 index 0000000..f084cd1 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toConsumableArray.js @@ -0,0 +1,14 @@ +var arrayWithoutHoles = require("./arrayWithoutHoles.js"); + +var iterableToArray = require("./iterableToArray.js"); + +var unsupportedIterableToArray = require("./unsupportedIterableToArray.js"); + +var nonIterableSpread = require("./nonIterableSpread.js"); + +function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); +} + +module.exports = _toConsumableArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toPrimitive.js b/node_modules/@babel/runtime/helpers/toPrimitive.js new file mode 100644 index 0000000..ac40338 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toPrimitive.js @@ -0,0 +1,17 @@ +var _typeof = require("@babel/runtime/helpers/typeof")["default"]; + +function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + + return (hint === "string" ? String : Number)(input); +} + +module.exports = _toPrimitive; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/toPropertyKey.js b/node_modules/@babel/runtime/helpers/toPropertyKey.js new file mode 100644 index 0000000..066b3f2 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/toPropertyKey.js @@ -0,0 +1,11 @@ +var _typeof = require("@babel/runtime/helpers/typeof")["default"]; + +var toPrimitive = require("./toPrimitive.js"); + +function _toPropertyKey(arg) { + var key = toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); +} + +module.exports = _toPropertyKey; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/typeof.js b/node_modules/@babel/runtime/helpers/typeof.js new file mode 100644 index 0000000..02a5d8a --- /dev/null +++ b/node_modules/@babel/runtime/helpers/typeof.js @@ -0,0 +1,22 @@ +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + module.exports = _typeof = function _typeof(obj) { + return typeof obj; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } else { + module.exports = _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } + + return _typeof(obj); +} + +module.exports = _typeof; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js b/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js new file mode 100644 index 0000000..11bca7b --- /dev/null +++ b/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js @@ -0,0 +1,13 @@ +var arrayLikeToArray = require("./arrayLikeToArray.js"); + +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); +} + +module.exports = _unsupportedIterableToArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js b/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js new file mode 100644 index 0000000..057cd19 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapAsyncGenerator.js @@ -0,0 +1,10 @@ +var AsyncGenerator = require("./AsyncGenerator.js"); + +function _wrapAsyncGenerator(fn) { + return function () { + return new AsyncGenerator(fn.apply(this, arguments)); + }; +} + +module.exports = _wrapAsyncGenerator; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapNativeSuper.js b/node_modules/@babel/runtime/helpers/wrapNativeSuper.js new file mode 100644 index 0000000..981c8dd --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapNativeSuper.js @@ -0,0 +1,45 @@ +var getPrototypeOf = require("./getPrototypeOf.js"); + +var setPrototypeOf = require("./setPrototypeOf.js"); + +var isNativeFunction = require("./isNativeFunction.js"); + +var construct = require("./construct.js"); + +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _wrapNativeSuper(Class); +} + +module.exports = _wrapNativeSuper; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/wrapRegExp.js b/node_modules/@babel/runtime/helpers/wrapRegExp.js new file mode 100644 index 0000000..e80a8b6 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/wrapRegExp.js @@ -0,0 +1,72 @@ +var _typeof = require("@babel/runtime/helpers/typeof")["default"]; + +var setPrototypeOf = require("./setPrototypeOf.js"); + +var inherits = require("./inherits.js"); + +function _wrapRegExp() { + module.exports = _wrapRegExp = function _wrapRegExp(re, groups) { + return new BabelRegExp(re, undefined, groups); + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + var _super = RegExp.prototype; + + var _groups = new WeakMap(); + + function BabelRegExp(re, flags, groups) { + var _this = new RegExp(re, flags); + + _groups.set(_this, groups || _groups.get(re)); + + return setPrototypeOf(_this, BabelRegExp.prototype); + } + + inherits(BabelRegExp, RegExp); + + BabelRegExp.prototype.exec = function (str) { + var result = _super.exec.call(this, str); + + if (result) result.groups = buildGroups(result, this); + return result; + }; + + BabelRegExp.prototype[Symbol.replace] = function (str, substitution) { + if (typeof substitution === "string") { + var groups = _groups.get(this); + + return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function (_, name) { + return "$" + groups[name]; + })); + } else if (typeof substitution === "function") { + var _this = this; + + return _super[Symbol.replace].call(this, str, function () { + var args = arguments; + + if (_typeof(args[args.length - 1]) !== "object") { + args = [].slice.call(args); + args.push(buildGroups(args, _this)); + } + + return substitution.apply(this, args); + }); + } else { + return _super[Symbol.replace].call(this, str, substitution); + } + }; + + function buildGroups(result, re) { + var g = _groups.get(re); + + return Object.keys(g).reduce(function (groups, name) { + groups[name] = result[g[name]]; + return groups; + }, Object.create(null)); + } + + return _wrapRegExp.apply(this, arguments); +} + +module.exports = _wrapRegExp; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/helpers/writeOnlyError.js b/node_modules/@babel/runtime/helpers/writeOnlyError.js new file mode 100644 index 0000000..6751a74 --- /dev/null +++ b/node_modules/@babel/runtime/helpers/writeOnlyError.js @@ -0,0 +1,6 @@ +function _writeOnlyError(name) { + throw new TypeError("\"" + name + "\" is write-only"); +} + +module.exports = _writeOnlyError; +module.exports["default"] = module.exports, module.exports.__esModule = true; \ No newline at end of file diff --git a/node_modules/@babel/runtime/package.json b/node_modules/@babel/runtime/package.json new file mode 100644 index 0000000..b10b5c1 --- /dev/null +++ b/node_modules/@babel/runtime/package.json @@ -0,0 +1,856 @@ +{ + "_args": [ + [ + "@babel/runtime@7.15.3", + "/home/other/discord_bot" + ] + ], + "_from": "@babel/runtime@7.15.3", + "_id": "@babel/runtime@7.15.3", + "_inBundle": false, + "_integrity": "sha512-OvwMLqNXkCXSz1kSm58sEsNuhqOx/fKpnUnKnFB5v8uDda5bLNEHNgKPvhDN6IU0LDcnHQ90LlJ0Q6jnyBSIBA==", + "_location": "/@babel/runtime", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@babel/runtime@7.15.3", + "name": "@babel/runtime", + "escapedName": "@babel%2fruntime", + "scope": "@babel", + "rawSpec": "7.15.3", + "saveSpec": null, + "fetchSpec": "7.15.3" + }, + "_requiredBy": [ + "/getstream" + ], + "_resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.15.3.tgz", + "_spec": "7.15.3", + "_where": "/home/other/discord_bot", + "author": { + "name": "The Babel Team", + "url": "https://babel.dev/team" + }, + "bugs": { + "url": "https://github.com/babel/babel/issues" + }, + "dependencies": { + "regenerator-runtime": "^0.13.4" + }, + "description": "babel's modular runtime helpers", + "engines": { + "node": ">=6.9.0" + }, + "exports": { + "./helpers/jsx": [ + { + "node": "./helpers/jsx.js", + "import": "./helpers/esm/jsx.js", + "default": "./helpers/jsx.js" + }, + "./helpers/jsx.js" + ], + "./helpers/esm/jsx": "./helpers/esm/jsx.js", + "./helpers/objectSpread2": [ + { + "node": "./helpers/objectSpread2.js", + "import": "./helpers/esm/objectSpread2.js", + "default": "./helpers/objectSpread2.js" + }, + "./helpers/objectSpread2.js" + ], + "./helpers/esm/objectSpread2": "./helpers/esm/objectSpread2.js", + "./helpers/typeof": [ + { + "node": "./helpers/typeof.js", + "import": "./helpers/esm/typeof.js", + "default": "./helpers/typeof.js" + }, + "./helpers/typeof.js" + ], + "./helpers/esm/typeof": "./helpers/esm/typeof.js", + "./helpers/wrapRegExp": [ + { + "node": "./helpers/wrapRegExp.js", + "import": "./helpers/esm/wrapRegExp.js", + "default": "./helpers/wrapRegExp.js" + }, + "./helpers/wrapRegExp.js" + ], + "./helpers/esm/wrapRegExp": "./helpers/esm/wrapRegExp.js", + "./helpers/asyncIterator": [ + { + "node": "./helpers/asyncIterator.js", + "import": "./helpers/esm/asyncIterator.js", + "default": "./helpers/asyncIterator.js" + }, + "./helpers/asyncIterator.js" + ], + "./helpers/esm/asyncIterator": "./helpers/esm/asyncIterator.js", + "./helpers/AwaitValue": [ + { + "node": "./helpers/AwaitValue.js", + "import": "./helpers/esm/AwaitValue.js", + "default": "./helpers/AwaitValue.js" + }, + "./helpers/AwaitValue.js" + ], + "./helpers/esm/AwaitValue": "./helpers/esm/AwaitValue.js", + "./helpers/AsyncGenerator": [ + { + "node": "./helpers/AsyncGenerator.js", + "import": "./helpers/esm/AsyncGenerator.js", + "default": "./helpers/AsyncGenerator.js" + }, + "./helpers/AsyncGenerator.js" + ], + "./helpers/esm/AsyncGenerator": "./helpers/esm/AsyncGenerator.js", + "./helpers/wrapAsyncGenerator": [ + { + "node": "./helpers/wrapAsyncGenerator.js", + "import": "./helpers/esm/wrapAsyncGenerator.js", + "default": "./helpers/wrapAsyncGenerator.js" + }, + "./helpers/wrapAsyncGenerator.js" + ], + "./helpers/esm/wrapAsyncGenerator": "./helpers/esm/wrapAsyncGenerator.js", + "./helpers/awaitAsyncGenerator": [ + { + "node": "./helpers/awaitAsyncGenerator.js", + "import": "./helpers/esm/awaitAsyncGenerator.js", + "default": "./helpers/awaitAsyncGenerator.js" + }, + "./helpers/awaitAsyncGenerator.js" + ], + "./helpers/esm/awaitAsyncGenerator": "./helpers/esm/awaitAsyncGenerator.js", + "./helpers/asyncGeneratorDelegate": [ + { + "node": "./helpers/asyncGeneratorDelegate.js", + "import": "./helpers/esm/asyncGeneratorDelegate.js", + "default": "./helpers/asyncGeneratorDelegate.js" + }, + "./helpers/asyncGeneratorDelegate.js" + ], + "./helpers/esm/asyncGeneratorDelegate": "./helpers/esm/asyncGeneratorDelegate.js", + "./helpers/asyncToGenerator": [ + { + "node": "./helpers/asyncToGenerator.js", + "import": "./helpers/esm/asyncToGenerator.js", + "default": "./helpers/asyncToGenerator.js" + }, + "./helpers/asyncToGenerator.js" + ], + "./helpers/esm/asyncToGenerator": "./helpers/esm/asyncToGenerator.js", + "./helpers/classCallCheck": [ + { + "node": "./helpers/classCallCheck.js", + "import": "./helpers/esm/classCallCheck.js", + "default": "./helpers/classCallCheck.js" + }, + "./helpers/classCallCheck.js" + ], + "./helpers/esm/classCallCheck": "./helpers/esm/classCallCheck.js", + "./helpers/createClass": [ + { + "node": "./helpers/createClass.js", + "import": "./helpers/esm/createClass.js", + "default": "./helpers/createClass.js" + }, + "./helpers/createClass.js" + ], + "./helpers/esm/createClass": "./helpers/esm/createClass.js", + "./helpers/defineEnumerableProperties": [ + { + "node": "./helpers/defineEnumerableProperties.js", + "import": "./helpers/esm/defineEnumerableProperties.js", + "default": "./helpers/defineEnumerableProperties.js" + }, + "./helpers/defineEnumerableProperties.js" + ], + "./helpers/esm/defineEnumerableProperties": "./helpers/esm/defineEnumerableProperties.js", + "./helpers/defaults": [ + { + "node": "./helpers/defaults.js", + "import": "./helpers/esm/defaults.js", + "default": "./helpers/defaults.js" + }, + "./helpers/defaults.js" + ], + "./helpers/esm/defaults": "./helpers/esm/defaults.js", + "./helpers/defineProperty": [ + { + "node": "./helpers/defineProperty.js", + "import": "./helpers/esm/defineProperty.js", + "default": "./helpers/defineProperty.js" + }, + "./helpers/defineProperty.js" + ], + "./helpers/esm/defineProperty": "./helpers/esm/defineProperty.js", + "./helpers/extends": [ + { + "node": "./helpers/extends.js", + "import": "./helpers/esm/extends.js", + "default": "./helpers/extends.js" + }, + "./helpers/extends.js" + ], + "./helpers/esm/extends": "./helpers/esm/extends.js", + "./helpers/objectSpread": [ + { + "node": "./helpers/objectSpread.js", + "import": "./helpers/esm/objectSpread.js", + "default": "./helpers/objectSpread.js" + }, + "./helpers/objectSpread.js" + ], + "./helpers/esm/objectSpread": "./helpers/esm/objectSpread.js", + "./helpers/inherits": [ + { + "node": "./helpers/inherits.js", + "import": "./helpers/esm/inherits.js", + "default": "./helpers/inherits.js" + }, + "./helpers/inherits.js" + ], + "./helpers/esm/inherits": "./helpers/esm/inherits.js", + "./helpers/inheritsLoose": [ + { + "node": "./helpers/inheritsLoose.js", + "import": "./helpers/esm/inheritsLoose.js", + "default": "./helpers/inheritsLoose.js" + }, + "./helpers/inheritsLoose.js" + ], + "./helpers/esm/inheritsLoose": "./helpers/esm/inheritsLoose.js", + "./helpers/getPrototypeOf": [ + { + "node": "./helpers/getPrototypeOf.js", + "import": "./helpers/esm/getPrototypeOf.js", + "default": "./helpers/getPrototypeOf.js" + }, + "./helpers/getPrototypeOf.js" + ], + "./helpers/esm/getPrototypeOf": "./helpers/esm/getPrototypeOf.js", + "./helpers/setPrototypeOf": [ + { + "node": "./helpers/setPrototypeOf.js", + "import": "./helpers/esm/setPrototypeOf.js", + "default": "./helpers/setPrototypeOf.js" + }, + "./helpers/setPrototypeOf.js" + ], + "./helpers/esm/setPrototypeOf": "./helpers/esm/setPrototypeOf.js", + "./helpers/isNativeReflectConstruct": [ + { + "node": "./helpers/isNativeReflectConstruct.js", + "import": "./helpers/esm/isNativeReflectConstruct.js", + "default": "./helpers/isNativeReflectConstruct.js" + }, + "./helpers/isNativeReflectConstruct.js" + ], + "./helpers/esm/isNativeReflectConstruct": "./helpers/esm/isNativeReflectConstruct.js", + "./helpers/construct": [ + { + "node": "./helpers/construct.js", + "import": "./helpers/esm/construct.js", + "default": "./helpers/construct.js" + }, + "./helpers/construct.js" + ], + "./helpers/esm/construct": "./helpers/esm/construct.js", + "./helpers/isNativeFunction": [ + { + "node": "./helpers/isNativeFunction.js", + "import": "./helpers/esm/isNativeFunction.js", + "default": "./helpers/isNativeFunction.js" + }, + "./helpers/isNativeFunction.js" + ], + "./helpers/esm/isNativeFunction": "./helpers/esm/isNativeFunction.js", + "./helpers/wrapNativeSuper": [ + { + "node": "./helpers/wrapNativeSuper.js", + "import": "./helpers/esm/wrapNativeSuper.js", + "default": "./helpers/wrapNativeSuper.js" + }, + "./helpers/wrapNativeSuper.js" + ], + "./helpers/esm/wrapNativeSuper": "./helpers/esm/wrapNativeSuper.js", + "./helpers/instanceof": [ + { + "node": "./helpers/instanceof.js", + "import": "./helpers/esm/instanceof.js", + "default": "./helpers/instanceof.js" + }, + "./helpers/instanceof.js" + ], + "./helpers/esm/instanceof": "./helpers/esm/instanceof.js", + "./helpers/interopRequireDefault": [ + { + "node": "./helpers/interopRequireDefault.js", + "import": "./helpers/esm/interopRequireDefault.js", + "default": "./helpers/interopRequireDefault.js" + }, + "./helpers/interopRequireDefault.js" + ], + "./helpers/esm/interopRequireDefault": "./helpers/esm/interopRequireDefault.js", + "./helpers/interopRequireWildcard": [ + { + "node": "./helpers/interopRequireWildcard.js", + "import": "./helpers/esm/interopRequireWildcard.js", + "default": "./helpers/interopRequireWildcard.js" + }, + "./helpers/interopRequireWildcard.js" + ], + "./helpers/esm/interopRequireWildcard": "./helpers/esm/interopRequireWildcard.js", + "./helpers/newArrowCheck": [ + { + "node": "./helpers/newArrowCheck.js", + "import": "./helpers/esm/newArrowCheck.js", + "default": "./helpers/newArrowCheck.js" + }, + "./helpers/newArrowCheck.js" + ], + "./helpers/esm/newArrowCheck": "./helpers/esm/newArrowCheck.js", + "./helpers/objectDestructuringEmpty": [ + { + "node": "./helpers/objectDestructuringEmpty.js", + "import": "./helpers/esm/objectDestructuringEmpty.js", + "default": "./helpers/objectDestructuringEmpty.js" + }, + "./helpers/objectDestructuringEmpty.js" + ], + "./helpers/esm/objectDestructuringEmpty": "./helpers/esm/objectDestructuringEmpty.js", + "./helpers/objectWithoutPropertiesLoose": [ + { + "node": "./helpers/objectWithoutPropertiesLoose.js", + "import": "./helpers/esm/objectWithoutPropertiesLoose.js", + "default": "./helpers/objectWithoutPropertiesLoose.js" + }, + "./helpers/objectWithoutPropertiesLoose.js" + ], + "./helpers/esm/objectWithoutPropertiesLoose": "./helpers/esm/objectWithoutPropertiesLoose.js", + "./helpers/objectWithoutProperties": [ + { + "node": "./helpers/objectWithoutProperties.js", + "import": "./helpers/esm/objectWithoutProperties.js", + "default": "./helpers/objectWithoutProperties.js" + }, + "./helpers/objectWithoutProperties.js" + ], + "./helpers/esm/objectWithoutProperties": "./helpers/esm/objectWithoutProperties.js", + "./helpers/assertThisInitialized": [ + { + "node": "./helpers/assertThisInitialized.js", + "import": "./helpers/esm/assertThisInitialized.js", + "default": "./helpers/assertThisInitialized.js" + }, + "./helpers/assertThisInitialized.js" + ], + "./helpers/esm/assertThisInitialized": "./helpers/esm/assertThisInitialized.js", + "./helpers/possibleConstructorReturn": [ + { + "node": "./helpers/possibleConstructorReturn.js", + "import": "./helpers/esm/possibleConstructorReturn.js", + "default": "./helpers/possibleConstructorReturn.js" + }, + "./helpers/possibleConstructorReturn.js" + ], + "./helpers/esm/possibleConstructorReturn": "./helpers/esm/possibleConstructorReturn.js", + "./helpers/createSuper": [ + { + "node": "./helpers/createSuper.js", + "import": "./helpers/esm/createSuper.js", + "default": "./helpers/createSuper.js" + }, + "./helpers/createSuper.js" + ], + "./helpers/esm/createSuper": "./helpers/esm/createSuper.js", + "./helpers/superPropBase": [ + { + "node": "./helpers/superPropBase.js", + "import": "./helpers/esm/superPropBase.js", + "default": "./helpers/superPropBase.js" + }, + "./helpers/superPropBase.js" + ], + "./helpers/esm/superPropBase": "./helpers/esm/superPropBase.js", + "./helpers/get": [ + { + "node": "./helpers/get.js", + "import": "./helpers/esm/get.js", + "default": "./helpers/get.js" + }, + "./helpers/get.js" + ], + "./helpers/esm/get": "./helpers/esm/get.js", + "./helpers/set": [ + { + "node": "./helpers/set.js", + "import": "./helpers/esm/set.js", + "default": "./helpers/set.js" + }, + "./helpers/set.js" + ], + "./helpers/esm/set": "./helpers/esm/set.js", + "./helpers/taggedTemplateLiteral": [ + { + "node": "./helpers/taggedTemplateLiteral.js", + "import": "./helpers/esm/taggedTemplateLiteral.js", + "default": "./helpers/taggedTemplateLiteral.js" + }, + "./helpers/taggedTemplateLiteral.js" + ], + "./helpers/esm/taggedTemplateLiteral": "./helpers/esm/taggedTemplateLiteral.js", + "./helpers/taggedTemplateLiteralLoose": [ + { + "node": "./helpers/taggedTemplateLiteralLoose.js", + "import": "./helpers/esm/taggedTemplateLiteralLoose.js", + "default": "./helpers/taggedTemplateLiteralLoose.js" + }, + "./helpers/taggedTemplateLiteralLoose.js" + ], + "./helpers/esm/taggedTemplateLiteralLoose": "./helpers/esm/taggedTemplateLiteralLoose.js", + "./helpers/readOnlyError": [ + { + "node": "./helpers/readOnlyError.js", + "import": "./helpers/esm/readOnlyError.js", + "default": "./helpers/readOnlyError.js" + }, + "./helpers/readOnlyError.js" + ], + "./helpers/esm/readOnlyError": "./helpers/esm/readOnlyError.js", + "./helpers/writeOnlyError": [ + { + "node": "./helpers/writeOnlyError.js", + "import": "./helpers/esm/writeOnlyError.js", + "default": "./helpers/writeOnlyError.js" + }, + "./helpers/writeOnlyError.js" + ], + "./helpers/esm/writeOnlyError": "./helpers/esm/writeOnlyError.js", + "./helpers/classNameTDZError": [ + { + "node": "./helpers/classNameTDZError.js", + "import": "./helpers/esm/classNameTDZError.js", + "default": "./helpers/classNameTDZError.js" + }, + "./helpers/classNameTDZError.js" + ], + "./helpers/esm/classNameTDZError": "./helpers/esm/classNameTDZError.js", + "./helpers/temporalUndefined": [ + { + "node": "./helpers/temporalUndefined.js", + "import": "./helpers/esm/temporalUndefined.js", + "default": "./helpers/temporalUndefined.js" + }, + "./helpers/temporalUndefined.js" + ], + "./helpers/esm/temporalUndefined": "./helpers/esm/temporalUndefined.js", + "./helpers/tdz": [ + { + "node": "./helpers/tdz.js", + "import": "./helpers/esm/tdz.js", + "default": "./helpers/tdz.js" + }, + "./helpers/tdz.js" + ], + "./helpers/esm/tdz": "./helpers/esm/tdz.js", + "./helpers/temporalRef": [ + { + "node": "./helpers/temporalRef.js", + "import": "./helpers/esm/temporalRef.js", + "default": "./helpers/temporalRef.js" + }, + "./helpers/temporalRef.js" + ], + "./helpers/esm/temporalRef": "./helpers/esm/temporalRef.js", + "./helpers/slicedToArray": [ + { + "node": "./helpers/slicedToArray.js", + "import": "./helpers/esm/slicedToArray.js", + "default": "./helpers/slicedToArray.js" + }, + "./helpers/slicedToArray.js" + ], + "./helpers/esm/slicedToArray": "./helpers/esm/slicedToArray.js", + "./helpers/slicedToArrayLoose": [ + { + "node": "./helpers/slicedToArrayLoose.js", + "import": "./helpers/esm/slicedToArrayLoose.js", + "default": "./helpers/slicedToArrayLoose.js" + }, + "./helpers/slicedToArrayLoose.js" + ], + "./helpers/esm/slicedToArrayLoose": "./helpers/esm/slicedToArrayLoose.js", + "./helpers/toArray": [ + { + "node": "./helpers/toArray.js", + "import": "./helpers/esm/toArray.js", + "default": "./helpers/toArray.js" + }, + "./helpers/toArray.js" + ], + "./helpers/esm/toArray": "./helpers/esm/toArray.js", + "./helpers/toConsumableArray": [ + { + "node": "./helpers/toConsumableArray.js", + "import": "./helpers/esm/toConsumableArray.js", + "default": "./helpers/toConsumableArray.js" + }, + "./helpers/toConsumableArray.js" + ], + "./helpers/esm/toConsumableArray": "./helpers/esm/toConsumableArray.js", + "./helpers/arrayWithoutHoles": [ + { + "node": "./helpers/arrayWithoutHoles.js", + "import": "./helpers/esm/arrayWithoutHoles.js", + "default": "./helpers/arrayWithoutHoles.js" + }, + "./helpers/arrayWithoutHoles.js" + ], + "./helpers/esm/arrayWithoutHoles": "./helpers/esm/arrayWithoutHoles.js", + "./helpers/arrayWithHoles": [ + { + "node": "./helpers/arrayWithHoles.js", + "import": "./helpers/esm/arrayWithHoles.js", + "default": "./helpers/arrayWithHoles.js" + }, + "./helpers/arrayWithHoles.js" + ], + "./helpers/esm/arrayWithHoles": "./helpers/esm/arrayWithHoles.js", + "./helpers/maybeArrayLike": [ + { + "node": "./helpers/maybeArrayLike.js", + "import": "./helpers/esm/maybeArrayLike.js", + "default": "./helpers/maybeArrayLike.js" + }, + "./helpers/maybeArrayLike.js" + ], + "./helpers/esm/maybeArrayLike": "./helpers/esm/maybeArrayLike.js", + "./helpers/iterableToArray": [ + { + "node": "./helpers/iterableToArray.js", + "import": "./helpers/esm/iterableToArray.js", + "default": "./helpers/iterableToArray.js" + }, + "./helpers/iterableToArray.js" + ], + "./helpers/esm/iterableToArray": "./helpers/esm/iterableToArray.js", + "./helpers/iterableToArrayLimit": [ + { + "node": "./helpers/iterableToArrayLimit.js", + "import": "./helpers/esm/iterableToArrayLimit.js", + "default": "./helpers/iterableToArrayLimit.js" + }, + "./helpers/iterableToArrayLimit.js" + ], + "./helpers/esm/iterableToArrayLimit": "./helpers/esm/iterableToArrayLimit.js", + "./helpers/iterableToArrayLimitLoose": [ + { + "node": "./helpers/iterableToArrayLimitLoose.js", + "import": "./helpers/esm/iterableToArrayLimitLoose.js", + "default": "./helpers/iterableToArrayLimitLoose.js" + }, + "./helpers/iterableToArrayLimitLoose.js" + ], + "./helpers/esm/iterableToArrayLimitLoose": "./helpers/esm/iterableToArrayLimitLoose.js", + "./helpers/unsupportedIterableToArray": [ + { + "node": "./helpers/unsupportedIterableToArray.js", + "import": "./helpers/esm/unsupportedIterableToArray.js", + "default": "./helpers/unsupportedIterableToArray.js" + }, + "./helpers/unsupportedIterableToArray.js" + ], + "./helpers/esm/unsupportedIterableToArray": "./helpers/esm/unsupportedIterableToArray.js", + "./helpers/arrayLikeToArray": [ + { + "node": "./helpers/arrayLikeToArray.js", + "import": "./helpers/esm/arrayLikeToArray.js", + "default": "./helpers/arrayLikeToArray.js" + }, + "./helpers/arrayLikeToArray.js" + ], + "./helpers/esm/arrayLikeToArray": "./helpers/esm/arrayLikeToArray.js", + "./helpers/nonIterableSpread": [ + { + "node": "./helpers/nonIterableSpread.js", + "import": "./helpers/esm/nonIterableSpread.js", + "default": "./helpers/nonIterableSpread.js" + }, + "./helpers/nonIterableSpread.js" + ], + "./helpers/esm/nonIterableSpread": "./helpers/esm/nonIterableSpread.js", + "./helpers/nonIterableRest": [ + { + "node": "./helpers/nonIterableRest.js", + "import": "./helpers/esm/nonIterableRest.js", + "default": "./helpers/nonIterableRest.js" + }, + "./helpers/nonIterableRest.js" + ], + "./helpers/esm/nonIterableRest": "./helpers/esm/nonIterableRest.js", + "./helpers/createForOfIteratorHelper": [ + { + "node": "./helpers/createForOfIteratorHelper.js", + "import": "./helpers/esm/createForOfIteratorHelper.js", + "default": "./helpers/createForOfIteratorHelper.js" + }, + "./helpers/createForOfIteratorHelper.js" + ], + "./helpers/esm/createForOfIteratorHelper": "./helpers/esm/createForOfIteratorHelper.js", + "./helpers/createForOfIteratorHelperLoose": [ + { + "node": "./helpers/createForOfIteratorHelperLoose.js", + "import": "./helpers/esm/createForOfIteratorHelperLoose.js", + "default": "./helpers/createForOfIteratorHelperLoose.js" + }, + "./helpers/createForOfIteratorHelperLoose.js" + ], + "./helpers/esm/createForOfIteratorHelperLoose": "./helpers/esm/createForOfIteratorHelperLoose.js", + "./helpers/skipFirstGeneratorNext": [ + { + "node": "./helpers/skipFirstGeneratorNext.js", + "import": "./helpers/esm/skipFirstGeneratorNext.js", + "default": "./helpers/skipFirstGeneratorNext.js" + }, + "./helpers/skipFirstGeneratorNext.js" + ], + "./helpers/esm/skipFirstGeneratorNext": "./helpers/esm/skipFirstGeneratorNext.js", + "./helpers/toPrimitive": [ + { + "node": "./helpers/toPrimitive.js", + "import": "./helpers/esm/toPrimitive.js", + "default": "./helpers/toPrimitive.js" + }, + "./helpers/toPrimitive.js" + ], + "./helpers/esm/toPrimitive": "./helpers/esm/toPrimitive.js", + "./helpers/toPropertyKey": [ + { + "node": "./helpers/toPropertyKey.js", + "import": "./helpers/esm/toPropertyKey.js", + "default": "./helpers/toPropertyKey.js" + }, + "./helpers/toPropertyKey.js" + ], + "./helpers/esm/toPropertyKey": "./helpers/esm/toPropertyKey.js", + "./helpers/initializerWarningHelper": [ + { + "node": "./helpers/initializerWarningHelper.js", + "import": "./helpers/esm/initializerWarningHelper.js", + "default": "./helpers/initializerWarningHelper.js" + }, + "./helpers/initializerWarningHelper.js" + ], + "./helpers/esm/initializerWarningHelper": "./helpers/esm/initializerWarningHelper.js", + "./helpers/initializerDefineProperty": [ + { + "node": "./helpers/initializerDefineProperty.js", + "import": "./helpers/esm/initializerDefineProperty.js", + "default": "./helpers/initializerDefineProperty.js" + }, + "./helpers/initializerDefineProperty.js" + ], + "./helpers/esm/initializerDefineProperty": "./helpers/esm/initializerDefineProperty.js", + "./helpers/applyDecoratedDescriptor": [ + { + "node": "./helpers/applyDecoratedDescriptor.js", + "import": "./helpers/esm/applyDecoratedDescriptor.js", + "default": "./helpers/applyDecoratedDescriptor.js" + }, + "./helpers/applyDecoratedDescriptor.js" + ], + "./helpers/esm/applyDecoratedDescriptor": "./helpers/esm/applyDecoratedDescriptor.js", + "./helpers/classPrivateFieldLooseKey": [ + { + "node": "./helpers/classPrivateFieldLooseKey.js", + "import": "./helpers/esm/classPrivateFieldLooseKey.js", + "default": "./helpers/classPrivateFieldLooseKey.js" + }, + "./helpers/classPrivateFieldLooseKey.js" + ], + "./helpers/esm/classPrivateFieldLooseKey": "./helpers/esm/classPrivateFieldLooseKey.js", + "./helpers/classPrivateFieldLooseBase": [ + { + "node": "./helpers/classPrivateFieldLooseBase.js", + "import": "./helpers/esm/classPrivateFieldLooseBase.js", + "default": "./helpers/classPrivateFieldLooseBase.js" + }, + "./helpers/classPrivateFieldLooseBase.js" + ], + "./helpers/esm/classPrivateFieldLooseBase": "./helpers/esm/classPrivateFieldLooseBase.js", + "./helpers/classPrivateFieldGet": [ + { + "node": "./helpers/classPrivateFieldGet.js", + "import": "./helpers/esm/classPrivateFieldGet.js", + "default": "./helpers/classPrivateFieldGet.js" + }, + "./helpers/classPrivateFieldGet.js" + ], + "./helpers/esm/classPrivateFieldGet": "./helpers/esm/classPrivateFieldGet.js", + "./helpers/classPrivateFieldSet": [ + { + "node": "./helpers/classPrivateFieldSet.js", + "import": "./helpers/esm/classPrivateFieldSet.js", + "default": "./helpers/classPrivateFieldSet.js" + }, + "./helpers/classPrivateFieldSet.js" + ], + "./helpers/esm/classPrivateFieldSet": "./helpers/esm/classPrivateFieldSet.js", + "./helpers/classPrivateFieldDestructureSet": [ + { + "node": "./helpers/classPrivateFieldDestructureSet.js", + "import": "./helpers/esm/classPrivateFieldDestructureSet.js", + "default": "./helpers/classPrivateFieldDestructureSet.js" + }, + "./helpers/classPrivateFieldDestructureSet.js" + ], + "./helpers/esm/classPrivateFieldDestructureSet": "./helpers/esm/classPrivateFieldDestructureSet.js", + "./helpers/classExtractFieldDescriptor": [ + { + "node": "./helpers/classExtractFieldDescriptor.js", + "import": "./helpers/esm/classExtractFieldDescriptor.js", + "default": "./helpers/classExtractFieldDescriptor.js" + }, + "./helpers/classExtractFieldDescriptor.js" + ], + "./helpers/esm/classExtractFieldDescriptor": "./helpers/esm/classExtractFieldDescriptor.js", + "./helpers/classStaticPrivateFieldSpecGet": [ + { + "node": "./helpers/classStaticPrivateFieldSpecGet.js", + "import": "./helpers/esm/classStaticPrivateFieldSpecGet.js", + "default": "./helpers/classStaticPrivateFieldSpecGet.js" + }, + "./helpers/classStaticPrivateFieldSpecGet.js" + ], + "./helpers/esm/classStaticPrivateFieldSpecGet": "./helpers/esm/classStaticPrivateFieldSpecGet.js", + "./helpers/classStaticPrivateFieldSpecSet": [ + { + "node": "./helpers/classStaticPrivateFieldSpecSet.js", + "import": "./helpers/esm/classStaticPrivateFieldSpecSet.js", + "default": "./helpers/classStaticPrivateFieldSpecSet.js" + }, + "./helpers/classStaticPrivateFieldSpecSet.js" + ], + "./helpers/esm/classStaticPrivateFieldSpecSet": "./helpers/esm/classStaticPrivateFieldSpecSet.js", + "./helpers/classStaticPrivateMethodGet": [ + { + "node": "./helpers/classStaticPrivateMethodGet.js", + "import": "./helpers/esm/classStaticPrivateMethodGet.js", + "default": "./helpers/classStaticPrivateMethodGet.js" + }, + "./helpers/classStaticPrivateMethodGet.js" + ], + "./helpers/esm/classStaticPrivateMethodGet": "./helpers/esm/classStaticPrivateMethodGet.js", + "./helpers/classStaticPrivateMethodSet": [ + { + "node": "./helpers/classStaticPrivateMethodSet.js", + "import": "./helpers/esm/classStaticPrivateMethodSet.js", + "default": "./helpers/classStaticPrivateMethodSet.js" + }, + "./helpers/classStaticPrivateMethodSet.js" + ], + "./helpers/esm/classStaticPrivateMethodSet": "./helpers/esm/classStaticPrivateMethodSet.js", + "./helpers/classApplyDescriptorGet": [ + { + "node": "./helpers/classApplyDescriptorGet.js", + "import": "./helpers/esm/classApplyDescriptorGet.js", + "default": "./helpers/classApplyDescriptorGet.js" + }, + "./helpers/classApplyDescriptorGet.js" + ], + "./helpers/esm/classApplyDescriptorGet": "./helpers/esm/classApplyDescriptorGet.js", + "./helpers/classApplyDescriptorSet": [ + { + "node": "./helpers/classApplyDescriptorSet.js", + "import": "./helpers/esm/classApplyDescriptorSet.js", + "default": "./helpers/classApplyDescriptorSet.js" + }, + "./helpers/classApplyDescriptorSet.js" + ], + "./helpers/esm/classApplyDescriptorSet": "./helpers/esm/classApplyDescriptorSet.js", + "./helpers/classApplyDescriptorDestructureSet": [ + { + "node": "./helpers/classApplyDescriptorDestructureSet.js", + "import": "./helpers/esm/classApplyDescriptorDestructureSet.js", + "default": "./helpers/classApplyDescriptorDestructureSet.js" + }, + "./helpers/classApplyDescriptorDestructureSet.js" + ], + "./helpers/esm/classApplyDescriptorDestructureSet": "./helpers/esm/classApplyDescriptorDestructureSet.js", + "./helpers/classStaticPrivateFieldDestructureSet": [ + { + "node": "./helpers/classStaticPrivateFieldDestructureSet.js", + "import": "./helpers/esm/classStaticPrivateFieldDestructureSet.js", + "default": "./helpers/classStaticPrivateFieldDestructureSet.js" + }, + "./helpers/classStaticPrivateFieldDestructureSet.js" + ], + "./helpers/esm/classStaticPrivateFieldDestructureSet": "./helpers/esm/classStaticPrivateFieldDestructureSet.js", + "./helpers/classCheckPrivateStaticAccess": [ + { + "node": "./helpers/classCheckPrivateStaticAccess.js", + "import": "./helpers/esm/classCheckPrivateStaticAccess.js", + "default": "./helpers/classCheckPrivateStaticAccess.js" + }, + "./helpers/classCheckPrivateStaticAccess.js" + ], + "./helpers/esm/classCheckPrivateStaticAccess": "./helpers/esm/classCheckPrivateStaticAccess.js", + "./helpers/classCheckPrivateStaticFieldDescriptor": [ + { + "node": "./helpers/classCheckPrivateStaticFieldDescriptor.js", + "import": "./helpers/esm/classCheckPrivateStaticFieldDescriptor.js", + "default": "./helpers/classCheckPrivateStaticFieldDescriptor.js" + }, + "./helpers/classCheckPrivateStaticFieldDescriptor.js" + ], + "./helpers/esm/classCheckPrivateStaticFieldDescriptor": "./helpers/esm/classCheckPrivateStaticFieldDescriptor.js", + "./helpers/decorate": [ + { + "node": "./helpers/decorate.js", + "import": "./helpers/esm/decorate.js", + "default": "./helpers/decorate.js" + }, + "./helpers/decorate.js" + ], + "./helpers/esm/decorate": "./helpers/esm/decorate.js", + "./helpers/classPrivateMethodGet": [ + { + "node": "./helpers/classPrivateMethodGet.js", + "import": "./helpers/esm/classPrivateMethodGet.js", + "default": "./helpers/classPrivateMethodGet.js" + }, + "./helpers/classPrivateMethodGet.js" + ], + "./helpers/esm/classPrivateMethodGet": "./helpers/esm/classPrivateMethodGet.js", + "./helpers/classPrivateMethodSet": [ + { + "node": "./helpers/classPrivateMethodSet.js", + "import": "./helpers/esm/classPrivateMethodSet.js", + "default": "./helpers/classPrivateMethodSet.js" + }, + "./helpers/classPrivateMethodSet.js" + ], + "./helpers/esm/classPrivateMethodSet": "./helpers/esm/classPrivateMethodSet.js", + "./package": "./package.json", + "./package.json": "./package.json", + "./regenerator": "./regenerator/index.js", + "./regenerator/*.js": "./regenerator/*.js", + "./regenerator/": "./regenerator/" + }, + "homepage": "https://babel.dev/docs/en/next/babel-runtime", + "license": "MIT", + "name": "@babel/runtime", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/babel/babel.git", + "directory": "packages/babel-runtime" + }, + "version": "7.15.3" +} diff --git a/node_modules/@babel/runtime/regenerator/index.js b/node_modules/@babel/runtime/regenerator/index.js new file mode 100644 index 0000000..9fd4158 --- /dev/null +++ b/node_modules/@babel/runtime/regenerator/index.js @@ -0,0 +1 @@ +module.exports = require("regenerator-runtime"); diff --git a/node_modules/@discordjs/builders/CHANGELOG.md b/node_modules/@discordjs/builders/CHANGELOG.md new file mode 100644 index 0000000..eb8000d --- /dev/null +++ b/node_modules/@discordjs/builders/CHANGELOG.md @@ -0,0 +1,233 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@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 + +- 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)) +- Allow punctuation characters in context menus (#8783) ([b521366](https://github.com/discordjs/discord.js/commit/b5213664fa66746daab1673ebe2adf2db3d1522c)) + +## Typings + +- **Formatters:** Allow boolean in `formatEmoji` (#8823) ([ec37f13](https://github.com/discordjs/discord.js/commit/ec37f137fd4fca0fdbdb8a5c83abf32362a8f285)) + +# [@discordjs/builders@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.2.0...@discordjs/builders@1.3.0) - (2022-10-08) + +## Bug Fixes + +- Allow adding forums to `channelTypes` (#8658) ([b1e190c](https://github.com/discordjs/discord.js/commit/b1e190c4f0773a1a739625f5b41026f593515370)) +- **SlashCommandBuilder:** Missing methods in subcommand builder (#8583) ([1c5b78f](https://github.com/discordjs/discord.js/commit/1c5b78fd2130f09c951459cf4c2d637f46c3c2c9)) +- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9)) + +## Documentation + +- **builders/components:** Document constructors (#8636) ([8444576](https://github.com/discordjs/discord.js/commit/8444576f45da5fdddbf8ba2d91b4cb31a3b51c04)) +- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0)) +- Use remarks instead of `Note` in descriptions (#8597) ([f3ce4a7](https://github.com/discordjs/discord.js/commit/f3ce4a75d0c4eafc89a1f0ce9f4964bcbcdae6da)) + +## Features + +- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2)) +- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3)) +- Add `chatInputApplicationCommandMention` formatter (#8546) ([d08a57c](https://github.com/discordjs/discord.js/commit/d08a57cadd9d69a734077cc1902d931ab10336db)) + +## Refactor + +- Replace usage of deprecated `ChannelType`s (#8625) ([669c3cd](https://github.com/discordjs/discord.js/commit/669c3cd2566eac68ef38ab522dd6378ba761e8b3)) +- 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)) + +## Testing + +- Rename incorrect test (#8596) ([ce991dd](https://github.com/discordjs/discord.js/commit/ce991dd1d883f6785b5f4b4b3ac80ef21cb304e7)) + +## Typings + +- **interactions:** Fix `{Slash,ContextMenu}CommandBuilder#toJSON` (#8568) ([b7eb96d](https://github.com/discordjs/discord.js/commit/b7eb96d45670616521fbcca28a657793d91605c7)) + +# [@discordjs/builders@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.1.0...@discordjs/builders@1.2.0) - (2022-08-22) + +## Features + +- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007)) +- **website:** Show descriptions for `@typeParam` blocks (#8523) ([e475b63](https://github.com/discordjs/discord.js/commit/e475b63f257f6261d73cb89fee9ecbcdd84e2a6b)) +- **website:** Show parameter descriptions (#8519) ([7f415a2](https://github.com/discordjs/discord.js/commit/7f415a2502bf7ce2025dbcfed9017b0635a19966)) +- **WebSocketShard:** Support new resume url (#8480) ([bc06cc6](https://github.com/discordjs/discord.js/commit/bc06cc638d2f57ab5c600e8cdb6afc8eb2180166)) + +## Refactor + +- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e)) + +# [@discordjs/builders@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.16.0...@discordjs/builders@1.1.0) - (2022-07-29) + +## Bug Fixes + +- Use proper format for `@link` text (#8384) ([2655639](https://github.com/discordjs/discord.js/commit/26556390a3800e954974a00c1328ff47d3e67e9a)) +- **Formatters:** Add newline in `codeBlock` (#8369) ([5d8bd03](https://github.com/discordjs/discord.js/commit/5d8bd030d60ef364de3ef5f9963da8bda5c4efd4)) +- **selectMenu:** Allow json to be used for select menu options (#8322) ([6a2d0d8](https://github.com/discordjs/discord.js/commit/6a2d0d8e96d157d5b85cee7f17bffdfff4240074)) + +## Documentation + +- Use link tags (#8382) ([5494791](https://github.com/discordjs/discord.js/commit/549479131318c659f86f0eb18578d597e22522d3)) + +## Features + +- Add channel & message URL formatters (#8371) ([a7deb8f](https://github.com/discordjs/discord.js/commit/a7deb8f89830ead6185c5fb46a49688b6d209ed1)) + +## Testing + +- **builders:** Improve coverage (#8274) ([b7e6238](https://github.com/discordjs/discord.js/commit/b7e62380f2e6b9324d6bba9b9eaa5315080bf66a)) + +# [@discordjs/builders@0.16.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.15.0...@discordjs/builders@0.16.0) - (2022-07-17) + +## Bug Fixes + +- Slash command name regex (#8265) ([32f9056](https://github.com/discordjs/discord.js/commit/32f9056b15edede3bab07de96afb4b56d3a9ecca)) +- **TextInputBuilder:** Parse `custom_id`, `label`, and `style` (#8216) ([2d9dfa3](https://github.com/discordjs/discord.js/commit/2d9dfa3c6ea4bb972da2f7e088d148b798c866d9)) + +## Documentation + +- Add codecov coverage badge to readmes (#8226) ([f6db285](https://github.com/discordjs/discord.js/commit/f6db285c073898a749fe4591cbd4463d1896daf5)) + +## Features + +- **builder:** Add max min length in string option (#8214) ([96c8d21](https://github.com/discordjs/discord.js/commit/96c8d21f95eb366c46ae23505ba9054f44821b25)) +- Codecov (#8219) ([f10f4cd](https://github.com/discordjs/discord.js/commit/f10f4cdcd88ca6be7ec735ed3a415ba13da83db0)) +- **docgen:** Update typedoc ([b3346f4](https://github.com/discordjs/discord.js/commit/b3346f4b9b3d4f96443506643d4631dc1c6d7b21)) +- Website (#8043) ([127931d](https://github.com/discordjs/discord.js/commit/127931d1df7a2a5c27923c2f2151dbf3824e50cc)) +- **docgen:** Typescript support ([3279b40](https://github.com/discordjs/discord.js/commit/3279b40912e6aa61507bedb7db15a2b8668de44b)) +- Docgen package (#8029) ([8b979c0](https://github.com/discordjs/discord.js/commit/8b979c0245c42fd824d8e98745ee869f5360fc86)) + +## Refactor + +- **builder:** Remove `unsafe*Builder`s (#8074) ([a4d1862](https://github.com/discordjs/discord.js/commit/a4d18629828234f43f03d1bd4851d4b727c6903b)) +- Remove @sindresorhus/is as it's now esm only (#8133) ([c6f285b](https://github.com/discordjs/discord.js/commit/c6f285b7b089b004776fbeb444fe973a68d158d8)) +- Move all the config files to root (#8033) ([769ea0b](https://github.com/discordjs/discord.js/commit/769ea0bfe78c4f1d413c6b397c604ffe91e39c6a)) + +## Typings + +- Remove expect error (#8242) ([7e6dbaa](https://github.com/discordjs/discord.js/commit/7e6dbaaed900c07d1a04e23bbbf9cd0d1b0501c5)) +- **builder:** Remove casting (#8241) ([8198da5](https://github.com/discordjs/discord.js/commit/8198da5cd0898e06954615a2287853321e7ebbd4)) + +# [@discordjs/builders@0.15.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.14.0...@discordjs/builders@0.15.0) - (2022-06-06) + +## Features + +- Allow builders to accept rest params and arrays (#7874) ([ad75be9](https://github.com/discordjs/discord.js/commit/ad75be9a9cf90c8624495df99b75177e6c24022f)) +- Use vitest instead of jest for more speed ([8d8e6c0](https://github.com/discordjs/discord.js/commit/8d8e6c03decd7352a2aa180f6e5bc1a13602539b)) +- Add scripts package for locally used scripts ([f2ae1f9](https://github.com/discordjs/discord.js/commit/f2ae1f9348bfd893332a9060f71a8a5f272a1b8b)) + +# [@discordjs/builders@0.14.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.13.0...@discordjs/builders@0.14.0) - (2022-06-04) + +## Bug Fixes + +- **builders:** Leftover invalid null type ([8a7cd10](https://github.com/discordjs/discord.js/commit/8a7cd10554a2a71cd2fe7f6a177b5f4f43464348)) +- **SlashCommandBuilder:** Import `Permissions` correctly (#7921) ([7ce641d](https://github.com/discordjs/discord.js/commit/7ce641d33a4af6586d5e7beffbe7d38619dcf1a2)) +- Add localizations for subcommand builders and option choices (#7862) ([c1b5e73](https://github.com/discordjs/discord.js/commit/c1b5e731daa9cbbfca03a046e47cb1221ee1ed7c)) + +## Features + +- Export types from `interactions/slashCommands/mixins` (#7942) ([68d5169](https://github.com/discordjs/discord.js/commit/68d5169f66c96f8fe5be17a1c01cdd5155607ab2)) +- **builders:** Add new command permissions v2 (#7861) ([de3f157](https://github.com/discordjs/discord.js/commit/de3f1573f07dda294cc0fbb1ca4b659eb2388a12)) +- **builders:** Improve embed errors and predicates (#7795) ([ec8d87f](https://github.com/discordjs/discord.js/commit/ec8d87f93272cc9987f9613735c0361680c4ed1e)) + +## Refactor + +- Use arrays instead of rest parameters for builders (#7759) ([29293d7](https://github.com/discordjs/discord.js/commit/29293d7bbb5ed463e52e5a5853817e5a09cf265b)) + +## Styling + +- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629)) + +# [@discordjs/builders@0.13.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.12.0...@discordjs/builders@0.13.0) - (2022-04-17) + +## Bug Fixes + +- Validate select menu options (#7566) ([b1d63d9](https://github.com/discordjs/discord.js/commit/b1d63d919a61f309ac89f27016b0f148678dac2b)) +- **SelectMenu:** Set `placeholder` max to 150 (#7538) ([dcd4797](https://github.com/discordjs/discord.js/commit/dcd479767b6ec980a373f2ea1f22754f41661c1e)) +- Only check `instanceof Component` once (#7546) ([0aa4851](https://github.com/discordjs/discord.js/commit/0aa48516a4e33497e8e8dc50da164a57cdee09d3)) +- **builders:** Allow negative min/max value of number/integer option (#7484) ([3baa340](https://github.com/discordjs/discord.js/commit/3baa340821b8ecf8a16253bc0917a1033250d7c9)) +- **components:** SetX should take rest parameters (#7461) ([3617359](https://github.com/discordjs/discord.js/commit/36173590a712f041b087b7882054805a8bd42dae)) +- Unsafe embed builder field normalization (#7418) ([b936103](https://github.com/discordjs/discord.js/commit/b936103395121cb21a8c616f669ddab1d2efb0f1)) +- Fix some typos (#7393) ([92a04f4](https://github.com/discordjs/discord.js/commit/92a04f4d98f6c6760214034cc8f5a1eaa78893c7)) +- **builders:** Make type optional in constructor (#7391) ([4abb28c](https://github.com/discordjs/discord.js/commit/4abb28c0a1256c57a60369a6b8ec9e98c265b489)) +- Don't create new instances of builders classes (#7343) ([d6b56d0](https://github.com/discordjs/discord.js/commit/d6b56d0080c4c5f8ace731f1e8bcae0c9d3fb5a5)) + +## Documentation + +- Completely fix builders example link (#7543) ([1a14c0c](https://github.com/discordjs/discord.js/commit/1a14c0ca562ea173d363a770a0437209f461fd23)) +- Add slash command builders example, fixes #7338 (#7339) ([3ae6f3c](https://github.com/discordjs/discord.js/commit/3ae6f3c313091151245d6e6b52337b459ecfc765)) + +## Features + +- Slash command localization for builders (#7683) ([40b9a1d](https://github.com/discordjs/discord.js/commit/40b9a1d67d0b508ec593e030913acd8161cd17f8)) +- Add API v10 support (#7477) ([72577c4](https://github.com/discordjs/discord.js/commit/72577c4bfd02524a27afb6ff4aebba9301a690d3)) +- Add support for module: NodeNext in TS and ESM (#7598) ([8f1986a](https://github.com/discordjs/discord.js/commit/8f1986a6aa98365e09b00e84ad5f9f354ab61f3d)) +- Add Modals and Text Inputs (#7023) ([ed92015](https://github.com/discordjs/discord.js/commit/ed920156344233241a21b0c0b99736a3a855c23c)) +- Add missing `v13` component methods (#7466) ([f7257f0](https://github.com/discordjs/discord.js/commit/f7257f07655076eabfe355cb6a53260b39ca9670)) +- **builders:** Add attachment command option type (#7203) ([ae0f35f](https://github.com/discordjs/discord.js/commit/ae0f35f51d68dfa5a7dc43d161ef9365171debdb)) +- **components:** Add unsafe message component builders (#7387) ([6b6222b](https://github.com/discordjs/discord.js/commit/6b6222bf513d1ee8cd98fba0ad313def560b864f)) +- **embed:** Add setFields (#7322) ([bcc5cda](https://github.com/discordjs/discord.js/commit/bcc5cda8a902ddb28c7e3578e0f29b4272832624)) + +## Refactor + +- Remove nickname parsing (#7736) ([78a3afc](https://github.com/discordjs/discord.js/commit/78a3afcd7fdac358e06764cc0d675e1215c785f3)) +- Replace zod with shapeshift (#7547) ([3c0bbac](https://github.com/discordjs/discord.js/commit/3c0bbac82fa9988af4a62ff00c66d149fbe6b921)) +- Remove store channels (#7634) ([aedddb8](https://github.com/discordjs/discord.js/commit/aedddb875e740e1f1bd77f06ce1b361fd3b7bc36)) +- Allow builders to accept emoji strings (#7616) ([fb9a9c2](https://github.com/discordjs/discord.js/commit/fb9a9c221121ee1c7986f9c775b77b9691a0ae15)) +- Don't return builders from API data (#7584) ([549716e](https://github.com/discordjs/discord.js/commit/549716e4fcec89ca81216a6d22aa8e623175e37a)) +- Remove obsolete builder methods (#7590) ([10607db](https://github.com/discordjs/discord.js/commit/10607dbdafe257c5cbf5b952b7eecec4919e8b4a)) +- **Embed:** Remove add field (#7522) ([8478d2f](https://github.com/discordjs/discord.js/commit/8478d2f4de9ac013733850cbbc67902f7c5abc55)) +- Make `data` public in builders (#7486) ([ba31203](https://github.com/discordjs/discord.js/commit/ba31203a0ad96e0a00f8312c397889351e4c5cfd)) +- **embed:** Remove array support in favor of rest params (#7498) ([b3fa2ec](https://github.com/discordjs/discord.js/commit/b3fa2ece402839008738ad3adce3db958445838d)) +- **components:** Default set boolean methods to true (#7502) ([b122149](https://github.com/discordjs/discord.js/commit/b12214922cea2f43afbe6b1555a74a3c8e16f798)) +- Make public builder props getters (#7422) ([e8252ed](https://github.com/discordjs/discord.js/commit/e8252ed3b981a4b7e4013f12efadd2f5d9318d3e)) +- **builders-methods:** Make methods consistent (#7395) ([f495364](https://github.com/discordjs/discord.js/commit/f4953647ff9f39127978c73bf8a62c08462802ca)) +- Remove conditional autocomplete option return types (#7396) ([0909824](https://github.com/discordjs/discord.js/commit/09098240bfb13b8afafa4ab549f06d236e0ff1c9)) +- **embed:** Mark properties as readonly (#7332) ([31768fc](https://github.com/discordjs/discord.js/commit/31768fcd69ed5b4566a340bda89ce881418e8272)) + +## Typings + +- Fix regressions (#7649) ([5748dbe](https://github.com/discordjs/discord.js/commit/5748dbe08783beb80c526de38ccd105eb0e82664)) + +# [@discordjs/builders@0.12.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@0.11.0...@discordjs/builders@0.12.0) - (2022-01-24) + +## Bug Fixes + +- **builders:** Dont export `Button` component stuff twice (#7289) ([86d9d06](https://github.com/discordjs/discord.js/commit/86d9d0674347c08d056cd054cb4ce4253195bf94)) + +## Documentation + +- **SlashCommandSubcommands:** Updating old links from Discord developer portal (#7224) ([bd7a6f2](https://github.com/discordjs/discord.js/commit/bd7a6f265212624199fb0b2ddc8ece39759c63de)) + +## Features + +- Add components to /builders (#7195) ([2bb40fd](https://github.com/discordjs/discord.js/commit/2bb40fd767cf5918e3ba422ff73082734bfa05b0)) + +## Typings + +- Make `required` a boolean (#7307) ([c10afea](https://github.com/discordjs/discord.js/commit/c10afeadc702ab98bec5e077b3b92494a9596f9c)) diff --git a/node_modules/@discordjs/builders/LICENSE b/node_modules/@discordjs/builders/LICENSE new file mode 100644 index 0000000..cbe9c65 --- /dev/null +++ b/node_modules/@discordjs/builders/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/builders/README.md b/node_modules/@discordjs/builders/README.md new file mode 100644 index 0000000..59508dd --- /dev/null +++ b/node_modules/@discordjs/builders/README.md @@ -0,0 +1,70 @@ +
+
+

+ discord.js +

+
+

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

+

+ Vercel +

+
+ +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh-session +npm install @discordjs/builders +yarn add @discordjs/builders +pnpm add @discordjs/builders +``` + +## Examples + +Here are some examples for the builders and utilities you can find in this package: + +- [Slash Command Builders][example] + +## 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. +- [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]. + +[example]: https://github.com/discordjs/discord.js/blob/main/packages/builders/docs/examples/Slash%20Command%20Builders.md +[website]: https://discord.js.org/ +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/#/docs/builders +[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/builders +[npm]: https://www.npmjs.com/package/@discordjs/builders +[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/builders/dist/index.d.ts b/node_modules/@discordjs/builders/dist/index.d.ts new file mode 100644 index 0000000..b648419 --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.d.ts @@ -0,0 +1,1564 @@ +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'; +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; +declare const fieldInlinePredicate: _sapphire_shapeshift.UnionValidator; +declare const embedFieldPredicate: _sapphire_shapeshift.ObjectValidator<{ + name: string; + value: string; + inline: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>>; +declare const embedFieldsArrayPredicate: _sapphire_shapeshift.ArrayValidator<_sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>[], _sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>>; +declare const fieldLengthPredicate: _sapphire_shapeshift.NumberValidator; +declare function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void; +declare const authorNamePredicate: _sapphire_shapeshift.UnionValidator; +declare const imageURLPredicate: _sapphire_shapeshift.UnionValidator; +declare const urlPredicate: _sapphire_shapeshift.UnionValidator; +declare const embedAuthorPredicate: _sapphire_shapeshift.ObjectValidator<{ + name: string | null; + iconURL: string | null | undefined; + url: string | null | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name: string | null; + iconURL: string | null | undefined; + url: string | null | undefined; +}>>; +declare const RGBPredicate: _sapphire_shapeshift.NumberValidator; +declare const colorPredicate: _sapphire_shapeshift.UnionValidator; +declare const descriptionPredicate: _sapphire_shapeshift.UnionValidator; +declare const footerTextPredicate: _sapphire_shapeshift.UnionValidator; +declare const embedFooterPredicate: _sapphire_shapeshift.ObjectValidator<{ + text: string | null; + iconURL: string | null | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + text: string | null; + iconURL: string | null | undefined; +}>>; +declare const timestampPredicate: _sapphire_shapeshift.UnionValidator; +declare const titlePredicate: _sapphire_shapeshift.UnionValidator; + +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_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_RGBPredicate as RGBPredicate, + Assertions$5_authorNamePredicate as authorNamePredicate, + Assertions$5_colorPredicate as colorPredicate, + Assertions$5_descriptionPredicate as descriptionPredicate, + 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, + }; +} + +declare function normalizeArray(arr: RestOrArray): T[]; +type RestOrArray = T[] | [T[]]; + +type RGBTuple = [red: number, green: number, blue: number]; +interface IconData { + /** + * The URL of the icon + */ + iconURL?: string; + /** + * The proxy URL of the icon + */ + proxyIconURL?: string; +} +type EmbedAuthorData = IconData & Omit; +type EmbedAuthorOptions = Omit; +type EmbedFooterData = IconData & Omit; +type EmbedFooterOptions = Omit; +interface EmbedImageData extends Omit { + /** + * The proxy URL for the image + */ + proxyURL?: string; +} +/** + * Represents a embed in a message (image/video preview, rich embed, etc.) + */ +declare class EmbedBuilder { + readonly data: APIEmbed; + constructor(data?: APIEmbed); + /** + * 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: RestOrArray): this; + /** + * Removes, replaces, or inserts fields in the 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: number, deleteCount: number, ...fields: APIEmbedField[]): this; + /** + * Sets the embed's fields + * + * @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: RestOrArray): this; + /** + * Sets the author of this embed + * + * @param options - The options for the author + */ + setAuthor(options: EmbedAuthorOptions | null): this; + /** + * Sets the color of this embed + * + * @param color - The color of the embed + */ + setColor(color: RGBTuple | number | null): this; + /** + * Sets the description of this embed + * + * @param description - The description + */ + setDescription(description: string | null): this; + /** + * Sets the footer of this embed + * + * @param options - The options for the footer + */ + setFooter(options: EmbedFooterOptions | null): this; + /** + * Sets the image of this embed + * + * @param url - The URL of the image + */ + setImage(url: string | null): this; + /** + * Sets the thumbnail of this embed + * + * @param url - The URL of the thumbnail + */ + setThumbnail(url: string | null): this; + /** + * Sets the timestamp of this embed + * + * @param timestamp - The timestamp or date + */ + setTimestamp(timestamp?: Date | number | null): this; + /** + * Sets the title of this embed + * + * @param title - The title + */ + setTitle(title: string | null): this; + /** + * Sets the URL of this embed + * + * @param url - The URL + */ + setURL(url: string | null): this; + /** + * Transforms the embed to a plain object + */ + toJSON(): APIEmbed; +} + +/** + * Represents an option within a string select menu component + */ +declare class StringSelectMenuOptionBuilder implements JSONEncodable { + data: Partial; + /** + * 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?: Partial); + /** + * Sets the label of this option + * + * @param label - The label to show on this option + */ + setLabel(label: string): this; + /** + * Sets the value of this option + * + * @param value - The value of this option + */ + setValue(value: string): this; + /** + * Sets the description of this option + * + * @param description - The description of this option + */ + setDescription(description: string): this; + /** + * 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 + * + * @param emoji - The emoji to display on this option + */ + setEmoji(emoji: APIMessageComponentEmoji): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APISelectMenuOption; +} + +declare const customIdValidator: _sapphire_shapeshift.StringValidator; +declare const emojiValidator: _sapphire_shapeshift.ObjectValidator<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; +}>>; +declare const disabledValidator: _sapphire_shapeshift.BooleanValidator; +declare const buttonLabelValidator: _sapphire_shapeshift.StringValidator; +declare const buttonStyleValidator: _sapphire_shapeshift.NativeEnumValidator; +declare const placeholderValidator$1: _sapphire_shapeshift.StringValidator; +declare const minMaxValidator: _sapphire_shapeshift.NumberValidator; +declare const labelValueDescriptionValidator: _sapphire_shapeshift.StringValidator; +declare const jsonOptionValidator: _sapphire_shapeshift.ObjectValidator<{ + label: string; + value: string; + description: string | undefined; + emoji: _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; + }> | undefined; + default: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + label: string; + value: string; + description: string | undefined; + emoji: _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; + }> | undefined; + default: boolean | undefined; +}>>; +declare const optionValidator: _sapphire_shapeshift.InstanceValidator; +declare const optionsValidator: _sapphire_shapeshift.ArrayValidator; +declare const optionsLengthValidator: _sapphire_shapeshift.NumberValidator; +declare function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string): void; +declare const defaultValidator: _sapphire_shapeshift.BooleanValidator; +declare function validateRequiredSelectMenuOptionParameters(label?: string, value?: string): void; +declare const channelTypesValidator: _sapphire_shapeshift.ArrayValidator; +declare const urlValidator: _sapphire_shapeshift.StringValidator; +declare function validateRequiredButtonParameters(style?: ButtonStyle, label?: string, emoji?: APIMessageComponentEmoji, customId?: string, url?: string): void; + +declare const Assertions$4_buttonLabelValidator: typeof buttonLabelValidator; +declare const Assertions$4_buttonStyleValidator: typeof buttonStyleValidator; +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_optionsLengthValidator: typeof optionsLengthValidator; +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_buttonLabelValidator as buttonLabelValidator, + Assertions$4_buttonStyleValidator as buttonStyleValidator, + 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_optionsLengthValidator as optionsLengthValidator, + 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, + }; +} + +type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes; +/** + * Represents a discord component + * + * @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 + */ + readonly data: Partial; + /** + * Serializes this component to an API-compatible JSON object + * + * @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; + constructor(data: Partial); +} + +/** + * Represents a button component + */ +declare class ButtonBuilder 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?: Partial); + /** + * Sets the style of this button + * + * @param style - The style of the button + */ + setStyle(style: ButtonStyle): 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 open when this button is clicked + */ + setURL(url: string): 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 for this button + */ + setCustomId(customId: string): this; + /** + * Sets the emoji to display on this button + * + * @param emoji - The emoji to display on this button + */ + setEmoji(emoji: APIMessageComponentEmoji): this; + /** + * Sets whether this button is disabled + * + * @param disabled - Whether to disable this button + */ + setDisabled(disabled?: boolean): this; + /** + * Sets the label for this button + * + * @param label - The label to display on this button + */ + setLabel(label: string): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIButtonComponent; +} + +declare class BaseSelectMenuBuilder extends ComponentBuilder { + /** + * Sets the placeholder for this select menu + * + * @param placeholder - The placeholder to use for this select menu + */ + setPlaceholder(placeholder: string): this; + /** + * 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 + * + * @param maxValues - The maximum values that must be selected + */ + setMaxValues(maxValues: number): this; + /** + * Sets the custom id for this select menu + * + * @param customId - The custom id to use for this select menu + */ + setCustomId(customId: string): this; + /** + * Sets whether this select menu is disabled + * + * @param disabled - Whether this select menu is disabled + */ + setDisabled(disabled?: boolean): this; + toJSON(): SelectMenuType; +} + +declare class ChannelSelectMenuBuilder 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?: Partial); + addChannelTypes(...types: RestOrArray): this; + setChannelTypes(...types: RestOrArray): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIChannelSelectComponent; +} + +declare class MentionableSelectMenuBuilder 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?: Partial); +} + +declare class RoleSelectMenuBuilder 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?: Partial); +} + +/** + * Represents a string select menu component + */ +declare class StringSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * The options within this select menu + */ + readonly options: StringSelectMenuOptionBuilder[]; + /** + * 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?: Partial); + /** + * Adds options to this select menu + * + * @param options - The options to add to this select menu + * @returns + */ + addOptions(...options: RestOrArray): this; + /** + * Sets the options on this select menu + * + * @param options - The options to set on this select menu + */ + setOptions(...options: RestOrArray): this; + /** + * Removes, replaces, or inserts options in the string 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 order of the already-existing options of a string select menu. + * @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 ComponentBuilder.toJSON} + */ + toJSON(): APIStringSelectComponent; +} + +declare class UserSelectMenuBuilder 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?: Partial); +} + +declare class TextInputBuilder extends ComponentBuilder implements Equatable> { + /** + * 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?: APITextInputComponent & { + type?: ComponentType.TextInput; + }); + /** + * Sets the custom id for this text input + * + * @param customId - The custom id of this text input + */ + setCustomId(customId: string): this; + /** + * Sets the label for this text input + * + * @param label - The label for this text input + */ + setLabel(label: string): this; + /** + * Sets the style for this text input + * + * @param style - The style for this text input + */ + setStyle(style: TextInputStyle): this; + /** + * 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 + * + * @param maxLength - The maximum length of text for this text input + */ + setMaxLength(maxLength: number): this; + /** + * Sets the placeholder of this text input + * + * @param placeholder - The placeholder of this text input + */ + setPlaceholder(placeholder: string): this; + /** + * Sets the value of this text input + * + * @param value - The value for this text input + */ + setValue(value: string): this; + /** + * Sets whether this text input is required + * + * @param required - Whether this text input is required + */ + setRequired(required?: boolean): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APITextInputComponent; + /** + * {@inheritDoc Equatable.equals} + */ + equals(other: APITextInputComponent | JSONEncodable): boolean; +} + +type MessageComponentBuilder = ActionRowBuilder | MessageActionRowComponentBuilder; +type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder; +type MessageActionRowComponentBuilder = ButtonBuilder | ChannelSelectMenuBuilder | MentionableSelectMenuBuilder | RoleSelectMenuBuilder | StringSelectMenuBuilder | UserSelectMenuBuilder; +type ModalActionRowComponentBuilder = TextInputBuilder; +type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder; +/** + * Represents an action row component + * + * @typeParam T - The types of components this action row holds + */ +declare class ActionRowBuilder extends ComponentBuilder> { + /** + * The components within this action row + */ + readonly components: T[]; + /** + * 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 }?: Partial>); + /** + * Adds components to this action row. + * + * @param components - The components to add to this action row. + */ + addComponents(...components: RestOrArray): this; + /** + * Sets the components in this action row + * + * @param components - The components to set this row to + */ + setComponents(...components: RestOrArray): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIActionRowComponent>; +} + +interface MappedComponentTypes { + [ComponentType.ActionRow]: ActionRowBuilder; + [ComponentType.Button]: ButtonBuilder; + [ComponentType.StringSelect]: StringSelectMenuBuilder; + [ComponentType.TextInput]: TextInputBuilder; + [ComponentType.UserSelect]: UserSelectMenuBuilder; + [ComponentType.RoleSelect]: RoleSelectMenuBuilder; + [ComponentType.MentionableSelect]: MentionableSelectMenuBuilder; + [ComponentType.ChannelSelect]: ChannelSelectMenuBuilder; +} +/** + * Factory for creating components from API data + * + * @param data - The api data to transform to a component class + */ +declare function createComponentBuilder(data: (APIModalComponent | APIMessageComponent) & { + type: T; +}): MappedComponentTypes[T]; +declare function createComponentBuilder(data: C): C; + +declare const textInputStyleValidator: _sapphire_shapeshift.NativeEnumValidator; +declare const minLengthValidator: _sapphire_shapeshift.NumberValidator; +declare const maxLengthValidator: _sapphire_shapeshift.NumberValidator; +declare const requiredValidator: _sapphire_shapeshift.BooleanValidator; +declare const valueValidator: _sapphire_shapeshift.StringValidator; +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_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 namespace Assertions$3 { + export { + Assertions$3_labelValidator as labelValidator, + Assertions$3_maxLengthValidator as maxLengthValidator, + Assertions$3_minLengthValidator as minLengthValidator, + Assertions$3_placeholderValidator as placeholderValidator, + Assertions$3_requiredValidator as requiredValidator, + Assertions$3_textInputStyleValidator as textInputStyleValidator, + validateRequiredParameters$3 as validateRequiredParameters, + Assertions$3_valueValidator as valueValidator, + }; +} + +declare class ModalBuilder implements JSONEncodable { + readonly data: Partial; + readonly components: ActionRowBuilder[]; + constructor({ components, ...data }?: Partial); + /** + * Sets the title of the modal + * + * @param title - The title of the modal + */ + setTitle(title: string): this; + /** + * Sets the custom id of the modal + * + * @param customId - The custom id of this modal + */ + setCustomId(customId: string): this; + /** + * Adds components to this modal + * + * @param components - The components to add to this modal + */ + addComponents(...components: RestOrArray | APIActionRowComponent>): this; + /** + * Sets the components in this modal + * + * @param components - The components to set this modal to + */ + setComponents(...components: RestOrArray>): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIModalInteractionResponseCallbackData; +} + +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_componentsValidator: typeof componentsValidator; +declare const Assertions$2_titleValidator: typeof titleValidator; +declare namespace Assertions$2 { + export { + Assertions$2_componentsValidator as componentsValidator, + Assertions$2_titleValidator as titleValidator, + validateRequiredParameters$2 as validateRequiredParameters, + }; +} + +declare class SharedNameAndDescription { + readonly name: string; + readonly name_localizations?: LocalizationMap; + readonly description: string; + readonly description_localizations?: LocalizationMap; + /** + * Sets the name + * + * @param name - The name + */ + setName(name: string): this; + /** + * Sets the description + * + * @param description - The description + */ + setDescription(description: string): this; + /** + * Sets a name localization + * + * @param locale - The locale to set a description for + * @param localizedName - The localized description for the given locale + */ + setNameLocalization(locale: LocaleString, localizedName: string | null): this; + /** + * Sets the name localizations + * + * @param localizedNames - The dictionary of localized descriptions to set + */ + setNameLocalizations(localizedNames: LocalizationMap | null): this; + /** + * Sets a description localization + * + * @param locale - The locale to set a description for + * @param localizedDescription - The localized description for the given locale + */ + setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null): this; + /** + * Sets the description localizations + * + * @param localizedDescriptions - The dictionary of localized descriptions to set + */ + setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null): this; +} + +declare abstract class ApplicationCommandOptionBase extends SharedNameAndDescription { + abstract readonly type: ApplicationCommandOptionType; + readonly required: boolean; + /** + * Marks the option as required + * + * @param required - If this option should be required + */ + setRequired(required: boolean): this; + abstract toJSON(): APIApplicationCommandBasicOption; + protected runRequiredValidations(): void; +} + +declare class SlashCommandAttachmentOption extends ApplicationCommandOptionBase { + readonly type: ApplicationCommandOptionType.Attachment; + toJSON(): APIApplicationCommandAttachmentOption; +} + +declare class SlashCommandBooleanOption extends ApplicationCommandOptionBase { + readonly type: ApplicationCommandOptionType.Boolean; + toJSON(): APIApplicationCommandBooleanOption; +} + +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]; +declare class ApplicationCommandOptionChannelTypesMixin { + readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[]; + /** + * Adds channel types to this option + * + * @param channelTypes - The channel types to add + */ + addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]): this; +} + +declare class SlashCommandChannelOption extends ApplicationCommandOptionBase { + readonly type: ApplicationCommandOptionType.Channel; + toJSON(): APIApplicationCommandChannelOption; +} +interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin { +} + +declare abstract class ApplicationCommandNumericOptionMinMaxValueMixin { + readonly max_value?: number; + readonly min_value?: number; + /** + * 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 + * + * @param min - The minimum value this option can be + */ + abstract setMinValue(min: number): this; +} + +declare class ApplicationCommandOptionWithChoicesAndAutocompleteMixin { + readonly choices?: APIApplicationCommandOptionChoice[]; + readonly autocomplete?: boolean; + readonly type: ApplicationCommandOptionType; + /** + * Adds multiple choices for this option + * + * @param choices - The choices to add + */ + addChoices(...choices: APIApplicationCommandOptionChoice[]): this; + setChoices[]>(...choices: Input): this; + /** + * Marks the option as autocompletable + * + * @param autocomplete - If this option should be autocompletable + */ + setAutocomplete(autocomplete: boolean): this; +} + +declare class SlashCommandIntegerOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + readonly type: ApplicationCommandOptionType.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max: number): this; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min: number): this; + toJSON(): APIApplicationCommandIntegerOption; +} +interface SlashCommandIntegerOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +declare class SlashCommandMentionableOption extends ApplicationCommandOptionBase { + readonly type: ApplicationCommandOptionType.Mentionable; + toJSON(): APIApplicationCommandMentionableOption; +} + +declare class SlashCommandNumberOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + readonly type: ApplicationCommandOptionType.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max: number): this; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min: number): this; + toJSON(): APIApplicationCommandNumberOption; +} +interface SlashCommandNumberOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +declare class SlashCommandRoleOption extends ApplicationCommandOptionBase { + readonly type: ApplicationCommandOptionType.Role; + toJSON(): APIApplicationCommandRoleOption; +} + +declare class SlashCommandStringOption extends ApplicationCommandOptionBase { + readonly type: ApplicationCommandOptionType.String; + readonly max_length?: number; + readonly min_length?: number; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ + setMaxLength(max: number): this; + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ + setMinLength(min: number): this; + toJSON(): APIApplicationCommandStringOption; +} +interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +declare class SlashCommandUserOption extends ApplicationCommandOptionBase { + readonly type: ApplicationCommandOptionType.User; + toJSON(): APIApplicationCommandUserOption; +} + +declare class SharedSlashCommandOptions { + readonly options: ToAPIApplicationCommandOptions[]; + /** + * Adds a boolean option + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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; + private _sharedAddOptionMethod; +} + +/** + * Represents a folder for subcommands + * + * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups + */ +declare class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions { + /** + * The name of this subcommand group + */ + readonly name: string; + /** + * The description of this subcommand group + */ + readonly description: string; + /** + * The subcommands part of this subcommand group + */ + readonly options: SlashCommandSubcommandBuilder[]; + /** + * Adds a new subcommand to this group + * + * @param input - A function that returns a subcommand builder, or an already built builder + */ + addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): this; + toJSON(): APIApplicationCommandSubcommandGroupOption; +} +interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription { +} +/** + * Represents a subcommand + * + * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups + */ +declare class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions { + /** + * The name of this subcommand + */ + readonly name: string; + /** + * The description of this subcommand + */ + readonly description: string; + /** + * The options of this subcommand + */ + readonly options: ApplicationCommandOptionBase[]; + toJSON(): APIApplicationCommandSubcommandOption; +} +interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { +} + +declare class SlashCommandBuilder { + /** + * The name of this slash command + */ + readonly name: string; + /** + * The localized names for this command + */ + readonly name_localizations?: LocalizationMap; + /** + * The description of this slash command + */ + readonly description: string; + /** + * The localized descriptions for this command + */ + readonly description_localizations?: LocalizationMap; + /** + * The options of this slash command + */ + readonly options: ToAPIApplicationCommandOptions[]; + /** + * Whether the command is enabled by default when the app 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. + */ + readonly default_permission: boolean | undefined; + /** + * 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. + */ + readonly dm_permission: boolean | undefined; + /** + * Whether this command is NSFW + */ + readonly nsfw: 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. + */ + toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody; + /** + * 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. + */ + setDefaultPermission(value: boolean): 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 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. + * + * @param enabled - If the command should be enabled in DMs + * @see https://discord.com/developers/docs/interactions/application-commands#permissions + */ + setDMPermission(enabled: boolean | null | undefined): this; + /** + * 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 + */ + addSubcommandGroup(input: SlashCommandSubcommandGroupBuilder | ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder)): SlashCommandSubcommandsOnlyBuilder; + /** + * Adds a new subcommand to this command + * + * @param input - A function that returns a subcommand builder, or an already built builder + */ + addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): SlashCommandSubcommandsOnlyBuilder; +} +interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { +} +interface SlashCommandSubcommandsOnlyBuilder extends Omit> { +} +interface SlashCommandOptionsOnlyBuilder extends SharedNameAndDescription, SharedSlashCommandOptions, Pick { +} +interface ToAPIApplicationCommandOptions { + toJSON(): APIApplicationCommandOption; +} + +declare function validateName$1(name: unknown): asserts name is string; +declare function validateDescription(description: unknown): asserts description is string; +declare function validateLocale(locale: unknown): Locale; +declare function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[]; +declare function validateRequiredParameters$1(name: string, description: string, options: ToAPIApplicationCommandOptions[]): void; +declare function validateDefaultPermission$1(value: unknown): asserts value is boolean; +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 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 namespace Assertions$1 { + export { + Assertions$1_assertReturnOfBuilder as assertReturnOfBuilder, + Assertions$1_localizationMapPredicate as localizationMapPredicate, + 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, + }; +} + +declare class ContextMenuCommandBuilder { + /** + * The name of this context menu command + */ + readonly name: string; + /** + * The localized names for this command + */ + readonly name_localizations?: LocalizationMap; + /** + * The type of this context menu command + */ + readonly type: ContextMenuCommandType; + /** + * Whether the command is enabled by default when the app 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. + */ + readonly default_permission: boolean | undefined; + /** + * 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. + */ + readonly dm_permission: boolean | undefined; + /** + * Sets the name + * + * @param name - The name + */ + setName(name: string): this; + /** + * Sets the type + * + * @param type - The type + */ + setType(type: ContextMenuCommandType): 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 or not to enable this command by default + * @see 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. + * + * @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 + */ + 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. + * + * @param enabled - If the command should be enabled in DMs + * @see https://discord.com/developers/docs/interactions/application-commands#permissions + */ + setDMPermission(enabled: boolean | null | undefined): this; + /** + * Sets a name localization + * + * @param locale - The locale to set a description for + * @param localizedName - The localized description for the given locale + */ + setNameLocalization(locale: LocaleString, localizedName: string | null): this; + /** + * Sets the name localizations + * + * @param localizedNames - The dictionary of localized descriptions to set + */ + setNameLocalizations(localizedNames: LocalizationMap | null): this; + /** + * 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. + */ + 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; +declare function validateType(type: unknown): asserts type is ContextMenuCommandType; +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_validateRequiredParameters: typeof validateRequiredParameters; +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_validateRequiredParameters as validateRequiredParameters, + Assertions_validateType as validateType, + }; +} + +declare function embedLength(data: APIEmbed): number; + +declare const enableValidators: () => boolean; +declare const disableValidators: () => boolean; +declare const isValidationEnabled: () => boolean; + +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders/#readme | @discordjs/builders} version + * that you are currently using. + */ +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, 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 new file mode 100644 index 0000000..992fe9f --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.js @@ -0,0 +1,2446 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +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 __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 +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + ActionRowBuilder: () => ActionRowBuilder, + ApplicationCommandNumericOptionMinMaxValueMixin: () => ApplicationCommandNumericOptionMinMaxValueMixin, + ApplicationCommandOptionBase: () => ApplicationCommandOptionBase, + ApplicationCommandOptionChannelTypesMixin: () => ApplicationCommandOptionChannelTypesMixin, + ApplicationCommandOptionWithChoicesAndAutocompleteMixin: () => ApplicationCommandOptionWithChoicesAndAutocompleteMixin, + BaseSelectMenuBuilder: () => BaseSelectMenuBuilder, + ButtonBuilder: () => ButtonBuilder, + ChannelSelectMenuBuilder: () => ChannelSelectMenuBuilder, + ComponentAssertions: () => Assertions_exports2, + ComponentBuilder: () => ComponentBuilder, + ContextMenuCommandAssertions: () => Assertions_exports6, + ContextMenuCommandBuilder: () => ContextMenuCommandBuilder, + EmbedAssertions: () => Assertions_exports, + EmbedBuilder: () => EmbedBuilder, + MentionableSelectMenuBuilder: () => MentionableSelectMenuBuilder, + ModalAssertions: () => Assertions_exports4, + ModalBuilder: () => ModalBuilder, + RoleSelectMenuBuilder: () => RoleSelectMenuBuilder, + SelectMenuBuilder: () => StringSelectMenuBuilder, + SelectMenuOptionBuilder: () => StringSelectMenuOptionBuilder, + SharedNameAndDescription: () => SharedNameAndDescription, + SharedSlashCommandOptions: () => SharedSlashCommandOptions, + SlashCommandAssertions: () => Assertions_exports5, + SlashCommandAttachmentOption: () => SlashCommandAttachmentOption, + SlashCommandBooleanOption: () => SlashCommandBooleanOption, + SlashCommandBuilder: () => SlashCommandBuilder, + SlashCommandChannelOption: () => SlashCommandChannelOption, + SlashCommandIntegerOption: () => SlashCommandIntegerOption, + SlashCommandMentionableOption: () => SlashCommandMentionableOption, + SlashCommandNumberOption: () => SlashCommandNumberOption, + SlashCommandRoleOption: () => SlashCommandRoleOption, + SlashCommandStringOption: () => SlashCommandStringOption, + SlashCommandSubcommandBuilder: () => SlashCommandSubcommandBuilder, + SlashCommandSubcommandGroupBuilder: () => SlashCommandSubcommandGroupBuilder, + SlashCommandUserOption: () => SlashCommandUserOption, + StringSelectMenuBuilder: () => StringSelectMenuBuilder, + StringSelectMenuOptionBuilder: () => StringSelectMenuOptionBuilder, + TextInputAssertions: () => Assertions_exports3, + TextInputBuilder: () => TextInputBuilder, + UserSelectMenuBuilder: () => UserSelectMenuBuilder, + createComponentBuilder: () => createComponentBuilder, + disableValidators: () => disableValidators, + embedLength: () => embedLength, + enableValidators: () => enableValidators, + isValidationEnabled: () => isValidationEnabled, + normalizeArray: () => normalizeArray, + version: () => version +}); +module.exports = __toCommonJS(src_exports); + +// src/messages/embed/Assertions.ts +var Assertions_exports = {}; +__export(Assertions_exports, { + RGBPredicate: () => RGBPredicate, + authorNamePredicate: () => authorNamePredicate, + colorPredicate: () => colorPredicate, + descriptionPredicate: () => descriptionPredicate, + embedAuthorPredicate: () => embedAuthorPredicate, + embedFieldPredicate: () => embedFieldPredicate, + embedFieldsArrayPredicate: () => embedFieldsArrayPredicate, + embedFooterPredicate: () => embedFooterPredicate, + fieldInlinePredicate: () => fieldInlinePredicate, + fieldLengthPredicate: () => fieldLengthPredicate, + fieldNamePredicate: () => fieldNamePredicate, + fieldValuePredicate: () => fieldValuePredicate, + footerTextPredicate: () => footerTextPredicate, + imageURLPredicate: () => imageURLPredicate, + timestampPredicate: () => timestampPredicate, + titlePredicate: () => titlePredicate, + urlPredicate: () => urlPredicate, + validateFieldLength: () => validateFieldLength +}); +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"); + +// src/messages/embed/Assertions.ts +var fieldNamePredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(256).setValidationEnabled(isValidationEnabled); +var fieldValuePredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(1024).setValidationEnabled(isValidationEnabled); +var fieldInlinePredicate = import_shapeshift.s.boolean.optional; +var embedFieldPredicate = import_shapeshift.s.object({ + name: fieldNamePredicate, + value: fieldValuePredicate, + inline: fieldInlinePredicate +}).setValidationEnabled(isValidationEnabled); +var embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled); +var fieldLengthPredicate = import_shapeshift.s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateFieldLength(amountAdding, fields) { + fieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding); +} +__name(validateFieldLength, "validateFieldLength"); +var authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled); +var imageURLPredicate = import_shapeshift.s.string.url({ + allowedProtocols: [ + "http:", + "https:", + "attachment:" + ] +}).nullish.setValidationEnabled(isValidationEnabled); +var urlPredicate = import_shapeshift.s.string.url({ + allowedProtocols: [ + "http:", + "https:" + ] +}).nullish.setValidationEnabled(isValidationEnabled); +var embedAuthorPredicate = import_shapeshift.s.object({ + name: authorNamePredicate, + iconURL: imageURLPredicate, + url: urlPredicate +}).setValidationEnabled(isValidationEnabled); +var RGBPredicate = import_shapeshift.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(255).setValidationEnabled(isValidationEnabled); +var colorPredicate = import_shapeshift.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(16777215).or(import_shapeshift.s.tuple([ + RGBPredicate, + RGBPredicate, + RGBPredicate +])).nullable.setValidationEnabled(isValidationEnabled); +var descriptionPredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(4096).nullable.setValidationEnabled(isValidationEnabled); +var footerTextPredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(2048).nullable.setValidationEnabled(isValidationEnabled); +var embedFooterPredicate = import_shapeshift.s.object({ + text: footerTextPredicate, + iconURL: imageURLPredicate +}).setValidationEnabled(isValidationEnabled); +var timestampPredicate = import_shapeshift.s.union(import_shapeshift.s.number, import_shapeshift.s.date).nullable.setValidationEnabled(isValidationEnabled); +var titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled); + +// src/util/normalizeArray.ts +function normalizeArray(arr) { + if (Array.isArray(arr[0])) + return arr[0]; + return arr; +} +__name(normalizeArray, "normalizeArray"); + +// src/messages/embed/Embed.ts +var EmbedBuilder = class { + 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); + if (this.data.fields) + this.data.fields.push(...fields); + else + this.data.fields = fields; + return this; + } + /** + * Removes, replaces, or inserts fields in the 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); + if (this.data.fields) + this.data.fields.splice(index, deleteCount, ...fields); + else + this.data.fields = fields; + return this; + } + /** + * Sets the embed's fields + * + * @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 for the author + */ + setAuthor(options) { + if (options === null) { + this.data.author = void 0; + return this; + } + embedAuthorPredicate.parse(options); + 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 of the embed + */ + setColor(color) { + colorPredicate.parse(color); + if (Array.isArray(color)) { + const [red, green, blue] = color; + this.data.color = (red << 16) + (green << 8) + blue; + return this; + } + this.data.color = color ?? void 0; + return this; + } + /** + * Sets the description of this embed + * + * @param description - The description + */ + setDescription(description) { + descriptionPredicate.parse(description); + this.data.description = description ?? void 0; + return this; + } + /** + * Sets the footer of this embed + * + * @param options - The options for the footer + */ + setFooter(options) { + if (options === null) { + this.data.footer = void 0; + return this; + } + embedFooterPredicate.parse(options); + this.data.footer = { + text: options.text, + icon_url: options.iconURL + }; + return this; + } + /** + * Sets the image of this embed + * + * @param url - The URL of the image + */ + setImage(url) { + imageURLPredicate.parse(url); + this.data.image = url ? { + url + } : void 0; + return this; + } + /** + * Sets the thumbnail of this embed + * + * @param url - The URL of the thumbnail + */ + 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 + */ + setTimestamp(timestamp = Date.now()) { + timestampPredicate.parse(timestamp); + this.data.timestamp = timestamp ? new Date(timestamp).toISOString() : void 0; + return this; + } + /** + * Sets the title of this embed + * + * @param title - The title + */ + setTitle(title) { + titlePredicate.parse(title); + this.data.title = title ?? void 0; + return this; + } + /** + * Sets the URL of this embed + * + * @param url - The URL + */ + setURL(url) { + urlPredicate.parse(url); + this.data.url = url ?? void 0; + return this; + } + /** + * Transforms the embed to a plain object + */ + toJSON() { + return { + ...this.data + }; + } +}; +__name(EmbedBuilder, "EmbedBuilder"); + +// src/index.ts +__reExport(src_exports, require("@discordjs/formatters"), module.exports); + +// src/components/Assertions.ts +var Assertions_exports2 = {}; +__export(Assertions_exports2, { + buttonLabelValidator: () => buttonLabelValidator, + buttonStyleValidator: () => buttonStyleValidator, + channelTypesValidator: () => channelTypesValidator, + customIdValidator: () => customIdValidator, + defaultValidator: () => defaultValidator, + disabledValidator: () => disabledValidator, + emojiValidator: () => emojiValidator, + jsonOptionValidator: () => jsonOptionValidator, + labelValueDescriptionValidator: () => labelValueDescriptionValidator, + minMaxValidator: () => minMaxValidator, + optionValidator: () => optionValidator, + optionsLengthValidator: () => optionsLengthValidator, + optionsValidator: () => optionsValidator, + placeholderValidator: () => placeholderValidator, + urlValidator: () => urlValidator, + validateRequiredButtonParameters: () => validateRequiredButtonParameters, + validateRequiredSelectMenuOptionParameters: () => validateRequiredSelectMenuOptionParameters, + validateRequiredSelectMenuParameters: () => validateRequiredSelectMenuParameters +}); +var import_shapeshift2 = require("@sapphire/shapeshift"); +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 of this option + * + * @param label - The label to show on this option + */ + setLabel(label) { + this.data.label = labelValueDescriptionValidator.parse(label); + return this; + } + /** + * Sets the value of this option + * + * @param value - The value of this option + */ + setValue(value) { + this.data.value = labelValueDescriptionValidator.parse(value); + return this; + } + /** + * Sets the description of this option + * + * @param description - The description of this option + */ + 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 on this option + * + * @param emoji - The emoji to display on this option + */ + setEmoji(emoji) { + this.data.emoji = emojiValidator.parse(emoji); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); + return { + ...this.data + }; + } +}; +__name(StringSelectMenuOptionBuilder, "StringSelectMenuOptionBuilder"); + +// src/components/Assertions.ts +var customIdValidator = import_shapeshift2.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var emojiValidator = import_shapeshift2.s.object({ + id: import_shapeshift2.s.string, + name: import_shapeshift2.s.string, + animated: import_shapeshift2.s.boolean +}).partial.strict.setValidationEnabled(isValidationEnabled); +var disabledValidator = import_shapeshift2.s.boolean; +var buttonLabelValidator = import_shapeshift2.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(80).setValidationEnabled(isValidationEnabled); +var buttonStyleValidator = import_shapeshift2.s.nativeEnum(import_v10.ButtonStyle); +var placeholderValidator = import_shapeshift2.s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled); +var minMaxValidator = import_shapeshift2.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +var labelValueDescriptionValidator = import_shapeshift2.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var jsonOptionValidator = import_shapeshift2.s.object({ + label: labelValueDescriptionValidator, + value: labelValueDescriptionValidator, + description: labelValueDescriptionValidator.optional, + emoji: emojiValidator.optional, + default: import_shapeshift2.s.boolean.optional +}).setValidationEnabled(isValidationEnabled); +var optionValidator = import_shapeshift2.s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled); +var optionsValidator = optionValidator.array.lengthGreaterThanOrEqual(0).setValidationEnabled(isValidationEnabled); +var optionsLengthValidator = import_shapeshift2.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateRequiredSelectMenuParameters(options, customId) { + customIdValidator.parse(customId); + optionsValidator.parse(options); +} +__name(validateRequiredSelectMenuParameters, "validateRequiredSelectMenuParameters"); +var defaultValidator = import_shapeshift2.s.boolean; +function validateRequiredSelectMenuOptionParameters(label, value) { + labelValueDescriptionValidator.parse(label); + labelValueDescriptionValidator.parse(value); +} +__name(validateRequiredSelectMenuOptionParameters, "validateRequiredSelectMenuOptionParameters"); +var channelTypesValidator = import_shapeshift2.s.nativeEnum(import_v10.ChannelType).array.setValidationEnabled(isValidationEnabled); +var urlValidator = import_shapeshift2.s.string.url({ + allowedProtocols: [ + "http:", + "https:", + "discord:" + ] +}).setValidationEnabled(isValidationEnabled); +function validateRequiredButtonParameters(style, label, emoji, customId, url) { + if (url && customId) { + throw new RangeError("URL and custom id are mutually exclusive"); + } + if (!label && !emoji) { + throw new RangeError("Buttons must have a label and/or an emoji"); + } + if (style === import_v10.ButtonStyle.Link) { + if (!url) { + throw new RangeError("Link buttons must have a url"); + } + } else if (url) { + throw new RangeError("Non-link buttons cannot have a url"); + } +} +__name(validateRequiredButtonParameters, "validateRequiredButtonParameters"); + +// src/components/ActionRow.ts +var import_v1011 = require("discord-api-types/v10"); + +// src/components/Component.ts +var ComponentBuilder = class { + constructor(data) { + this.data = data; + } +}; +__name(ComponentBuilder, "ComponentBuilder"); + +// src/components/Components.ts +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 of the button + */ + 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 open when this button is clicked + */ + 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 for this button + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets the emoji to display on this button + * + * @param emoji - The emoji to display on this button + */ + 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 display on this button + */ + setLabel(label) { + this.data.label = buttonLabelValidator.parse(label); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredButtonParameters(this.data.style, this.data.label, this.data.emoji, this.data.custom_id, this.data.url); + return { + ...this.data + }; + } +}; +__name(ButtonBuilder, "ButtonBuilder"); + +// src/components/selectMenu/ChannelSelectMenu.ts +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 for this select menu + */ + 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 for this select menu + */ + 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; + } + toJSON() { + customIdValidator.parse(this.data.custom_id); + return { + ...this.data + }; + } +}; +__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 + }); + } + addChannelTypes(...types) { + types = normalizeArray(types); + this.data.channel_types ??= []; + this.data.channel_types.push(...channelTypesValidator.parse(types)); + return this; + } + setChannelTypes(...types) { + types = normalizeArray(types); + this.data.channel_types ??= []; + this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types)); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + customIdValidator.parse(this.data.custom_id); + return { + ...this.data + }; + } +}; +__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 + }); + } +}; +__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 + }); + } +}; +__name(RoleSelectMenuBuilder, "RoleSelectMenuBuilder"); + +// src/components/selectMenu/StringSelectMenu.ts +var import_v106 = require("discord-api-types/v10"); +var StringSelectMenuBuilder = 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 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 to this select menu + * @returns + */ + addOptions(...options) { + options = normalizeArray(options); + optionsLengthValidator.parse(this.options.length + options.length); + this.options.push(...options.map((option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)))); + return this; + } + /** + * Sets the options on this select menu + * + * @param options - The options to set on this select menu + */ + setOptions(...options) { + return this.spliceOptions(0, this.options.length, ...options); + } + /** + * Removes, replaces, or inserts options in the string 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 order of the already-existing options of a string select menu. + * @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) { + options = normalizeArray(options); + const clone = [ + ...this.options + ]; + clone.splice(index, deleteCount, ...options.map((option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)))); + optionsLengthValidator.parse(clone.length); + this.options.splice(0, this.options.length, ...clone); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredSelectMenuParameters(this.options, this.data.custom_id); + return { + ...this.data, + options: this.options.map((option) => option.toJSON()) + }; + } +}; +__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 + }); + } +}; +__name(UserSelectMenuBuilder, "UserSelectMenuBuilder"); + +// src/components/textInput/TextInput.ts +var import_util = require("@discordjs/util"); +var import_v109 = require("discord-api-types/v10"); +var import_fast_deep_equal = __toESM(require("fast-deep-equal")); + +// src/components/textInput/Assertions.ts +var Assertions_exports3 = {}; +__export(Assertions_exports3, { + labelValidator: () => labelValidator, + maxLengthValidator: () => maxLengthValidator, + minLengthValidator: () => minLengthValidator, + placeholderValidator: () => placeholderValidator2, + requiredValidator: () => requiredValidator, + textInputStyleValidator: () => textInputStyleValidator, + validateRequiredParameters: () => validateRequiredParameters, + valueValidator: () => valueValidator +}); +var import_shapeshift3 = require("@sapphire/shapeshift"); +var import_v108 = require("discord-api-types/v10"); +var textInputStyleValidator = import_shapeshift3.s.nativeEnum(import_v108.TextInputStyle); +var minLengthValidator = import_shapeshift3.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var maxLengthValidator = import_shapeshift3.s.number.int.greaterThanOrEqual(1).lessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var requiredValidator = import_shapeshift3.s.boolean; +var valueValidator = import_shapeshift3.s.string.lengthLessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var placeholderValidator2 = import_shapeshift3.s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var labelValidator = import_shapeshift3.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(45).setValidationEnabled(isValidationEnabled); +function validateRequiredParameters(customId, style, label) { + customIdValidator.parse(customId); + textInputStyleValidator.parse(style); + labelValidator.parse(label); +} +__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 of this text input + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets the label for this text input + * + * @param label - The label for this text input + */ + setLabel(label) { + this.data.label = labelValidator.parse(label); + return this; + } + /** + * Sets the style for this text input + * + * @param style - The style for this text input + */ + 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 of this text input + * + * @param placeholder - The placeholder of this text input + */ + setPlaceholder(placeholder) { + this.data.placeholder = placeholderValidator2.parse(placeholder); + return this; + } + /** + * Sets the value of this text input + * + * @param value - The value for this text input + */ + 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); + } + return (0, import_fast_deep_equal.default)(other, this.data); + } +}; +__name(TextInputBuilder, "TextInputBuilder"); + +// src/components/Components.ts +function createComponentBuilder(data) { + if (data instanceof ComponentBuilder) { + return data; + } + switch (data.type) { + case import_v1010.ComponentType.ActionRow: + return new ActionRowBuilder(data); + case import_v1010.ComponentType.Button: + return new ButtonBuilder(data); + case import_v1010.ComponentType.StringSelect: + return new StringSelectMenuBuilder(data); + case import_v1010.ComponentType.TextInput: + return new TextInputBuilder(data); + case import_v1010.ComponentType.UserSelect: + return new UserSelectMenuBuilder(data); + case import_v1010.ComponentType.RoleSelect: + return new RoleSelectMenuBuilder(data); + case import_v1010.ComponentType.MentionableSelect: + return new MentionableSelectMenuBuilder(data); + case import_v1010.ComponentType.ChannelSelect: + return new ChannelSelectMenuBuilder(data); + default: + throw new Error(`Cannot properly serialize component type: ${data.type}`); + } +} +__name(createComponentBuilder, "createComponentBuilder"); + +// src/components/ActionRow.ts +var ActionRowBuilder = class extends ComponentBuilder { + /** + * 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 to this action row. + */ + addComponents(...components) { + this.components.push(...normalizeArray(components)); + return this; + } + /** + * Sets the components in this action row + * + * @param components - The components to set this row to + */ + setComponents(...components) { + this.components.splice(0, this.components.length, ...normalizeArray(components)); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + return { + ...this.data, + components: this.components.map((component) => component.toJSON()) + }; + } +}; +__name(ActionRowBuilder, "ActionRowBuilder"); + +// src/interactions/modals/Assertions.ts +var Assertions_exports4 = {}; +__export(Assertions_exports4, { + componentsValidator: () => componentsValidator, + titleValidator: () => titleValidator, + validateRequiredParameters: () => validateRequiredParameters2 +}); +var import_shapeshift4 = require("@sapphire/shapeshift"); +var titleValidator = import_shapeshift4.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(45).setValidationEnabled(isValidationEnabled); +var componentsValidator = import_shapeshift4.s.instance(ActionRowBuilder).array.lengthGreaterThanOrEqual(1).setValidationEnabled(isValidationEnabled); +function validateRequiredParameters2(customId, title, components) { + customIdValidator.parse(customId); + titleValidator.parse(title); + componentsValidator.parse(components); +} +__name(validateRequiredParameters2, "validateRequiredParameters"); + +// src/interactions/modals/Modal.ts +var ModalBuilder = class { + components = []; + constructor({ components, ...data } = {}) { + this.data = { + ...data + }; + this.components = components?.map((component) => createComponentBuilder(component)) ?? []; + } + /** + * Sets the title of the modal + * + * @param title - The title of the modal + */ + setTitle(title) { + this.data.title = titleValidator.parse(title); + return this; + } + /** + * Sets the custom id of the modal + * + * @param customId - The custom id of this modal + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Adds components to this modal + * + * @param components - The components to add to this modal + */ + addComponents(...components) { + this.components.push(...normalizeArray(components).map((component) => component instanceof ActionRowBuilder ? component : new ActionRowBuilder(component))); + return this; + } + /** + * Sets the components in this modal + * + * @param components - The components to set this modal to + */ + 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 { + ...this.data, + components: this.components.map((component) => component.toJSON()) + }; + } +}; +__name(ModalBuilder, "ModalBuilder"); + +// src/interactions/slashCommands/Assertions.ts +var Assertions_exports5 = {}; +__export(Assertions_exports5, { + assertReturnOfBuilder: () => assertReturnOfBuilder, + localizationMapPredicate: () => localizationMapPredicate, + validateChoicesLength: () => validateChoicesLength, + validateDMPermission: () => validateDMPermission, + validateDefaultMemberPermissions: () => validateDefaultMemberPermissions, + validateDefaultPermission: () => validateDefaultPermission, + validateDescription: () => validateDescription, + validateLocale: () => validateLocale, + validateLocalizationMap: () => validateLocalizationMap, + validateMaxOptionsLength: () => validateMaxOptionsLength, + validateNSFW: () => validateNSFW, + validateName: () => validateName, + validateRequired: () => validateRequired, + validateRequiredParameters: () => validateRequiredParameters3 +}); +var import_shapeshift5 = require("@sapphire/shapeshift"); +var import_v1012 = require("discord-api-types/v10"); +var namePredicate = import_shapeshift5.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(32).regex(/^[\p{Ll}\p{Lm}\p{Lo}\p{N}\p{sc=Devanagari}\p{sc=Thai}_-]+$/u).setValidationEnabled(isValidationEnabled); +function validateName(name) { + namePredicate.parse(name); +} +__name(validateName, "validateName"); +var descriptionPredicate2 = import_shapeshift5.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var localePredicate = import_shapeshift5.s.nativeEnum(import_v1012.Locale); +function validateDescription(description) { + descriptionPredicate2.parse(description); +} +__name(validateDescription, "validateDescription"); +var maxArrayLengthPredicate = import_shapeshift5.s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateLocale(locale) { + return localePredicate.parse(locale); +} +__name(validateLocale, "validateLocale"); +function validateMaxOptionsLength(options) { + maxArrayLengthPredicate.parse(options); +} +__name(validateMaxOptionsLength, "validateMaxOptionsLength"); +function validateRequiredParameters3(name, description, options) { + validateName(name); + validateDescription(description); + validateMaxOptionsLength(options); +} +__name(validateRequiredParameters3, "validateRequiredParameters"); +var booleanPredicate = import_shapeshift5.s.boolean; +function validateDefaultPermission(value) { + booleanPredicate.parse(value); +} +__name(validateDefaultPermission, "validateDefaultPermission"); +function validateRequired(required) { + booleanPredicate.parse(required); +} +__name(validateRequired, "validateRequired"); +var choicesLengthPredicate = import_shapeshift5.s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateChoicesLength(amountAdding, choices) { + choicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding); +} +__name(validateChoicesLength, "validateChoicesLength"); +function assertReturnOfBuilder(input, ExpectedInstanceOf) { + import_shapeshift5.s.instance(ExpectedInstanceOf).parse(input); +} +__name(assertReturnOfBuilder, "assertReturnOfBuilder"); +var localizationMapPredicate = import_shapeshift5.s.object(Object.fromEntries(Object.values(import_v1012.Locale).map((locale) => [ + locale, + import_shapeshift5.s.string.nullish +]))).strict.nullish.setValidationEnabled(isValidationEnabled); +function validateLocalizationMap(value) { + localizationMapPredicate.parse(value); +} +__name(validateLocalizationMap, "validateLocalizationMap"); +var dmPermissionPredicate = import_shapeshift5.s.boolean.nullish; +function validateDMPermission(value) { + dmPermissionPredicate.parse(value); +} +__name(validateDMPermission, "validateDMPermission"); +var memberPermissionPredicate = import_shapeshift5.s.union(import_shapeshift5.s.bigint.transform((value) => value.toString()), import_shapeshift5.s.number.safeInt.transform((value) => value.toString()), import_shapeshift5.s.string.regex(/^\d+$/)).nullish; +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"); + +// src/interactions/slashCommands/SlashCommandSubcommands.ts +var import_v1024 = require("discord-api-types/v10"); +var import_ts_mixer5 = require("ts-mixer"); + +// src/interactions/slashCommands/mixins/NameAndDescription.ts +var SharedNameAndDescription = class { + /** + * Sets the name + * + * @param name - The name + */ + setName(name) { + validateName(name); + Reflect.set(this, "name", name); + return this; + } + /** + * Sets the description + * + * @param description - The description + */ + setDescription(description) { + validateDescription(description); + Reflect.set(this, "description", description); + return this; + } + /** + * Sets a name localization + * + * @param locale - The locale to set a description for + * @param localizedName - The localized description for the given locale + */ + setNameLocalization(locale, localizedName) { + if (!this.name_localizations) { + Reflect.set(this, "name_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedName === null) { + this.name_localizations[parsedLocale] = null; + return this; + } + validateName(localizedName); + this.name_localizations[parsedLocale] = localizedName; + return this; + } + /** + * Sets the name localizations + * + * @param localizedNames - The dictionary of localized descriptions to set + */ + setNameLocalizations(localizedNames) { + if (localizedNames === null) { + Reflect.set(this, "name_localizations", null); + return this; + } + Reflect.set(this, "name_localizations", {}); + for (const args of Object.entries(localizedNames)) { + this.setNameLocalization(...args); + } + return this; + } + /** + * Sets a description localization + * + * @param locale - The locale to set a description for + * @param localizedDescription - The localized description for the given locale + */ + setDescriptionLocalization(locale, localizedDescription) { + if (!this.description_localizations) { + Reflect.set(this, "description_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedDescription === null) { + this.description_localizations[parsedLocale] = null; + return this; + } + validateDescription(localizedDescription); + this.description_localizations[parsedLocale] = localizedDescription; + return this; + } + /** + * Sets the description localizations + * + * @param localizedDescriptions - The dictionary of localized descriptions to set + */ + setDescriptionLocalizations(localizedDescriptions) { + if (localizedDescriptions === null) { + Reflect.set(this, "description_localizations", null); + return this; + } + Reflect.set(this, "description_localizations", {}); + for (const args of Object.entries(localizedDescriptions)) { + this.setDescriptionLocalization(...args); + } + return this; + } +}; +__name(SharedNameAndDescription, "SharedNameAndDescription"); + +// src/interactions/slashCommands/options/attachment.ts +var import_v1013 = require("discord-api-types/v10"); + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts +var ApplicationCommandOptionBase = class extends SharedNameAndDescription { + required = false; + /** + * Marks the option as required + * + * @param required - If this option should be required + */ + setRequired(required) { + validateRequired(required); + Reflect.set(this, "required", required); + return this; + } + runRequiredValidations() { + validateRequiredParameters3(this.name, this.description, []); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + validateRequired(this.required); + } +}; +__name(ApplicationCommandOptionBase, "ApplicationCommandOptionBase"); + +// src/interactions/slashCommands/options/attachment.ts +var SlashCommandAttachmentOption = class extends ApplicationCommandOptionBase { + type = import_v1013.ApplicationCommandOptionType.Attachment; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandAttachmentOption, "SlashCommandAttachmentOption"); + +// src/interactions/slashCommands/options/boolean.ts +var import_v1014 = require("discord-api-types/v10"); +var SlashCommandBooleanOption = class extends ApplicationCommandOptionBase { + type = import_v1014.ApplicationCommandOptionType.Boolean; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandBooleanOption, "SlashCommandBooleanOption"); + +// src/interactions/slashCommands/options/channel.ts +var import_v1016 = require("discord-api-types/v10"); +var import_ts_mixer = require("ts-mixer"); + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts +var import_shapeshift6 = require("@sapphire/shapeshift"); +var import_v1015 = require("discord-api-types/v10"); +var allowedChannelTypes = [ + import_v1015.ChannelType.GuildText, + import_v1015.ChannelType.GuildVoice, + import_v1015.ChannelType.GuildCategory, + import_v1015.ChannelType.GuildAnnouncement, + import_v1015.ChannelType.AnnouncementThread, + import_v1015.ChannelType.PublicThread, + import_v1015.ChannelType.PrivateThread, + import_v1015.ChannelType.GuildStageVoice, + import_v1015.ChannelType.GuildForum +]; +var channelTypesPredicate = import_shapeshift6.s.array(import_shapeshift6.s.union(...allowedChannelTypes.map((type) => import_shapeshift6.s.literal(type)))); +var ApplicationCommandOptionChannelTypesMixin = class { + /** + * Adds channel types to this option + * + * @param channelTypes - The channel types to add + */ + addChannelTypes(...channelTypes) { + if (this.channel_types === void 0) { + Reflect.set(this, "channel_types", []); + } + this.channel_types.push(...channelTypesPredicate.parse(channelTypes)); + return this; + } +}; +__name(ApplicationCommandOptionChannelTypesMixin, "ApplicationCommandOptionChannelTypesMixin"); + +// src/interactions/slashCommands/options/channel.ts +var __decorate = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var SlashCommandChannelOption = /* @__PURE__ */ __name(class SlashCommandChannelOption2 extends ApplicationCommandOptionBase { + type = import_v1016.ApplicationCommandOptionType.Channel; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}, "SlashCommandChannelOption"); +SlashCommandChannelOption = __decorate([ + (0, import_ts_mixer.mix)(ApplicationCommandOptionChannelTypesMixin) +], SlashCommandChannelOption); + +// src/interactions/slashCommands/options/integer.ts +var import_shapeshift8 = require("@sapphire/shapeshift"); +var import_v1018 = require("discord-api-types/v10"); +var import_ts_mixer2 = require("ts-mixer"); + +// src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts +var ApplicationCommandNumericOptionMinMaxValueMixin = class { +}; +__name(ApplicationCommandNumericOptionMinMaxValueMixin, "ApplicationCommandNumericOptionMinMaxValueMixin"); + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts +var import_shapeshift7 = require("@sapphire/shapeshift"); +var import_v1017 = require("discord-api-types/v10"); +var stringPredicate = import_shapeshift7.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100); +var numberPredicate = import_shapeshift7.s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY); +var choicesPredicate = import_shapeshift7.s.object({ + name: stringPredicate, + name_localizations: localizationMapPredicate, + value: import_shapeshift7.s.union(stringPredicate, numberPredicate) +}).array; +var booleanPredicate2 = import_shapeshift7.s.boolean; +var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { + /** + * Adds multiple choices for 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."); + } + choicesPredicate.parse(choices); + if (this.choices === void 0) { + Reflect.set(this, "choices", []); + } + validateChoicesLength(choices.length, this.choices); + for (const { name, name_localizations, value } of choices) { + if (this.type === import_v1017.ApplicationCommandOptionType.String) { + stringPredicate.parse(value); + } else { + numberPredicate.parse(value); + } + this.choices.push({ + name, + name_localizations, + value + }); + } + return this; + } + setChoices(...choices) { + if (choices.length > 0 && this.autocomplete) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + choicesPredicate.parse(choices); + Reflect.set(this, "choices", []); + this.addChoices(...choices); + return this; + } + /** + * Marks the option as autocompletable + * + * @param autocomplete - If this option should be autocompletable + */ + setAutocomplete(autocomplete) { + booleanPredicate2.parse(autocomplete); + if (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + Reflect.set(this, "autocomplete", autocomplete); + return this; + } +}; +__name(ApplicationCommandOptionWithChoicesAndAutocompleteMixin, "ApplicationCommandOptionWithChoicesAndAutocompleteMixin"); + +// src/interactions/slashCommands/options/integer.ts +var __decorate2 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var numberValidator = import_shapeshift8.s.number.int; +var SlashCommandIntegerOption = /* @__PURE__ */ __name(class SlashCommandIntegerOption2 extends ApplicationCommandOptionBase { + 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; + } + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { + ...this + }; + } +}, "SlashCommandIntegerOption"); +SlashCommandIntegerOption = __decorate2([ + (0, import_ts_mixer2.mix)(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandIntegerOption); + +// src/interactions/slashCommands/options/mentionable.ts +var import_v1019 = require("discord-api-types/v10"); +var SlashCommandMentionableOption = class extends ApplicationCommandOptionBase { + type = import_v1019.ApplicationCommandOptionType.Mentionable; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandMentionableOption, "SlashCommandMentionableOption"); + +// src/interactions/slashCommands/options/number.ts +var import_shapeshift9 = require("@sapphire/shapeshift"); +var import_v1020 = require("discord-api-types/v10"); +var import_ts_mixer3 = require("ts-mixer"); +var __decorate3 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var numberValidator2 = import_shapeshift9.s.number; +var SlashCommandNumberOption = /* @__PURE__ */ __name(class SlashCommandNumberOption2 extends ApplicationCommandOptionBase { + 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; + } + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { + ...this + }; + } +}, "SlashCommandNumberOption"); +SlashCommandNumberOption = __decorate3([ + (0, import_ts_mixer3.mix)(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandNumberOption); + +// src/interactions/slashCommands/options/role.ts +var import_v1021 = require("discord-api-types/v10"); +var SlashCommandRoleOption = class extends ApplicationCommandOptionBase { + type = import_v1021.ApplicationCommandOptionType.Role; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandRoleOption, "SlashCommandRoleOption"); + +// src/interactions/slashCommands/options/string.ts +var import_shapeshift10 = require("@sapphire/shapeshift"); +var import_v1022 = require("discord-api-types/v10"); +var import_ts_mixer4 = require("ts-mixer"); +var __decorate4 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var minLengthValidator2 = import_shapeshift10.s.number.greaterThanOrEqual(0).lessThanOrEqual(6e3); +var maxLengthValidator2 = import_shapeshift10.s.number.greaterThanOrEqual(1).lessThanOrEqual(6e3); +var SlashCommandStringOption = /* @__PURE__ */ __name(class SlashCommandStringOption2 extends ApplicationCommandOptionBase { + type = import_v1022.ApplicationCommandOptionType.String; + /** + * 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; + } + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { + ...this + }; + } +}, "SlashCommandStringOption"); +SlashCommandStringOption = __decorate4([ + (0, import_ts_mixer4.mix)(ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandStringOption); + +// src/interactions/slashCommands/options/user.ts +var import_v1023 = require("discord-api-types/v10"); +var SlashCommandUserOption = class extends ApplicationCommandOptionBase { + type = import_v1023.ApplicationCommandOptionType.User; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandUserOption, "SlashCommandUserOption"); + +// src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts +var SharedSlashCommandOptions = class { + /** + * 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); + } + _sharedAddOptionMethod(input, Instance) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new Instance()) : input; + assertReturnOfBuilder(result, Instance); + options.push(result); + return this; + } +}; +__name(SharedSlashCommandOptions, "SharedSlashCommandOptions"); + +// src/interactions/slashCommands/SlashCommandSubcommands.ts +var __decorate5 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var SlashCommandSubcommandGroupBuilder = /* @__PURE__ */ __name(class SlashCommandSubcommandGroupBuilder2 { + /** + * The name of this subcommand group + */ + name = void 0; + /** + * The description of this subcommand group + */ + description = void 0; + /** + * The subcommands part of 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); + const result = typeof input === "function" ? input(new SlashCommandSubcommandBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandBuilder); + options.push(result); + return this; + } + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + return { + type: import_v1024.ApplicationCommandOptionType.SubcommandGroup, + name: this.name, + name_localizations: this.name_localizations, + description: this.description, + description_localizations: this.description_localizations, + options: this.options.map((option) => option.toJSON()) + }; + } +}, "SlashCommandSubcommandGroupBuilder"); +SlashCommandSubcommandGroupBuilder = __decorate5([ + (0, import_ts_mixer5.mix)(SharedNameAndDescription) +], SlashCommandSubcommandGroupBuilder); +var SlashCommandSubcommandBuilder = /* @__PURE__ */ __name(class SlashCommandSubcommandBuilder2 { + /** + * The name of this subcommand + */ + name = void 0; + /** + * The description of this subcommand + */ + description = void 0; + /** + * The options of this subcommand + */ + options = []; + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + return { + type: import_v1024.ApplicationCommandOptionType.Subcommand, + name: this.name, + name_localizations: this.name_localizations, + description: this.description, + description_localizations: this.description_localizations, + options: this.options.map((option) => option.toJSON()) + }; + } +}, "SlashCommandSubcommandBuilder"); +SlashCommandSubcommandBuilder = __decorate5([ + (0, import_ts_mixer5.mix)(SharedNameAndDescription, SharedSlashCommandOptions) +], SlashCommandSubcommandBuilder); + +// src/interactions/slashCommands/SlashCommandBuilder.ts +var __decorate6 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var SlashCommandBuilder = /* @__PURE__ */ __name(class SlashCommandBuilder2 { + /** + * The name of this slash command + */ + name = void 0; + /** + * The description of this slash command + */ + description = void 0; + /** + * The options of this slash command + */ + options = []; + /** + * Whether the command is enabled by default when the app 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. + */ + default_permission = void 0; + /** + * Set of permissions represented as a bit set for the command + */ + default_member_permissions = void 0; + /** + * Indicates whether the command is available in DMs with the application, only for globally-scoped commands. + * By default, commands are visible. + */ + dm_permission = void 0; + /** + * Whether this command is NSFW + */ + nsfw = void 0; + /** + * 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. + */ + 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()) + }; + } + /** + * 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. + */ + 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 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 DMs with the application, only for globally-scoped commands. + * By default, commands are visible. + * + * @param enabled - If the command should be enabled in DMs + * @see 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); + const result = typeof input === "function" ? input(new SlashCommandSubcommandGroupBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder); + 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); + const result = typeof input === "function" ? input(new SlashCommandSubcommandBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandBuilder); + options.push(result); + return this; + } +}, "SlashCommandBuilder"); +SlashCommandBuilder = __decorate6([ + (0, import_ts_mixer6.mix)(SharedSlashCommandOptions, SharedNameAndDescription) +], SlashCommandBuilder); + +// src/interactions/contextMenuCommands/Assertions.ts +var Assertions_exports6 = {}; +__export(Assertions_exports6, { + validateDMPermission: () => validateDMPermission2, + validateDefaultMemberPermissions: () => validateDefaultMemberPermissions2, + validateDefaultPermission: () => validateDefaultPermission2, + validateName: () => validateName2, + validateRequiredParameters: () => validateRequiredParameters4, + validateType: () => validateType +}); +var import_shapeshift11 = require("@sapphire/shapeshift"); +var import_v1025 = require("discord-api-types/v10"); +var namePredicate2 = import_shapeshift11.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(32).regex(/^( *[\p{P}\p{L}\p{N}\p{sc=Devanagari}\p{sc=Thai}]+ *)+$/u).setValidationEnabled(isValidationEnabled); +var typePredicate = import_shapeshift11.s.union(import_shapeshift11.s.literal(import_v1025.ApplicationCommandType.User), import_shapeshift11.s.literal(import_v1025.ApplicationCommandType.Message)).setValidationEnabled(isValidationEnabled); +var booleanPredicate3 = import_shapeshift11.s.boolean; +function validateDefaultPermission2(value) { + booleanPredicate3.parse(value); +} +__name(validateDefaultPermission2, "validateDefaultPermission"); +function validateName2(name) { + namePredicate2.parse(name); +} +__name(validateName2, "validateName"); +function validateType(type) { + typePredicate.parse(type); +} +__name(validateType, "validateType"); +function validateRequiredParameters4(name, type) { + validateName2(name); + validateType(type); +} +__name(validateRequiredParameters4, "validateRequiredParameters"); +var dmPermissionPredicate2 = import_shapeshift11.s.boolean.nullish; +function validateDMPermission2(value) { + dmPermissionPredicate2.parse(value); +} +__name(validateDMPermission2, "validateDMPermission"); +var memberPermissionPredicate2 = import_shapeshift11.s.union(import_shapeshift11.s.bigint.transform((value) => value.toString()), import_shapeshift11.s.number.safeInt.transform((value) => value.toString()), import_shapeshift11.s.string.regex(/^\d+$/)).nullish; +function validateDefaultMemberPermissions2(permissions) { + return memberPermissionPredicate2.parse(permissions); +} +__name(validateDefaultMemberPermissions2, "validateDefaultMemberPermissions"); + +// src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts +var ContextMenuCommandBuilder = class { + /** + * The name of this context menu command + */ + name = void 0; + /** + * The type of this context menu command + */ + type = void 0; + /** + * Whether the command is enabled by default when the app 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. + */ + default_permission = void 0; + /** + * Set of permissions represented as a bit set for the command + */ + default_member_permissions = void 0; + /** + * Indicates whether the command is available in DMs with the application, only for globally-scoped commands. + * By default, commands are visible. + */ + dm_permission = void 0; + /** + * Sets the name + * + * @param name - The name + */ + setName(name) { + validateName2(name); + Reflect.set(this, "name", name); + return this; + } + /** + * Sets the type + * + * @param type - The type + */ + 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 or not to enable this command by default + * @see 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 the 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 + */ + setDefaultMemberPermissions(permissions) { + const permissionValue = validateDefaultMemberPermissions2(permissions); + Reflect.set(this, "default_member_permissions", permissionValue); + return this; + } + /** + * Sets if the command is available in DMs with the application, only for globally-scoped commands. + * By default, commands are visible. + * + * @param enabled - If the command should be enabled in DMs + * @see 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 + * + * @param locale - The locale to set a description for + * @param localizedName - The localized description for the given locale + */ + setNameLocalization(locale, localizedName) { + if (!this.name_localizations) { + Reflect.set(this, "name_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedName === null) { + this.name_localizations[parsedLocale] = null; + return this; + } + validateName2(localizedName); + this.name_localizations[parsedLocale] = localizedName; + return this; + } + /** + * Sets the name localizations + * + * @param localizedNames - The dictionary of localized descriptions to set + */ + setNameLocalizations(localizedNames) { + if (localizedNames === null) { + Reflect.set(this, "name_localizations", null); + return this; + } + Reflect.set(this, "name_localizations", {}); + for (const args of Object.entries(localizedNames)) + this.setNameLocalization(...args); + return this; + } + /** + * 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. + */ + toJSON() { + validateRequiredParameters4(this.name, this.type); + validateLocalizationMap(this.name_localizations); + return { + ...this + }; + } +}; +__name(ContextMenuCommandBuilder, "ContextMenuCommandBuilder"); + +// src/util/componentUtil.ts +function embedLength(data) { + return (data.title?.length ?? 0) + (data.description?.length ?? 0) + (data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) + (data.footer?.text.length ?? 0) + (data.author?.name.length ?? 0); +} +__name(embedLength, "embedLength"); + +// src/index.ts +__reExport(src_exports, require("@discordjs/util"), module.exports); +var version = "[VI]{{inject}}[/VI]"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ActionRowBuilder, + ApplicationCommandNumericOptionMinMaxValueMixin, + ApplicationCommandOptionBase, + ApplicationCommandOptionChannelTypesMixin, + ApplicationCommandOptionWithChoicesAndAutocompleteMixin, + BaseSelectMenuBuilder, + ButtonBuilder, + ChannelSelectMenuBuilder, + ComponentAssertions, + ComponentBuilder, + ContextMenuCommandAssertions, + ContextMenuCommandBuilder, + EmbedAssertions, + EmbedBuilder, + MentionableSelectMenuBuilder, + ModalAssertions, + ModalBuilder, + RoleSelectMenuBuilder, + SelectMenuBuilder, + SelectMenuOptionBuilder, + SharedNameAndDescription, + SharedSlashCommandOptions, + SlashCommandAssertions, + SlashCommandAttachmentOption, + SlashCommandBooleanOption, + SlashCommandBuilder, + SlashCommandChannelOption, + SlashCommandIntegerOption, + SlashCommandMentionableOption, + SlashCommandNumberOption, + SlashCommandRoleOption, + SlashCommandStringOption, + SlashCommandSubcommandBuilder, + SlashCommandSubcommandGroupBuilder, + SlashCommandUserOption, + StringSelectMenuBuilder, + StringSelectMenuOptionBuilder, + TextInputAssertions, + TextInputBuilder, + UserSelectMenuBuilder, + createComponentBuilder, + disableValidators, + embedLength, + enableValidators, + isValidationEnabled, + normalizeArray, + version +}); +//# 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 new file mode 100644 index 0000000..423fbbe --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.js.map @@ -0,0 +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/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';\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\nexport const version = '[VI]{{inject}}[/VI]' 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\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/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 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 { 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\treturn this.spliceOptions(0, this.options.length, ...options);\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts options in the string 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 *\n\t * It's useful for modifying and adjusting order of the already-existing options of a string select menu.\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\t// eslint-disable-next-line no-param-reassign\n\t\toptions = 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...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\n\t\toptionsLengthValidator.parse(clone.length);\n\n\t\tthis.options.splice(0, this.options.length, ...clone);\n\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\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@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 * Whether this command is NSFW\n\t */\n\tpublic readonly nsfw: 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 * 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\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) => pr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MAAgB;AAC3C,UACEA,KAAKC,OAAOC,UAAU,MACtBF,KAAKG,aAAaD,UAAU,MAC5BF,KAAKI,QAAQC,OAAO,CAACC,MAAMC,SAASD,OAAOC,KAAKC,KAAKN,SAASK,KAAKE,MAAMP,QAAQ,CAAA,KAAM,MACvFF,KAAKU,QAAQC,KAAKT,UAAU,MAC5BF,KAAKY,QAAQJ,KAAKN,UAAU;AAE/B;AARgBH;;;AzC2DhB,wBAAc,4BA7Dd;AAoEO,IAAMc,UAAU;","names":["Assertions_exports","validate","enableValidators","disableValidators","isValidationEnabled","fieldNamePredicate","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","setValidationEnabled","isValidationEnabled","fieldValuePredicate","fieldInlinePredicate","boolean","optional","embedFieldPredicate","object","name","value","inline","embedFieldsArrayPredicate","array","fieldLengthPredicate","number","lessThanOrEqual","validateFieldLength","amountAdding","fields","parse","length","authorNamePredicate","nullable","imageURLPredicate","url","allowedProtocols","nullish","urlPredicate","embedAuthorPredicate","iconURL","RGBPredicate","int","greaterThanOrEqual","colorPredicate","or","tuple","descriptionPredicate","footerTextPredicate","embedFooterPredicate","text","timestampPredicate","union","date","titlePredicate","normalizeArray","arr","Array","isArray","EmbedBuilder","data","timestamp","Date","toISOString","addFields","fields","normalizeArray","validateFieldLength","length","embedFieldsArrayPredicate","parse","push","spliceFields","index","deleteCount","splice","setFields","setAuthor","options","author","undefined","embedAuthorPredicate","name","url","icon_url","iconURL","setColor","color","colorPredicate","Array","isArray","red","green","blue","setDescription","description","descriptionPredicate","setFooter","footer","embedFooterPredicate","text","setImage","imageURLPredicate","image","setThumbnail","thumbnail","setTimestamp","now","timestampPredicate","setTitle","title","titlePredicate","setURL","urlPredicate","toJSON","Assertions_exports","import_shapeshift","StringSelectMenuOptionBuilder","data","setLabel","label","labelValueDescriptionValidator","parse","setValue","value","setDescription","description","setDefault","isDefault","default","defaultValidator","setEmoji","emoji","emojiValidator","toJSON","validateRequiredSelectMenuOptionParameters","customIdValidator","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","setValidationEnabled","isValidationEnabled","emojiValidator","object","id","name","animated","boolean","partial","strict","disabledValidator","buttonLabelValidator","buttonStyleValidator","nativeEnum","ButtonStyle","placeholderValidator","minMaxValidator","number","int","greaterThanOrEqual","lessThanOrEqual","labelValueDescriptionValidator","jsonOptionValidator","label","value","description","optional","emoji","default","optionValidator","instance","StringSelectMenuOptionBuilder","optionsValidator","array","optionsLengthValidator","validateRequiredSelectMenuParameters","options","customId","parse","defaultValidator","validateRequiredSelectMenuOptionParameters","channelTypesValidator","ChannelType","urlValidator","url","allowedProtocols","validateRequiredButtonParameters","style","RangeError","Link","import_v10","ComponentBuilder","data","import_v10","import_v10","ButtonBuilder","ComponentBuilder","data","type","ComponentType","Button","setStyle","style","buttonStyleValidator","parse","setURL","url","urlValidator","setCustomId","customId","custom_id","customIdValidator","setEmoji","emoji","emojiValidator","setDisabled","disabled","disabledValidator","setLabel","label","buttonLabelValidator","toJSON","validateRequiredButtonParameters","import_v10","BaseSelectMenuBuilder","ComponentBuilder","setPlaceholder","placeholder","data","placeholderValidator","parse","setMinValues","minValues","min_values","minMaxValidator","setMaxValues","maxValues","max_values","setCustomId","customId","custom_id","customIdValidator","setDisabled","disabled","disabledValidator","toJSON","ChannelSelectMenuBuilder","BaseSelectMenuBuilder","data","type","ComponentType","ChannelSelect","addChannelTypes","types","normalizeArray","channel_types","push","channelTypesValidator","parse","setChannelTypes","splice","length","toJSON","customIdValidator","custom_id","import_v10","MentionableSelectMenuBuilder","BaseSelectMenuBuilder","data","type","ComponentType","MentionableSelect","import_v10","RoleSelectMenuBuilder","BaseSelectMenuBuilder","data","type","ComponentType","RoleSelect","import_v10","StringSelectMenuBuilder","BaseSelectMenuBuilder","data","options","initData","type","ComponentType","StringSelect","map","option","StringSelectMenuOptionBuilder","addOptions","normalizeArray","optionsLengthValidator","parse","length","push","jsonOptionValidator","setOptions","spliceOptions","index","deleteCount","clone","splice","toJSON","validateRequiredSelectMenuParameters","custom_id","import_v10","UserSelectMenuBuilder","BaseSelectMenuBuilder","data","type","ComponentType","UserSelect","import_v10","Assertions_exports","placeholderValidator","import_shapeshift","import_v10","textInputStyleValidator","s","nativeEnum","TextInputStyle","minLengthValidator","number","int","greaterThanOrEqual","lessThanOrEqual","setValidationEnabled","isValidationEnabled","maxLengthValidator","requiredValidator","boolean","valueValidator","string","lengthLessThanOrEqual","placeholderValidator","labelValidator","lengthGreaterThanOrEqual","validateRequiredParameters","customId","style","label","customIdValidator","parse","TextInputBuilder","ComponentBuilder","data","type","ComponentType","TextInput","setCustomId","customId","custom_id","customIdValidator","parse","setLabel","label","labelValidator","setStyle","style","textInputStyleValidator","setMinLength","minLength","min_length","minLengthValidator","setMaxLength","maxLength","max_length","maxLengthValidator","setPlaceholder","placeholder","placeholderValidator","setValue","value","valueValidator","setRequired","required","requiredValidator","toJSON","validateRequiredParameters","equals","other","isJSONEncodable","isEqual","createComponentBuilder","data","ComponentBuilder","type","ComponentType","ActionRow","ActionRowBuilder","Button","ButtonBuilder","StringSelect","StringSelectMenuBuilder","TextInput","TextInputBuilder","UserSelect","UserSelectMenuBuilder","RoleSelect","RoleSelectMenuBuilder","MentionableSelect","MentionableSelectMenuBuilder","ChannelSelect","ChannelSelectMenuBuilder","Error","ActionRowBuilder","ComponentBuilder","components","data","type","ComponentType","ActionRow","map","component","createComponentBuilder","addComponents","push","normalizeArray","setComponents","splice","length","toJSON","Assertions_exports","validateRequiredParameters","import_shapeshift","titleValidator","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","setValidationEnabled","isValidationEnabled","componentsValidator","instance","ActionRowBuilder","array","validateRequiredParameters","customId","title","components","customIdValidator","parse","ModalBuilder","components","data","map","component","createComponentBuilder","setTitle","title","titleValidator","parse","setCustomId","customId","custom_id","customIdValidator","addComponents","push","normalizeArray","ActionRowBuilder","setComponents","splice","length","toJSON","validateRequiredParameters","Assertions_exports","validateRequiredParameters","import_shapeshift","import_v10","namePredicate","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","regex","setValidationEnabled","isValidationEnabled","validateName","name","parse","descriptionPredicate","localePredicate","nativeEnum","Locale","validateDescription","description","maxArrayLengthPredicate","unknown","array","validateLocale","locale","validateMaxOptionsLength","options","validateRequiredParameters","booleanPredicate","boolean","validateDefaultPermission","value","validateRequired","required","choicesLengthPredicate","number","lessThanOrEqual","validateChoicesLength","amountAdding","choices","length","assertReturnOfBuilder","input","ExpectedInstanceOf","instance","localizationMapPredicate","object","Object","fromEntries","values","map","nullish","strict","validateLocalizationMap","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","union","bigint","transform","toString","safeInt","validateDefaultMemberPermissions","permissions","validateNSFW","import_ts_mixer","import_v10","import_ts_mixer","SharedNameAndDescription","setName","name","validateName","Reflect","set","setDescription","description","validateDescription","setNameLocalization","locale","localizedName","name_localizations","parsedLocale","validateLocale","setNameLocalizations","localizedNames","args","Object","entries","setDescriptionLocalization","localizedDescription","description_localizations","setDescriptionLocalizations","localizedDescriptions","import_v10","ApplicationCommandOptionBase","SharedNameAndDescription","required","setRequired","validateRequired","Reflect","set","runRequiredValidations","validateRequiredParameters","name","description","validateLocalizationMap","name_localizations","description_localizations","SlashCommandAttachmentOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Attachment","toJSON","runRequiredValidations","import_v10","SlashCommandBooleanOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Boolean","toJSON","runRequiredValidations","import_v10","import_shapeshift","import_v10","allowedChannelTypes","ChannelType","GuildText","GuildVoice","GuildCategory","GuildAnnouncement","AnnouncementThread","PublicThread","PrivateThread","GuildStageVoice","GuildForum","channelTypesPredicate","s","array","union","map","type","literal","ApplicationCommandOptionChannelTypesMixin","addChannelTypes","channelTypes","channel_types","undefined","Reflect","set","push","parse","SlashCommandChannelOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Channel","toJSON","runRequiredValidations","mix","ApplicationCommandOptionChannelTypesMixin","import_shapeshift","import_v10","import_ts_mixer","ApplicationCommandNumericOptionMinMaxValueMixin","import_shapeshift","import_v10","stringPredicate","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","numberPredicate","number","greaterThan","Number","NEGATIVE_INFINITY","lessThan","POSITIVE_INFINITY","choicesPredicate","object","name","name_localizations","localizationMapPredicate","value","union","array","booleanPredicate","boolean","ApplicationCommandOptionWithChoicesAndAutocompleteMixin","addChoices","choices","length","autocomplete","RangeError","parse","undefined","Reflect","set","validateChoicesLength","type","ApplicationCommandOptionType","String","push","setChoices","setAutocomplete","Array","isArray","numberValidator","s","number","int","SlashCommandIntegerOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Integer","setMaxValue","max","parse","Reflect","set","setMinValue","min","toJSON","runRequiredValidations","autocomplete","Array","isArray","choices","length","RangeError","mix","ApplicationCommandNumericOptionMinMaxValueMixin","ApplicationCommandOptionWithChoicesAndAutocompleteMixin","import_v10","SlashCommandMentionableOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Mentionable","toJSON","runRequiredValidations","import_shapeshift","import_v10","import_ts_mixer","numberValidator","s","number","SlashCommandNumberOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Number","setMaxValue","max","parse","Reflect","set","setMinValue","min","toJSON","runRequiredValidations","autocomplete","Array","isArray","choices","length","RangeError","mix","ApplicationCommandNumericOptionMinMaxValueMixin","ApplicationCommandOptionWithChoicesAndAutocompleteMixin","import_v10","SlashCommandRoleOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Role","toJSON","runRequiredValidations","import_shapeshift","import_v10","import_ts_mixer","minLengthValidator","s","number","greaterThanOrEqual","lessThanOrEqual","maxLengthValidator","SlashCommandStringOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","String","setMaxLength","max","parse","Reflect","set","setMinLength","min","toJSON","runRequiredValidations","autocomplete","Array","isArray","choices","length","RangeError","mix","ApplicationCommandOptionWithChoicesAndAutocompleteMixin","import_v10","SlashCommandUserOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","User","toJSON","runRequiredValidations","SharedSlashCommandOptions","addBooleanOption","input","_sharedAddOptionMethod","SlashCommandBooleanOption","addUserOption","SlashCommandUserOption","addChannelOption","SlashCommandChannelOption","addRoleOption","SlashCommandRoleOption","addAttachmentOption","SlashCommandAttachmentOption","addMentionableOption","SlashCommandMentionableOption","addStringOption","SlashCommandStringOption","addIntegerOption","SlashCommandIntegerOption","addNumberOption","SlashCommandNumberOption","Instance","options","validateMaxOptionsLength","result","assertReturnOfBuilder","push","SlashCommandSubcommandGroupBuilder","name","undefined","description","options","addSubcommand","input","validateMaxOptionsLength","result","SlashCommandSubcommandBuilder","assertReturnOfBuilder","push","toJSON","validateRequiredParameters","type","ApplicationCommandOptionType","SubcommandGroup","name_localizations","description_localizations","map","option","mix","SharedNameAndDescription","Subcommand","SharedSlashCommandOptions","SlashCommandBuilder","name","undefined","description","options","default_permission","default_member_permissions","dm_permission","nsfw","toJSON","validateRequiredParameters","validateLocalizationMap","name_localizations","description_localizations","map","option","setDefaultPermission","value","validateDefaultPermission","Reflect","set","setDefaultMemberPermissions","permissions","permissionValue","validateDefaultMemberPermissions","setDMPermission","enabled","validateDMPermission","setNSFW","validateNSFW","addSubcommandGroup","input","validateMaxOptionsLength","result","SlashCommandSubcommandGroupBuilder","assertReturnOfBuilder","push","addSubcommand","SlashCommandSubcommandBuilder","mix","SharedSlashCommandOptions","SharedNameAndDescription","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","import_shapeshift","import_v10","namePredicate","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","regex","setValidationEnabled","isValidationEnabled","typePredicate","union","literal","ApplicationCommandType","User","Message","booleanPredicate","boolean","validateDefaultPermission","value","parse","validateName","name","validateType","type","validateRequiredParameters","dmPermissionPredicate","nullish","validateDMPermission","memberPermissionPredicate","bigint","transform","toString","number","safeInt","validateDefaultMemberPermissions","permissions","ContextMenuCommandBuilder","name","undefined","type","default_permission","default_member_permissions","dm_permission","setName","validateName","Reflect","set","setType","validateType","setDefaultPermission","value","validateDefaultPermission","setDefaultMemberPermissions","permissions","permissionValue","validateDefaultMemberPermissions","setDMPermission","enabled","validateDMPermission","setNameLocalization","locale","localizedName","name_localizations","parsedLocale","validateLocale","setNameLocalizations","localizedNames","args","Object","entries","toJSON","validateRequiredParameters","validateLocalizationMap","embedLength","data","title","length","description","fields","reduce","prev","curr","name","value","footer","text","author","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.mjs b/node_modules/@discordjs/builders/dist/index.mjs new file mode 100644 index 0000000..500c20a --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.mjs @@ -0,0 +1,2368 @@ +var __defProp = Object.defineProperty; +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 }); +}; + +// src/messages/embed/Assertions.ts +var Assertions_exports = {}; +__export(Assertions_exports, { + RGBPredicate: () => RGBPredicate, + authorNamePredicate: () => authorNamePredicate, + colorPredicate: () => colorPredicate, + descriptionPredicate: () => descriptionPredicate, + embedAuthorPredicate: () => embedAuthorPredicate, + embedFieldPredicate: () => embedFieldPredicate, + embedFieldsArrayPredicate: () => embedFieldsArrayPredicate, + embedFooterPredicate: () => embedFooterPredicate, + fieldInlinePredicate: () => fieldInlinePredicate, + fieldLengthPredicate: () => fieldLengthPredicate, + fieldNamePredicate: () => fieldNamePredicate, + fieldValuePredicate: () => fieldValuePredicate, + footerTextPredicate: () => footerTextPredicate, + imageURLPredicate: () => imageURLPredicate, + timestampPredicate: () => timestampPredicate, + titlePredicate: () => titlePredicate, + urlPredicate: () => urlPredicate, + validateFieldLength: () => validateFieldLength +}); +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"); + +// src/messages/embed/Assertions.ts +var fieldNamePredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(256).setValidationEnabled(isValidationEnabled); +var fieldValuePredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(1024).setValidationEnabled(isValidationEnabled); +var fieldInlinePredicate = s.boolean.optional; +var embedFieldPredicate = s.object({ + name: fieldNamePredicate, + value: fieldValuePredicate, + inline: fieldInlinePredicate +}).setValidationEnabled(isValidationEnabled); +var embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled); +var fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateFieldLength(amountAdding, fields) { + fieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding); +} +__name(validateFieldLength, "validateFieldLength"); +var authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled); +var imageURLPredicate = s.string.url({ + allowedProtocols: [ + "http:", + "https:", + "attachment:" + ] +}).nullish.setValidationEnabled(isValidationEnabled); +var urlPredicate = s.string.url({ + allowedProtocols: [ + "http:", + "https:" + ] +}).nullish.setValidationEnabled(isValidationEnabled); +var embedAuthorPredicate = s.object({ + name: authorNamePredicate, + iconURL: imageURLPredicate, + url: urlPredicate +}).setValidationEnabled(isValidationEnabled); +var RGBPredicate = s.number.int.greaterThanOrEqual(0).lessThanOrEqual(255).setValidationEnabled(isValidationEnabled); +var colorPredicate = s.number.int.greaterThanOrEqual(0).lessThanOrEqual(16777215).or(s.tuple([ + RGBPredicate, + RGBPredicate, + RGBPredicate +])).nullable.setValidationEnabled(isValidationEnabled); +var descriptionPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(4096).nullable.setValidationEnabled(isValidationEnabled); +var footerTextPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(2048).nullable.setValidationEnabled(isValidationEnabled); +var embedFooterPredicate = s.object({ + text: footerTextPredicate, + iconURL: imageURLPredicate +}).setValidationEnabled(isValidationEnabled); +var timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled); +var titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled); + +// src/util/normalizeArray.ts +function normalizeArray(arr) { + if (Array.isArray(arr[0])) + return arr[0]; + return arr; +} +__name(normalizeArray, "normalizeArray"); + +// src/messages/embed/Embed.ts +var EmbedBuilder = class { + 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); + if (this.data.fields) + this.data.fields.push(...fields); + else + this.data.fields = fields; + return this; + } + /** + * Removes, replaces, or inserts fields in the 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); + if (this.data.fields) + this.data.fields.splice(index, deleteCount, ...fields); + else + this.data.fields = fields; + return this; + } + /** + * Sets the embed's fields + * + * @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 for the author + */ + setAuthor(options) { + if (options === null) { + this.data.author = void 0; + return this; + } + embedAuthorPredicate.parse(options); + 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 of the embed + */ + setColor(color) { + colorPredicate.parse(color); + if (Array.isArray(color)) { + const [red, green, blue] = color; + this.data.color = (red << 16) + (green << 8) + blue; + return this; + } + this.data.color = color ?? void 0; + return this; + } + /** + * Sets the description of this embed + * + * @param description - The description + */ + setDescription(description) { + descriptionPredicate.parse(description); + this.data.description = description ?? void 0; + return this; + } + /** + * Sets the footer of this embed + * + * @param options - The options for the footer + */ + setFooter(options) { + if (options === null) { + this.data.footer = void 0; + return this; + } + embedFooterPredicate.parse(options); + this.data.footer = { + text: options.text, + icon_url: options.iconURL + }; + return this; + } + /** + * Sets the image of this embed + * + * @param url - The URL of the image + */ + setImage(url) { + imageURLPredicate.parse(url); + this.data.image = url ? { + url + } : void 0; + return this; + } + /** + * Sets the thumbnail of this embed + * + * @param url - The URL of the thumbnail + */ + 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 + */ + setTimestamp(timestamp = Date.now()) { + timestampPredicate.parse(timestamp); + this.data.timestamp = timestamp ? new Date(timestamp).toISOString() : void 0; + return this; + } + /** + * Sets the title of this embed + * + * @param title - The title + */ + setTitle(title) { + titlePredicate.parse(title); + this.data.title = title ?? void 0; + return this; + } + /** + * Sets the URL of this embed + * + * @param url - The URL + */ + setURL(url) { + urlPredicate.parse(url); + this.data.url = url ?? void 0; + return this; + } + /** + * Transforms the embed to a plain object + */ + toJSON() { + return { + ...this.data + }; + } +}; +__name(EmbedBuilder, "EmbedBuilder"); + +// src/index.ts +export * from "@discordjs/formatters"; + +// src/components/Assertions.ts +var Assertions_exports2 = {}; +__export(Assertions_exports2, { + buttonLabelValidator: () => buttonLabelValidator, + buttonStyleValidator: () => buttonStyleValidator, + channelTypesValidator: () => channelTypesValidator, + customIdValidator: () => customIdValidator, + defaultValidator: () => defaultValidator, + disabledValidator: () => disabledValidator, + emojiValidator: () => emojiValidator, + jsonOptionValidator: () => jsonOptionValidator, + labelValueDescriptionValidator: () => labelValueDescriptionValidator, + minMaxValidator: () => minMaxValidator, + optionValidator: () => optionValidator, + optionsLengthValidator: () => optionsLengthValidator, + optionsValidator: () => optionsValidator, + placeholderValidator: () => placeholderValidator, + urlValidator: () => urlValidator, + validateRequiredButtonParameters: () => validateRequiredButtonParameters, + validateRequiredSelectMenuOptionParameters: () => validateRequiredSelectMenuOptionParameters, + validateRequiredSelectMenuParameters: () => validateRequiredSelectMenuParameters +}); +import { s as s2 } from "@sapphire/shapeshift"; +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 of this option + * + * @param label - The label to show on this option + */ + setLabel(label) { + this.data.label = labelValueDescriptionValidator.parse(label); + return this; + } + /** + * Sets the value of this option + * + * @param value - The value of this option + */ + setValue(value) { + this.data.value = labelValueDescriptionValidator.parse(value); + return this; + } + /** + * Sets the description of this option + * + * @param description - The description of this option + */ + 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 on this option + * + * @param emoji - The emoji to display on this option + */ + setEmoji(emoji) { + this.data.emoji = emojiValidator.parse(emoji); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); + return { + ...this.data + }; + } +}; +__name(StringSelectMenuOptionBuilder, "StringSelectMenuOptionBuilder"); + +// src/components/Assertions.ts +var customIdValidator = s2.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var emojiValidator = s2.object({ + id: s2.string, + name: s2.string, + animated: s2.boolean +}).partial.strict.setValidationEnabled(isValidationEnabled); +var disabledValidator = s2.boolean; +var buttonLabelValidator = s2.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(80).setValidationEnabled(isValidationEnabled); +var buttonStyleValidator = s2.nativeEnum(ButtonStyle); +var placeholderValidator = s2.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled); +var minMaxValidator = s2.number.int.greaterThanOrEqual(0).lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +var labelValueDescriptionValidator = s2.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var jsonOptionValidator = s2.object({ + label: labelValueDescriptionValidator, + value: labelValueDescriptionValidator, + description: labelValueDescriptionValidator.optional, + emoji: emojiValidator.optional, + default: s2.boolean.optional +}).setValidationEnabled(isValidationEnabled); +var optionValidator = s2.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled); +var optionsValidator = optionValidator.array.lengthGreaterThanOrEqual(0).setValidationEnabled(isValidationEnabled); +var optionsLengthValidator = s2.number.int.greaterThanOrEqual(0).lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateRequiredSelectMenuParameters(options, customId) { + customIdValidator.parse(customId); + optionsValidator.parse(options); +} +__name(validateRequiredSelectMenuParameters, "validateRequiredSelectMenuParameters"); +var defaultValidator = s2.boolean; +function validateRequiredSelectMenuOptionParameters(label, value) { + labelValueDescriptionValidator.parse(label); + labelValueDescriptionValidator.parse(value); +} +__name(validateRequiredSelectMenuOptionParameters, "validateRequiredSelectMenuOptionParameters"); +var channelTypesValidator = s2.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled); +var urlValidator = s2.string.url({ + allowedProtocols: [ + "http:", + "https:", + "discord:" + ] +}).setValidationEnabled(isValidationEnabled); +function validateRequiredButtonParameters(style, label, emoji, customId, url) { + if (url && customId) { + throw new RangeError("URL and custom id are mutually exclusive"); + } + if (!label && !emoji) { + throw new RangeError("Buttons must have a label and/or an emoji"); + } + if (style === ButtonStyle.Link) { + if (!url) { + throw new RangeError("Link buttons must have a url"); + } + } else if (url) { + throw new RangeError("Non-link buttons cannot have a url"); + } +} +__name(validateRequiredButtonParameters, "validateRequiredButtonParameters"); + +// src/components/ActionRow.ts +import { ComponentType as ComponentType9 } from "discord-api-types/v10"; + +// src/components/Component.ts +var ComponentBuilder = class { + constructor(data) { + this.data = data; + } +}; +__name(ComponentBuilder, "ComponentBuilder"); + +// src/components/Components.ts +import { ComponentType as ComponentType8 } from "discord-api-types/v10"; + +// src/components/button/Button.ts +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 of the button + */ + 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 open when this button is clicked + */ + 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 for this button + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets the emoji to display on this button + * + * @param emoji - The emoji to display on this button + */ + 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 display on this button + */ + setLabel(label) { + this.data.label = buttonLabelValidator.parse(label); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredButtonParameters(this.data.style, this.data.label, this.data.emoji, this.data.custom_id, this.data.url); + return { + ...this.data + }; + } +}; +__name(ButtonBuilder, "ButtonBuilder"); + +// src/components/selectMenu/ChannelSelectMenu.ts +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 for this select menu + */ + 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 for this select menu + */ + 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; + } + toJSON() { + customIdValidator.parse(this.data.custom_id); + return { + ...this.data + }; + } +}; +__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 + }); + } + addChannelTypes(...types) { + types = normalizeArray(types); + this.data.channel_types ??= []; + this.data.channel_types.push(...channelTypesValidator.parse(types)); + return this; + } + setChannelTypes(...types) { + types = normalizeArray(types); + this.data.channel_types ??= []; + this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types)); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + customIdValidator.parse(this.data.custom_id); + return { + ...this.data + }; + } +}; +__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 + }); + } +}; +__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 + }); + } +}; +__name(RoleSelectMenuBuilder, "RoleSelectMenuBuilder"); + +// src/components/selectMenu/StringSelectMenu.ts +import { ComponentType as ComponentType5 } from "discord-api-types/v10"; +var StringSelectMenuBuilder = 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 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 to this select menu + * @returns + */ + addOptions(...options) { + options = normalizeArray(options); + optionsLengthValidator.parse(this.options.length + options.length); + this.options.push(...options.map((option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)))); + return this; + } + /** + * Sets the options on this select menu + * + * @param options - The options to set on this select menu + */ + setOptions(...options) { + return this.spliceOptions(0, this.options.length, ...options); + } + /** + * Removes, replaces, or inserts options in the string 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 order of the already-existing options of a string select menu. + * @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) { + options = normalizeArray(options); + const clone = [ + ...this.options + ]; + clone.splice(index, deleteCount, ...options.map((option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)))); + optionsLengthValidator.parse(clone.length); + this.options.splice(0, this.options.length, ...clone); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredSelectMenuParameters(this.options, this.data.custom_id); + return { + ...this.data, + options: this.options.map((option) => option.toJSON()) + }; + } +}; +__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 + }); + } +}; +__name(UserSelectMenuBuilder, "UserSelectMenuBuilder"); + +// src/components/textInput/TextInput.ts +import { isJSONEncodable } from "@discordjs/util"; +import { ComponentType as ComponentType7 } from "discord-api-types/v10"; +import isEqual from "fast-deep-equal"; + +// src/components/textInput/Assertions.ts +var Assertions_exports3 = {}; +__export(Assertions_exports3, { + labelValidator: () => labelValidator, + maxLengthValidator: () => maxLengthValidator, + minLengthValidator: () => minLengthValidator, + placeholderValidator: () => placeholderValidator2, + requiredValidator: () => requiredValidator, + textInputStyleValidator: () => textInputStyleValidator, + validateRequiredParameters: () => validateRequiredParameters, + valueValidator: () => valueValidator +}); +import { s as s3 } from "@sapphire/shapeshift"; +import { TextInputStyle } from "discord-api-types/v10"; +var textInputStyleValidator = s3.nativeEnum(TextInputStyle); +var minLengthValidator = s3.number.int.greaterThanOrEqual(0).lessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var maxLengthValidator = s3.number.int.greaterThanOrEqual(1).lessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var requiredValidator = s3.boolean; +var valueValidator = s3.string.lengthLessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var placeholderValidator2 = s3.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var labelValidator = s3.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(45).setValidationEnabled(isValidationEnabled); +function validateRequiredParameters(customId, style, label) { + customIdValidator.parse(customId); + textInputStyleValidator.parse(style); + labelValidator.parse(label); +} +__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 of this text input + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets the label for this text input + * + * @param label - The label for this text input + */ + setLabel(label) { + this.data.label = labelValidator.parse(label); + return this; + } + /** + * Sets the style for this text input + * + * @param style - The style for this text input + */ + 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 of this text input + * + * @param placeholder - The placeholder of this text input + */ + setPlaceholder(placeholder) { + this.data.placeholder = placeholderValidator2.parse(placeholder); + return this; + } + /** + * Sets the value of this text input + * + * @param value - The value for this text input + */ + 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); + } + return isEqual(other, this.data); + } +}; +__name(TextInputBuilder, "TextInputBuilder"); + +// src/components/Components.ts +function createComponentBuilder(data) { + if (data instanceof ComponentBuilder) { + return data; + } + switch (data.type) { + case ComponentType8.ActionRow: + return new ActionRowBuilder(data); + case ComponentType8.Button: + return new ButtonBuilder(data); + case ComponentType8.StringSelect: + return new StringSelectMenuBuilder(data); + case ComponentType8.TextInput: + return new TextInputBuilder(data); + case ComponentType8.UserSelect: + return new UserSelectMenuBuilder(data); + case ComponentType8.RoleSelect: + return new RoleSelectMenuBuilder(data); + case ComponentType8.MentionableSelect: + return new MentionableSelectMenuBuilder(data); + case ComponentType8.ChannelSelect: + return new ChannelSelectMenuBuilder(data); + default: + throw new Error(`Cannot properly serialize component type: ${data.type}`); + } +} +__name(createComponentBuilder, "createComponentBuilder"); + +// src/components/ActionRow.ts +var ActionRowBuilder = class extends ComponentBuilder { + /** + * 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 to this action row. + */ + addComponents(...components) { + this.components.push(...normalizeArray(components)); + return this; + } + /** + * Sets the components in this action row + * + * @param components - The components to set this row to + */ + setComponents(...components) { + this.components.splice(0, this.components.length, ...normalizeArray(components)); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + return { + ...this.data, + components: this.components.map((component) => component.toJSON()) + }; + } +}; +__name(ActionRowBuilder, "ActionRowBuilder"); + +// src/interactions/modals/Assertions.ts +var Assertions_exports4 = {}; +__export(Assertions_exports4, { + componentsValidator: () => componentsValidator, + titleValidator: () => titleValidator, + validateRequiredParameters: () => validateRequiredParameters2 +}); +import { s as s4 } from "@sapphire/shapeshift"; +var titleValidator = s4.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(45).setValidationEnabled(isValidationEnabled); +var componentsValidator = s4.instance(ActionRowBuilder).array.lengthGreaterThanOrEqual(1).setValidationEnabled(isValidationEnabled); +function validateRequiredParameters2(customId, title, components) { + customIdValidator.parse(customId); + titleValidator.parse(title); + componentsValidator.parse(components); +} +__name(validateRequiredParameters2, "validateRequiredParameters"); + +// src/interactions/modals/Modal.ts +var ModalBuilder = class { + components = []; + constructor({ components, ...data } = {}) { + this.data = { + ...data + }; + this.components = components?.map((component) => createComponentBuilder(component)) ?? []; + } + /** + * Sets the title of the modal + * + * @param title - The title of the modal + */ + setTitle(title) { + this.data.title = titleValidator.parse(title); + return this; + } + /** + * Sets the custom id of the modal + * + * @param customId - The custom id of this modal + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Adds components to this modal + * + * @param components - The components to add to this modal + */ + addComponents(...components) { + this.components.push(...normalizeArray(components).map((component) => component instanceof ActionRowBuilder ? component : new ActionRowBuilder(component))); + return this; + } + /** + * Sets the components in this modal + * + * @param components - The components to set this modal to + */ + 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 { + ...this.data, + components: this.components.map((component) => component.toJSON()) + }; + } +}; +__name(ModalBuilder, "ModalBuilder"); + +// src/interactions/slashCommands/Assertions.ts +var Assertions_exports5 = {}; +__export(Assertions_exports5, { + assertReturnOfBuilder: () => assertReturnOfBuilder, + localizationMapPredicate: () => localizationMapPredicate, + validateChoicesLength: () => validateChoicesLength, + validateDMPermission: () => validateDMPermission, + validateDefaultMemberPermissions: () => validateDefaultMemberPermissions, + validateDefaultPermission: () => validateDefaultPermission, + validateDescription: () => validateDescription, + validateLocale: () => validateLocale, + validateLocalizationMap: () => validateLocalizationMap, + validateMaxOptionsLength: () => validateMaxOptionsLength, + validateNSFW: () => validateNSFW, + validateName: () => validateName, + validateRequired: () => validateRequired, + validateRequiredParameters: () => validateRequiredParameters3 +}); +import { s as s5 } from "@sapphire/shapeshift"; +import { Locale } from "discord-api-types/v10"; +var namePredicate = s5.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(32).regex(/^[\p{Ll}\p{Lm}\p{Lo}\p{N}\p{sc=Devanagari}\p{sc=Thai}_-]+$/u).setValidationEnabled(isValidationEnabled); +function validateName(name) { + namePredicate.parse(name); +} +__name(validateName, "validateName"); +var descriptionPredicate2 = s5.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var localePredicate = s5.nativeEnum(Locale); +function validateDescription(description) { + descriptionPredicate2.parse(description); +} +__name(validateDescription, "validateDescription"); +var maxArrayLengthPredicate = s5.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateLocale(locale) { + return localePredicate.parse(locale); +} +__name(validateLocale, "validateLocale"); +function validateMaxOptionsLength(options) { + maxArrayLengthPredicate.parse(options); +} +__name(validateMaxOptionsLength, "validateMaxOptionsLength"); +function validateRequiredParameters3(name, description, options) { + validateName(name); + validateDescription(description); + validateMaxOptionsLength(options); +} +__name(validateRequiredParameters3, "validateRequiredParameters"); +var booleanPredicate = s5.boolean; +function validateDefaultPermission(value) { + booleanPredicate.parse(value); +} +__name(validateDefaultPermission, "validateDefaultPermission"); +function validateRequired(required) { + booleanPredicate.parse(required); +} +__name(validateRequired, "validateRequired"); +var choicesLengthPredicate = s5.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateChoicesLength(amountAdding, choices) { + choicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding); +} +__name(validateChoicesLength, "validateChoicesLength"); +function assertReturnOfBuilder(input, ExpectedInstanceOf) { + s5.instance(ExpectedInstanceOf).parse(input); +} +__name(assertReturnOfBuilder, "assertReturnOfBuilder"); +var localizationMapPredicate = s5.object(Object.fromEntries(Object.values(Locale).map((locale) => [ + locale, + s5.string.nullish +]))).strict.nullish.setValidationEnabled(isValidationEnabled); +function validateLocalizationMap(value) { + localizationMapPredicate.parse(value); +} +__name(validateLocalizationMap, "validateLocalizationMap"); +var dmPermissionPredicate = s5.boolean.nullish; +function validateDMPermission(value) { + dmPermissionPredicate.parse(value); +} +__name(validateDMPermission, "validateDMPermission"); +var memberPermissionPredicate = s5.union(s5.bigint.transform((value) => value.toString()), s5.number.safeInt.transform((value) => value.toString()), s5.string.regex(/^\d+$/)).nullish; +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"; + +// src/interactions/slashCommands/SlashCommandSubcommands.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType11 } from "discord-api-types/v10"; +import { mix as mix5 } from "ts-mixer"; + +// src/interactions/slashCommands/mixins/NameAndDescription.ts +var SharedNameAndDescription = class { + /** + * Sets the name + * + * @param name - The name + */ + setName(name) { + validateName(name); + Reflect.set(this, "name", name); + return this; + } + /** + * Sets the description + * + * @param description - The description + */ + setDescription(description) { + validateDescription(description); + Reflect.set(this, "description", description); + return this; + } + /** + * Sets a name localization + * + * @param locale - The locale to set a description for + * @param localizedName - The localized description for the given locale + */ + setNameLocalization(locale, localizedName) { + if (!this.name_localizations) { + Reflect.set(this, "name_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedName === null) { + this.name_localizations[parsedLocale] = null; + return this; + } + validateName(localizedName); + this.name_localizations[parsedLocale] = localizedName; + return this; + } + /** + * Sets the name localizations + * + * @param localizedNames - The dictionary of localized descriptions to set + */ + setNameLocalizations(localizedNames) { + if (localizedNames === null) { + Reflect.set(this, "name_localizations", null); + return this; + } + Reflect.set(this, "name_localizations", {}); + for (const args of Object.entries(localizedNames)) { + this.setNameLocalization(...args); + } + return this; + } + /** + * Sets a description localization + * + * @param locale - The locale to set a description for + * @param localizedDescription - The localized description for the given locale + */ + setDescriptionLocalization(locale, localizedDescription) { + if (!this.description_localizations) { + Reflect.set(this, "description_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedDescription === null) { + this.description_localizations[parsedLocale] = null; + return this; + } + validateDescription(localizedDescription); + this.description_localizations[parsedLocale] = localizedDescription; + return this; + } + /** + * Sets the description localizations + * + * @param localizedDescriptions - The dictionary of localized descriptions to set + */ + setDescriptionLocalizations(localizedDescriptions) { + if (localizedDescriptions === null) { + Reflect.set(this, "description_localizations", null); + return this; + } + Reflect.set(this, "description_localizations", {}); + for (const args of Object.entries(localizedDescriptions)) { + this.setDescriptionLocalization(...args); + } + return this; + } +}; +__name(SharedNameAndDescription, "SharedNameAndDescription"); + +// src/interactions/slashCommands/options/attachment.ts +import { ApplicationCommandOptionType } from "discord-api-types/v10"; + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts +var ApplicationCommandOptionBase = class extends SharedNameAndDescription { + required = false; + /** + * Marks the option as required + * + * @param required - If this option should be required + */ + setRequired(required) { + validateRequired(required); + Reflect.set(this, "required", required); + return this; + } + runRequiredValidations() { + validateRequiredParameters3(this.name, this.description, []); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + validateRequired(this.required); + } +}; +__name(ApplicationCommandOptionBase, "ApplicationCommandOptionBase"); + +// src/interactions/slashCommands/options/attachment.ts +var SlashCommandAttachmentOption = class extends ApplicationCommandOptionBase { + type = ApplicationCommandOptionType.Attachment; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandAttachmentOption, "SlashCommandAttachmentOption"); + +// src/interactions/slashCommands/options/boolean.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType2 } from "discord-api-types/v10"; +var SlashCommandBooleanOption = class extends ApplicationCommandOptionBase { + type = ApplicationCommandOptionType2.Boolean; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandBooleanOption, "SlashCommandBooleanOption"); + +// src/interactions/slashCommands/options/channel.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType3 } from "discord-api-types/v10"; +import { mix } from "ts-mixer"; + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts +import { s as s6 } from "@sapphire/shapeshift"; +import { ChannelType as ChannelType2 } from "discord-api-types/v10"; +var allowedChannelTypes = [ + ChannelType2.GuildText, + ChannelType2.GuildVoice, + ChannelType2.GuildCategory, + ChannelType2.GuildAnnouncement, + ChannelType2.AnnouncementThread, + ChannelType2.PublicThread, + ChannelType2.PrivateThread, + ChannelType2.GuildStageVoice, + ChannelType2.GuildForum +]; +var channelTypesPredicate = s6.array(s6.union(...allowedChannelTypes.map((type) => s6.literal(type)))); +var ApplicationCommandOptionChannelTypesMixin = class { + /** + * Adds channel types to this option + * + * @param channelTypes - The channel types to add + */ + addChannelTypes(...channelTypes) { + if (this.channel_types === void 0) { + Reflect.set(this, "channel_types", []); + } + this.channel_types.push(...channelTypesPredicate.parse(channelTypes)); + return this; + } +}; +__name(ApplicationCommandOptionChannelTypesMixin, "ApplicationCommandOptionChannelTypesMixin"); + +// src/interactions/slashCommands/options/channel.ts +var __decorate = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var SlashCommandChannelOption = /* @__PURE__ */ __name(class SlashCommandChannelOption2 extends ApplicationCommandOptionBase { + type = ApplicationCommandOptionType3.Channel; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}, "SlashCommandChannelOption"); +SlashCommandChannelOption = __decorate([ + mix(ApplicationCommandOptionChannelTypesMixin) +], SlashCommandChannelOption); + +// src/interactions/slashCommands/options/integer.ts +import { s as s8 } from "@sapphire/shapeshift"; +import { ApplicationCommandOptionType as ApplicationCommandOptionType5 } from "discord-api-types/v10"; +import { mix as mix2 } from "ts-mixer"; + +// src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts +var ApplicationCommandNumericOptionMinMaxValueMixin = class { +}; +__name(ApplicationCommandNumericOptionMinMaxValueMixin, "ApplicationCommandNumericOptionMinMaxValueMixin"); + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts +import { s as s7 } from "@sapphire/shapeshift"; +import { ApplicationCommandOptionType as ApplicationCommandOptionType4 } from "discord-api-types/v10"; +var stringPredicate = s7.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100); +var numberPredicate = s7.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY); +var choicesPredicate = s7.object({ + name: stringPredicate, + name_localizations: localizationMapPredicate, + value: s7.union(stringPredicate, numberPredicate) +}).array; +var booleanPredicate2 = s7.boolean; +var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { + /** + * Adds multiple choices for 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."); + } + choicesPredicate.parse(choices); + if (this.choices === void 0) { + Reflect.set(this, "choices", []); + } + validateChoicesLength(choices.length, this.choices); + for (const { name, name_localizations, value } of choices) { + if (this.type === ApplicationCommandOptionType4.String) { + stringPredicate.parse(value); + } else { + numberPredicate.parse(value); + } + this.choices.push({ + name, + name_localizations, + value + }); + } + return this; + } + setChoices(...choices) { + if (choices.length > 0 && this.autocomplete) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + choicesPredicate.parse(choices); + Reflect.set(this, "choices", []); + this.addChoices(...choices); + return this; + } + /** + * Marks the option as autocompletable + * + * @param autocomplete - If this option should be autocompletable + */ + setAutocomplete(autocomplete) { + booleanPredicate2.parse(autocomplete); + if (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + Reflect.set(this, "autocomplete", autocomplete); + return this; + } +}; +__name(ApplicationCommandOptionWithChoicesAndAutocompleteMixin, "ApplicationCommandOptionWithChoicesAndAutocompleteMixin"); + +// src/interactions/slashCommands/options/integer.ts +var __decorate2 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var numberValidator = s8.number.int; +var SlashCommandIntegerOption = /* @__PURE__ */ __name(class SlashCommandIntegerOption2 extends ApplicationCommandOptionBase { + 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; + } + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { + ...this + }; + } +}, "SlashCommandIntegerOption"); +SlashCommandIntegerOption = __decorate2([ + mix2(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandIntegerOption); + +// src/interactions/slashCommands/options/mentionable.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType6 } from "discord-api-types/v10"; +var SlashCommandMentionableOption = class extends ApplicationCommandOptionBase { + type = ApplicationCommandOptionType6.Mentionable; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandMentionableOption, "SlashCommandMentionableOption"); + +// src/interactions/slashCommands/options/number.ts +import { s as s9 } from "@sapphire/shapeshift"; +import { ApplicationCommandOptionType as ApplicationCommandOptionType7 } from "discord-api-types/v10"; +import { mix as mix3 } from "ts-mixer"; +var __decorate3 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var numberValidator2 = s9.number; +var SlashCommandNumberOption = /* @__PURE__ */ __name(class SlashCommandNumberOption2 extends ApplicationCommandOptionBase { + 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; + } + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { + ...this + }; + } +}, "SlashCommandNumberOption"); +SlashCommandNumberOption = __decorate3([ + mix3(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandNumberOption); + +// src/interactions/slashCommands/options/role.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType8 } from "discord-api-types/v10"; +var SlashCommandRoleOption = class extends ApplicationCommandOptionBase { + type = ApplicationCommandOptionType8.Role; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandRoleOption, "SlashCommandRoleOption"); + +// src/interactions/slashCommands/options/string.ts +import { s as s10 } from "@sapphire/shapeshift"; +import { ApplicationCommandOptionType as ApplicationCommandOptionType9 } from "discord-api-types/v10"; +import { mix as mix4 } from "ts-mixer"; +var __decorate4 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var minLengthValidator2 = s10.number.greaterThanOrEqual(0).lessThanOrEqual(6e3); +var maxLengthValidator2 = s10.number.greaterThanOrEqual(1).lessThanOrEqual(6e3); +var SlashCommandStringOption = /* @__PURE__ */ __name(class SlashCommandStringOption2 extends ApplicationCommandOptionBase { + type = ApplicationCommandOptionType9.String; + /** + * 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; + } + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { + ...this + }; + } +}, "SlashCommandStringOption"); +SlashCommandStringOption = __decorate4([ + mix4(ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandStringOption); + +// src/interactions/slashCommands/options/user.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType10 } from "discord-api-types/v10"; +var SlashCommandUserOption = class extends ApplicationCommandOptionBase { + type = ApplicationCommandOptionType10.User; + toJSON() { + this.runRequiredValidations(); + return { + ...this + }; + } +}; +__name(SlashCommandUserOption, "SlashCommandUserOption"); + +// src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts +var SharedSlashCommandOptions = class { + /** + * 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); + } + _sharedAddOptionMethod(input, Instance) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new Instance()) : input; + assertReturnOfBuilder(result, Instance); + options.push(result); + return this; + } +}; +__name(SharedSlashCommandOptions, "SharedSlashCommandOptions"); + +// src/interactions/slashCommands/SlashCommandSubcommands.ts +var __decorate5 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var SlashCommandSubcommandGroupBuilder = /* @__PURE__ */ __name(class SlashCommandSubcommandGroupBuilder2 { + /** + * The name of this subcommand group + */ + name = void 0; + /** + * The description of this subcommand group + */ + description = void 0; + /** + * The subcommands part of 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); + const result = typeof input === "function" ? input(new SlashCommandSubcommandBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandBuilder); + options.push(result); + return this; + } + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + return { + type: ApplicationCommandOptionType11.SubcommandGroup, + name: this.name, + name_localizations: this.name_localizations, + description: this.description, + description_localizations: this.description_localizations, + options: this.options.map((option) => option.toJSON()) + }; + } +}, "SlashCommandSubcommandGroupBuilder"); +SlashCommandSubcommandGroupBuilder = __decorate5([ + mix5(SharedNameAndDescription) +], SlashCommandSubcommandGroupBuilder); +var SlashCommandSubcommandBuilder = /* @__PURE__ */ __name(class SlashCommandSubcommandBuilder2 { + /** + * The name of this subcommand + */ + name = void 0; + /** + * The description of this subcommand + */ + description = void 0; + /** + * The options of this subcommand + */ + options = []; + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + return { + type: ApplicationCommandOptionType11.Subcommand, + name: this.name, + name_localizations: this.name_localizations, + description: this.description, + description_localizations: this.description_localizations, + options: this.options.map((option) => option.toJSON()) + }; + } +}, "SlashCommandSubcommandBuilder"); +SlashCommandSubcommandBuilder = __decorate5([ + mix5(SharedNameAndDescription, SharedSlashCommandOptions) +], SlashCommandSubcommandBuilder); + +// src/interactions/slashCommands/SlashCommandBuilder.ts +var __decorate6 = function(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var SlashCommandBuilder = /* @__PURE__ */ __name(class SlashCommandBuilder2 { + /** + * The name of this slash command + */ + name = void 0; + /** + * The description of this slash command + */ + description = void 0; + /** + * The options of this slash command + */ + options = []; + /** + * Whether the command is enabled by default when the app 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. + */ + default_permission = void 0; + /** + * Set of permissions represented as a bit set for the command + */ + default_member_permissions = void 0; + /** + * Indicates whether the command is available in DMs with the application, only for globally-scoped commands. + * By default, commands are visible. + */ + dm_permission = void 0; + /** + * Whether this command is NSFW + */ + nsfw = void 0; + /** + * 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. + */ + 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()) + }; + } + /** + * 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. + */ + 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 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 DMs with the application, only for globally-scoped commands. + * By default, commands are visible. + * + * @param enabled - If the command should be enabled in DMs + * @see 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); + const result = typeof input === "function" ? input(new SlashCommandSubcommandGroupBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder); + 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); + const result = typeof input === "function" ? input(new SlashCommandSubcommandBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandBuilder); + options.push(result); + return this; + } +}, "SlashCommandBuilder"); +SlashCommandBuilder = __decorate6([ + mix6(SharedSlashCommandOptions, SharedNameAndDescription) +], SlashCommandBuilder); + +// src/interactions/contextMenuCommands/Assertions.ts +var Assertions_exports6 = {}; +__export(Assertions_exports6, { + validateDMPermission: () => validateDMPermission2, + validateDefaultMemberPermissions: () => validateDefaultMemberPermissions2, + validateDefaultPermission: () => validateDefaultPermission2, + validateName: () => validateName2, + validateRequiredParameters: () => validateRequiredParameters4, + validateType: () => validateType +}); +import { s as s11 } from "@sapphire/shapeshift"; +import { ApplicationCommandType } from "discord-api-types/v10"; +var namePredicate2 = s11.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(32).regex(/^( *[\p{P}\p{L}\p{N}\p{sc=Devanagari}\p{sc=Thai}]+ *)+$/u).setValidationEnabled(isValidationEnabled); +var typePredicate = s11.union(s11.literal(ApplicationCommandType.User), s11.literal(ApplicationCommandType.Message)).setValidationEnabled(isValidationEnabled); +var booleanPredicate3 = s11.boolean; +function validateDefaultPermission2(value) { + booleanPredicate3.parse(value); +} +__name(validateDefaultPermission2, "validateDefaultPermission"); +function validateName2(name) { + namePredicate2.parse(name); +} +__name(validateName2, "validateName"); +function validateType(type) { + typePredicate.parse(type); +} +__name(validateType, "validateType"); +function validateRequiredParameters4(name, type) { + validateName2(name); + validateType(type); +} +__name(validateRequiredParameters4, "validateRequiredParameters"); +var dmPermissionPredicate2 = s11.boolean.nullish; +function validateDMPermission2(value) { + dmPermissionPredicate2.parse(value); +} +__name(validateDMPermission2, "validateDMPermission"); +var memberPermissionPredicate2 = s11.union(s11.bigint.transform((value) => value.toString()), s11.number.safeInt.transform((value) => value.toString()), s11.string.regex(/^\d+$/)).nullish; +function validateDefaultMemberPermissions2(permissions) { + return memberPermissionPredicate2.parse(permissions); +} +__name(validateDefaultMemberPermissions2, "validateDefaultMemberPermissions"); + +// src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts +var ContextMenuCommandBuilder = class { + /** + * The name of this context menu command + */ + name = void 0; + /** + * The type of this context menu command + */ + type = void 0; + /** + * Whether the command is enabled by default when the app 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. + */ + default_permission = void 0; + /** + * Set of permissions represented as a bit set for the command + */ + default_member_permissions = void 0; + /** + * Indicates whether the command is available in DMs with the application, only for globally-scoped commands. + * By default, commands are visible. + */ + dm_permission = void 0; + /** + * Sets the name + * + * @param name - The name + */ + setName(name) { + validateName2(name); + Reflect.set(this, "name", name); + return this; + } + /** + * Sets the type + * + * @param type - The type + */ + 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 or not to enable this command by default + * @see 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 the 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 + */ + setDefaultMemberPermissions(permissions) { + const permissionValue = validateDefaultMemberPermissions2(permissions); + Reflect.set(this, "default_member_permissions", permissionValue); + return this; + } + /** + * Sets if the command is available in DMs with the application, only for globally-scoped commands. + * By default, commands are visible. + * + * @param enabled - If the command should be enabled in DMs + * @see 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 + * + * @param locale - The locale to set a description for + * @param localizedName - The localized description for the given locale + */ + setNameLocalization(locale, localizedName) { + if (!this.name_localizations) { + Reflect.set(this, "name_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedName === null) { + this.name_localizations[parsedLocale] = null; + return this; + } + validateName2(localizedName); + this.name_localizations[parsedLocale] = localizedName; + return this; + } + /** + * Sets the name localizations + * + * @param localizedNames - The dictionary of localized descriptions to set + */ + setNameLocalizations(localizedNames) { + if (localizedNames === null) { + Reflect.set(this, "name_localizations", null); + return this; + } + Reflect.set(this, "name_localizations", {}); + for (const args of Object.entries(localizedNames)) + this.setNameLocalization(...args); + return this; + } + /** + * 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. + */ + toJSON() { + validateRequiredParameters4(this.name, this.type); + validateLocalizationMap(this.name_localizations); + return { + ...this + }; + } +}; +__name(ContextMenuCommandBuilder, "ContextMenuCommandBuilder"); + +// src/util/componentUtil.ts +function embedLength(data) { + return (data.title?.length ?? 0) + (data.description?.length ?? 0) + (data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) + (data.footer?.text.length ?? 0) + (data.author?.name.length ?? 0); +} +__name(embedLength, "embedLength"); + +// src/index.ts +export * from "@discordjs/util"; +var version = "[VI]{{inject}}[/VI]"; +export { + ActionRowBuilder, + ApplicationCommandNumericOptionMinMaxValueMixin, + ApplicationCommandOptionBase, + ApplicationCommandOptionChannelTypesMixin, + ApplicationCommandOptionWithChoicesAndAutocompleteMixin, + BaseSelectMenuBuilder, + ButtonBuilder, + ChannelSelectMenuBuilder, + Assertions_exports2 as ComponentAssertions, + ComponentBuilder, + Assertions_exports6 as ContextMenuCommandAssertions, + ContextMenuCommandBuilder, + Assertions_exports as EmbedAssertions, + EmbedBuilder, + MentionableSelectMenuBuilder, + Assertions_exports4 as ModalAssertions, + ModalBuilder, + RoleSelectMenuBuilder, + StringSelectMenuBuilder as SelectMenuBuilder, + StringSelectMenuOptionBuilder as SelectMenuOptionBuilder, + SharedNameAndDescription, + SharedSlashCommandOptions, + Assertions_exports5 as SlashCommandAssertions, + SlashCommandAttachmentOption, + SlashCommandBooleanOption, + SlashCommandBuilder, + SlashCommandChannelOption, + SlashCommandIntegerOption, + SlashCommandMentionableOption, + SlashCommandNumberOption, + SlashCommandRoleOption, + SlashCommandStringOption, + SlashCommandSubcommandBuilder, + SlashCommandSubcommandGroupBuilder, + SlashCommandUserOption, + StringSelectMenuBuilder, + StringSelectMenuOptionBuilder, + Assertions_exports3 as TextInputAssertions, + TextInputBuilder, + UserSelectMenuBuilder, + createComponentBuilder, + disableValidators, + embedLength, + enableValidators, + isValidationEnabled, + normalizeArray, + 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 new file mode 100644 index 0000000..8b72d7e --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.mjs.map @@ -0,0 +1 @@ +{"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\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/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 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","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';\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\nexport const version = '[VI]{{inject}}[/VI]' 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 * 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\treturn this.spliceOptions(0, this.options.length, ...options);\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts options in the string 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 *\n\t * It's useful for modifying and adjusting order of the already-existing options of a string select menu.\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\t// eslint-disable-next-line no-param-reassign\n\t\toptions = 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...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\n\t\toptionsLengthValidator.parse(clone.length);\n\n\t\tthis.options.splice(0, this.options.length, ...clone);\n\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\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@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 * Whether this command is NSFW\n\t */\n\tpublic readonly nsfw: 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 * 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\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":";;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;AAAA,SAASA,SAAS;;;ACAlB,IAAIC,WAAW;AAER,IAAMC,mBAAmB,6BAAOD,WAAW,MAAlB;AACzB,IAAME,oBAAoB,6BAAOF,WAAW,OAAlB;AAC1B,IAAMG,sBAAsB,6BAAMH,UAAN;;;ADA5B,IAAMI,qBAAqBC,EAAEC,OAClCC,yBAAyB,CAAA,EACzBC,sBAAsB,GAAA,EACtBC,qBAAqBC,mBAAAA;AAEhB,IAAMC,sBAAsBN,EAAEC,OACnCC,yBAAyB,CAAA,EACzBC,sBAAsB,IAAA,EACtBC,qBAAqBC,mBAAAA;AAEhB,IAAME,uBAAuBP,EAAEQ,QAAQC;AAEvC,IAAMC,sBAAsBV,EACjCW,OAAO;EACPC,MAAMb;EACNc,OAAOP;EACPQ,QAAQP;AACT,CAAA,EACCH,qBAAqBC,mBAAAA;AAEhB,IAAMU,4BAA4BL,oBAAoBM,MAAMZ,qBAAqBC,mBAAAA;AAEjF,IAAMY,uBAAuBjB,EAAEkB,OAAOC,gBAAgB,EAAA,EAAIf,qBAAqBC,mBAAAA;AAE/E,SAASe,oBAAoBC,cAAsBC,QAAgC;AACzFL,uBAAqBM,OAAOD,QAAQE,UAAU,KAAKH,YAAAA;AACpD;AAFgBD;AAIT,IAAMK,sBAAsB1B,mBA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oBAAmB,GAAKQ,IAAAA;AAC9B,WAAO;EACR;;;;;;;;EASOG,SAA4D;AAClEC,IAAAA,4BAA2B,KAAKlC,MAAM,KAAKE,IAAI;AAE/CiC,4BAAwB,KAAKV,kBAAkB;AAE/C,WAAO;MAAE,GAAG;IAAK;EAClB;AACD;AA1Ka1B;;;ACfN,SAASqC,YAAYC,MAAgB;AAC3C,UACEA,KAAKC,OAAOC,UAAU,MACtBF,KAAKG,aAAaD,UAAU,MAC5BF,KAAKI,QAAQC,OAAO,CAACC,MAAMC,SAASD,OAAOC,KAAKC,KAAKN,SAASK,KAAKE,MAAMP,QAAQ,CAAA,KAAM,MACvFF,KAAKU,QAAQC,KAAKT,UAAU,MAC5BF,KAAKY,QAAQJ,KAAKN,UAAU;AAE/B;AARgBH;;;ArC2DhB,cAAc;AAOP,IAAMc,UAAU;","names":["s","validate","enableValidators","disableValidators","isValidationEnabled","fieldNamePredicate","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","setValidationEnabled","isValidationEnabled","fieldValuePredicate","fieldInlinePredicate","boolean","optional","embedFieldPredicate","object","name","value","inline","embedFieldsArrayPredicate","array","fieldLengthPredicate","number","lessThanOrEqual","validateFieldLength","amountAdding","fields","parse","length","authorNamePredicate","nullable","imageURLPredicate","url","allowedProtocols","nullish","urlPredicate","embedAuthorPredicate","iconURL","RGBPredicate","int","greaterThanOrEqual","colorPredicate","or","tuple","descriptionPredicate","footerTextPredicate","embedFooterPredicate","text","timestampPredicate","union","date","titlePredicate","normalizeArray","arr","Array","isArray","EmbedBuilder","data","timestamp","Date","toISOString","addFields","fields","normalizeArray","validateFieldLength","length","embedFieldsArrayPredicate","parse","push","spliceFields","index","deleteCount","splice","setFields","setAuthor","options","author","undefined","embedAuthorPredicate","name","url","icon_url","iconURL","setColor","color","colorPredicate","Array","isArray","red","green","blue","setDescription","description","descriptionPredicate","setFooter","footer","embedFooterPredicate","text","setImage","imageURLPredicate","image","setThumbnail","thumbnail","setTimestamp","now","timestampPredicate","setTitle","title","titlePredicate","setURL","urlPredicate","toJSON","Assertions_exports","s","ButtonStyle","ChannelType","StringSelectMenuOptionBuilder","data","setLabel","label","labelValueDescriptionValidator","parse","setValue","value","setDescription","description","setDefault","isDefault","default","defaultValidator","setEmoji","emoji","emojiValidator","toJSON","validateRequiredSelectMenuOptionParameters","customIdValidator","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","setValidationEnabled","isValidationEnabled","emojiValidator","object","id","name","animated","boolean","partial","strict","disabledValidator","buttonLabelValidator","buttonStyleValidator","nativeEnum","ButtonStyle","placeholderValidator","minMaxValidator","number","int","greaterThanOrEqual","lessThanOrEqual","labelValueDescriptionValidator","jsonOptionValidator","label","value","description","optional","emoji","default","optionValidator","instance","StringSelectMenuOptionBuilder","optionsValidator","array","optionsLengthValidator","validateRequiredSelectMenuParameters","options","customId","parse","defaultValidator","validateRequiredSelectMenuOptionParameters","channelTypesValidator","ChannelType","urlValidator","url","allowedProtocols","validateRequiredButtonParameters","style","RangeError","Link","ComponentType","ComponentBuilder","data","ComponentType","ComponentType","ButtonBuilder","ComponentBuilder","data","type","ComponentType","Button","setStyle","style","buttonStyleValidator","parse","setURL","url","urlValidator","setCustomId","customId","custom_id","customIdValidator","setEmoji","emoji","emojiValidator","setDisabled","disabled","disabledValidator","setLabel","label","buttonLabelValidator","toJSON","validateRequiredButtonParameters","ComponentType","BaseSelectMenuBuilder","ComponentBuilder","setPlaceholder","placeholder","data","placeholderValidator","parse","setMinValues","minValues","min_values","minMaxValidator","setMaxValues","maxValues","max_values","setCustomId","customId","custom_id","customIdValidator","setDisabled","disabled","disabledValidator","toJSON","ChannelSelectMenuBuilder","BaseSelectMenuBuilder","data","type","ComponentType","ChannelSelect","addChannelTypes","types","normalizeArray","channel_types","push","channelTypesValidator","parse","setChannelTypes","splice","length","toJSON","customIdValidator","custom_id","ComponentType","MentionableSelectMenuBuilder","BaseSelectMenuBuilder","data","type","ComponentType","MentionableSelect","ComponentType","RoleSelectMenuBuilder","BaseSelectMenuBuilder","data","type","ComponentType","RoleSelect","ComponentType","StringSelectMenuBuilder","BaseSelectMenuBuilder","data","options","initData","type","ComponentType","StringSelect","map","option","StringSelectMenuOptionBuilder","addOptions","normalizeArray","optionsLengthValidator","parse","length","push","jsonOptionValidator","setOptions","spliceOptions","index","deleteCount","clone","splice","toJSON","validateRequiredSelectMenuParameters","custom_id","ComponentType","UserSelectMenuBuilder","BaseSelectMenuBuilder","data","type","ComponentType","UserSelect","isJSONEncodable","ComponentType","isEqual","Assertions_exports","placeholderValidator","s","TextInputStyle","textInputStyleValidator","s","nativeEnum","TextInputStyle","minLengthValidator","number","int","greaterThanOrEqual","lessThanOrEqual","setValidationEnabled","isValidationEnabled","maxLengthValidator","requiredValidator","boolean","valueValidator","string","lengthLessThanOrEqual","placeholderValidator","labelValidator","lengthGreaterThanOrEqual","validateRequiredParameters","customId","style","label","customIdValidator","parse","TextInputBuilder","ComponentBuilder","data","type","ComponentType","TextInput","setCustomId","customId","custom_id","customIdValidator","parse","setLabel","label","labelValidator","setStyle","style","textInputStyleValidator","setMinLength","minLength","min_length","minLengthValidator","setMaxLength","maxLength","max_length","maxLengthValidator","setPlaceholder","placeholder","placeholderValidator","setValue","value","valueValidator","setRequired","required","requiredValidator","toJSON","validateRequiredParameters","equals","other","isJSONEncodable","isEqual","createComponentBuilder","data","ComponentBuilder","type","ComponentType","ActionRow","ActionRowBuilder","Button","ButtonBuilder","StringSelect","StringSelectMenuBuilder","TextInput","TextInputBuilder","UserSelect","UserSelectMenuBuilder","RoleSelect","RoleSelectMenuBuilder","MentionableSelect","MentionableSelectMenuBuilder","ChannelSelect","ChannelSelectMenuBuilder","Error","ActionRowBuilder","ComponentBuilder","components","data","type","ComponentType","ActionRow","map","component","createComponentBuilder","addComponents","push","normalizeArray","setComponents","splice","length","toJSON","Assertions_exports","validateRequiredParameters","s","titleValidator","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","setValidationEnabled","isValidationEnabled","componentsValidator","instance","ActionRowBuilder","array","validateRequiredParameters","customId","title","components","customIdValidator","parse","ModalBuilder","components","data","map","component","createComponentBuilder","setTitle","title","titleValidator","parse","setCustomId","customId","custom_id","customIdValidator","addComponents","push","normalizeArray","ActionRowBuilder","setComponents","splice","length","toJSON","validateRequiredParameters","Assertions_exports","validateRequiredParameters","s","Locale","namePredicate","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","regex","setValidationEnabled","isValidationEnabled","validateName","name","parse","descriptionPredicate","localePredicate","nativeEnum","Locale","validateDescription","description","maxArrayLengthPredicate","unknown","array","validateLocale","locale","validateMaxOptionsLength","options","validateRequiredParameters","booleanPredicate","boolean","validateDefaultPermission","value","validateRequired","required","choicesLengthPredicate","number","lessThanOrEqual","validateChoicesLength","amountAdding","choices","length","assertReturnOfBuilder","input","ExpectedInstanceOf","instance","localizationMapPredicate","object","Object","fromEntries","values","map","nullish","strict","validateLocalizationMap","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","union","bigint","transform","toString","safeInt","validateDefaultMemberPermissions","permissions","validateNSFW","mix","ApplicationCommandOptionType","mix","SharedNameAndDescription","setName","name","validateName","Reflect","set","setDescription","description","validateDescription","setNameLocalization","locale","localizedName","name_localizations","parsedLocale","validateLocale","setNameLocalizations","localizedNames","args","Object","entries","setDescriptionLocalization","localizedDescription","description_localizations","setDescriptionLocalizations","localizedDescriptions","ApplicationCommandOptionType","ApplicationCommandOptionBase","SharedNameAndDescription","required","setRequired","validateRequired","Reflect","set","runRequiredValidations","validateRequiredParameters","name","description","validateLocalizationMap","name_localizations","description_localizations","SlashCommandAttachmentOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Attachment","toJSON","runRequiredValidations","ApplicationCommandOptionType","SlashCommandBooleanOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Boolean","toJSON","runRequiredValidations","ApplicationCommandOptionType","mix","s","ChannelType","allowedChannelTypes","ChannelType","GuildText","GuildVoice","GuildCategory","GuildAnnouncement","AnnouncementThread","PublicThread","PrivateThread","GuildStageVoice","GuildForum","channelTypesPredicate","s","array","union","map","type","literal","ApplicationCommandOptionChannelTypesMixin","addChannelTypes","channelTypes","channel_types","undefined","Reflect","set","push","parse","SlashCommandChannelOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Channel","toJSON","runRequiredValidations","mix","ApplicationCommandOptionChannelTypesMixin","s","ApplicationCommandOptionType","mix","ApplicationCommandNumericOptionMinMaxValueMixin","s","ApplicationCommandOptionType","stringPredicate","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","numberPredicate","number","greaterThan","Number","NEGATIVE_INFINITY","lessThan","POSITIVE_INFINITY","choicesPredicate","object","name","name_localizations","localizationMapPredicate","value","union","array","booleanPredicate","boolean","ApplicationCommandOptionWithChoicesAndAutocompleteMixin","addChoices","choices","length","autocomplete","RangeError","parse","undefined","Reflect","set","validateChoicesLength","type","ApplicationCommandOptionType","String","push","setChoices","setAutocomplete","Array","isArray","numberValidator","s","number","int","SlashCommandIntegerOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Integer","setMaxValue","max","parse","Reflect","set","setMinValue","min","toJSON","runRequiredValidations","autocomplete","Array","isArray","choices","length","RangeError","mix","ApplicationCommandNumericOptionMinMaxValueMixin","ApplicationCommandOptionWithChoicesAndAutocompleteMixin","ApplicationCommandOptionType","SlashCommandMentionableOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Mentionable","toJSON","runRequiredValidations","s","ApplicationCommandOptionType","mix","numberValidator","s","number","SlashCommandNumberOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Number","setMaxValue","max","parse","Reflect","set","setMinValue","min","toJSON","runRequiredValidations","autocomplete","Array","isArray","choices","length","RangeError","mix","ApplicationCommandNumericOptionMinMaxValueMixin","ApplicationCommandOptionWithChoicesAndAutocompleteMixin","ApplicationCommandOptionType","SlashCommandRoleOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","Role","toJSON","runRequiredValidations","s","ApplicationCommandOptionType","mix","minLengthValidator","s","number","greaterThanOrEqual","lessThanOrEqual","maxLengthValidator","SlashCommandStringOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","String","setMaxLength","max","parse","Reflect","set","setMinLength","min","toJSON","runRequiredValidations","autocomplete","Array","isArray","choices","length","RangeError","mix","ApplicationCommandOptionWithChoicesAndAutocompleteMixin","ApplicationCommandOptionType","SlashCommandUserOption","ApplicationCommandOptionBase","type","ApplicationCommandOptionType","User","toJSON","runRequiredValidations","SharedSlashCommandOptions","addBooleanOption","input","_sharedAddOptionMethod","SlashCommandBooleanOption","addUserOption","SlashCommandUserOption","addChannelOption","SlashCommandChannelOption","addRoleOption","SlashCommandRoleOption","addAttachmentOption","SlashCommandAttachmentOption","addMentionableOption","SlashCommandMentionableOption","addStringOption","SlashCommandStringOption","addIntegerOption","SlashCommandIntegerOption","addNumberOption","SlashCommandNumberOption","Instance","options","validateMaxOptionsLength","result","assertReturnOfBuilder","push","SlashCommandSubcommandGroupBuilder","name","undefined","description","options","addSubcommand","input","validateMaxOptionsLength","result","SlashCommandSubcommandBuilder","assertReturnOfBuilder","push","toJSON","validateRequiredParameters","type","ApplicationCommandOptionType","SubcommandGroup","name_localizations","description_localizations","map","option","mix","SharedNameAndDescription","Subcommand","SharedSlashCommandOptions","SlashCommandBuilder","name","undefined","description","options","default_permission","default_member_permissions","dm_permission","nsfw","toJSON","validateRequiredParameters","validateLocalizationMap","name_localizations","description_localizations","map","option","setDefaultPermission","value","validateDefaultPermission","Reflect","set","setDefaultMemberPermissions","permissions","permissionValue","validateDefaultMemberPermissions","setDMPermission","enabled","validateDMPermission","setNSFW","validateNSFW","addSubcommandGroup","input","validateMaxOptionsLength","result","SlashCommandSubcommandGroupBuilder","assertReturnOfBuilder","push","addSubcommand","SlashCommandSubcommandBuilder","mix","SharedSlashCommandOptions","SharedNameAndDescription","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","s","ApplicationCommandType","namePredicate","s","string","lengthGreaterThanOrEqual","lengthLessThanOrEqual","regex","setValidationEnabled","isValidationEnabled","typePredicate","union","literal","ApplicationCommandType","User","Message","booleanPredicate","boolean","validateDefaultPermission","value","parse","validateName","name","validateType","type","validateRequiredParameters","dmPermissionPredicate","nullish","validateDMPermission","memberPermissionPredicate","bigint","transform","toString","number","safeInt","validateDefaultMemberPermissions","permissions","ContextMenuCommandBuilder","name","undefined","type","default_permission","default_member_permissions","dm_permission","setName","validateName","Reflect","set","setType","validateType","setDefaultPermission","value","validateDefaultPermission","setDefaultMemberPermissions","permissions","permissionValue","validateDefaultMemberPermissions","setDMPermission","enabled","validateDMPermission","setNameLocalization","locale","localizedName","name_localizations","parsedLocale","validateLocale","setNameLocalizations","localizedNames","args","Object","entries","toJSON","validateRequiredParameters","validateLocalizationMap","embedLength","data","title","length","description","fields","reduce","prev","curr","name","value","footer","text","author","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/package.json b/node_modules/@discordjs/builders/package.json new file mode 100644 index 0000000..7691d31 --- /dev/null +++ b/node_modules/@discordjs/builders/package.json @@ -0,0 +1,88 @@ +{ + "name": "@discordjs/builders", + "version": "1.5.0", + "description": "A set of builders that you can use when creating your bot", + "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", + "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": { + "import": "./dist/index.mjs", + "require": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "directories": { + "lib": "src", + "test": "__tests__" + }, + "files": [ + "dist" + ], + "contributors": [ + "Vlad Frangu ", + "Crawl ", + "Amish Shah ", + "SpaceEEC ", + "Aura Román " + ], + "license": "Apache-2.0", + "keywords": [ + "discord", + "api", + "bot", + "client", + "node", + "discordapp", + "discordjs" + ], + "repository": { + "type": "git", + "url": "https://github.com/discordjs/discord.js.git" + }, + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" + }, + "homepage": "https://discord.js.org", + "dependencies": { + "@discordjs/formatters": "^0.2.0", + "@discordjs/util": "^0.2.0", + "@sapphire/shapeshift": "^3.8.1", + "discord-api-types": "^0.37.35", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.3", + "tslib": "^2.5.0" + }, + "devDependencies": { + "@favware/cliff-jumper": "^1.10.0", + "@microsoft/api-extractor": "^7.34.4", + "@types/node": "16.18.13", + "@vitest/coverage-c8": "^0.29.1", + "cross-env": "^7.0.3", + "downlevel-dts": "^0.11.0", + "esbuild-plugin-version-injector": "^1.0.3", + "eslint": "^8.35.0", + "eslint-config-neon": "^0.1.40", + "eslint-formatter-pretty": "^4.1.0", + "prettier": "^2.8.4", + "tsup": "^6.6.3", + "typescript": "^4.9.5", + "vitest": "^0.29.1" + }, + "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 new file mode 100644 index 0000000..afd6eef --- /dev/null +++ b/node_modules/@discordjs/collection/CHANGELOG.md @@ -0,0 +1,128 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@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 + +- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4)) + +## Features + +- Add `Collection#subtract()` (#8393) ([291f36c](https://github.com/discordjs/discord.js/commit/291f36cd736b5dea058145a1335bf7c78ec1d81d)) + +# [@discordjs/collection@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.1.0...@discordjs/collection@1.2.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)) +- Remove xml tag from collection#find (#8550) ([4032457](https://github.com/discordjs/discord.js/commit/40324574ebea9894cadcc967e0db0e4e21d62768)) + +## Features + +- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2)) + +## 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)) + +## Typings + +- **Collection:** Make fn return type unknown (#8676) ([822b7f2](https://github.com/discordjs/discord.js/commit/822b7f234af053c8f917b0a998b82abfccd33801)) + +# [@discordjs/collection@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.0.1...@discordjs/collection@1.1.0) - (2022-08-22) + +## Bug Fixes + +- Use proper format for `@link` text (#8384) ([2655639](https://github.com/discordjs/discord.js/commit/26556390a3800e954974a00c1328ff47d3e67e9a)) + +## Documentation + +- Fence examples in codeblocks ([193b252](https://github.com/discordjs/discord.js/commit/193b252672440a860318d3c2968aedd9cb88e0ce)) +- Use link tags (#8382) ([5494791](https://github.com/discordjs/discord.js/commit/549479131318c659f86f0eb18578d597e22522d3)) + +## Features + +- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007)) +- **website:** Show descriptions for `@typeParam` blocks (#8523) ([e475b63](https://github.com/discordjs/discord.js/commit/e475b63f257f6261d73cb89fee9ecbcdd84e2a6b)) + +## Refactor + +- **website:** Adjust typography (#8503) ([0f83402](https://github.com/discordjs/discord.js/commit/0f834029850d2448981596cf082ff59917018d66)) +- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e)) + +# [@discordjs/collection@0.8.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.7.0...@discordjs/collection@0.8.0) - (2022-07-17) + +## Bug Fixes + +- **Collection:** Make error messages consistent (#8224) ([5bd6b28](https://github.com/discordjs/discord.js/commit/5bd6b28b3ebfced1cb9d23e83bd7c0def7a12404)) +- Check for function type (#8064) ([3bb9c0e](https://github.com/discordjs/discord.js/commit/3bb9c0e5c37311044ff41761b572ac4f91cda57c)) + +## Documentation + +- Add codecov coverage badge to readmes (#8226) ([f6db285](https://github.com/discordjs/discord.js/commit/f6db285c073898a749fe4591cbd4463d1896daf5)) + +## Features + +- Codecov (#8219) ([f10f4cd](https://github.com/discordjs/discord.js/commit/f10f4cdcd88ca6be7ec735ed3a415ba13da83db0)) +- **docgen:** Update typedoc ([b3346f4](https://github.com/discordjs/discord.js/commit/b3346f4b9b3d4f96443506643d4631dc1c6d7b21)) +- Website (#8043) ([127931d](https://github.com/discordjs/discord.js/commit/127931d1df7a2a5c27923c2f2151dbf3824e50cc)) +- **docgen:** Typescript support ([3279b40](https://github.com/discordjs/discord.js/commit/3279b40912e6aa61507bedb7db15a2b8668de44b)) +- Docgen package (#8029) ([8b979c0](https://github.com/discordjs/discord.js/commit/8b979c0245c42fd824d8e98745ee869f5360fc86)) +- Use vitest instead of jest for more speed ([8d8e6c0](https://github.com/discordjs/discord.js/commit/8d8e6c03decd7352a2aa180f6e5bc1a13602539b)) +- Add scripts package for locally used scripts ([f2ae1f9](https://github.com/discordjs/discord.js/commit/f2ae1f9348bfd893332a9060f71a8a5f272a1b8b)) + +## Refactor + +- **collection:** Remove `default` property (#8055) ([c8f1690](https://github.com/discordjs/discord.js/commit/c8f1690896f55f06e05a83704262783cfc2bb91d)) +- **collection:** Remove default export (#8053) ([16810f3](https://github.com/discordjs/discord.js/commit/16810f3e410bf35ed7e6e7412d517ea74c792c5d)) +- Move all the config files to root (#8033) ([769ea0b](https://github.com/discordjs/discord.js/commit/769ea0bfe78c4f1d413c6b397c604ffe91e39c6a)) + +## Testing + +- **collection:** Improve coverage (#8222) ([a51f721](https://github.com/discordjs/discord.js/commit/a51f7215eca67a0f46fba8b2d706f7ec6f6dc228)) + +# [@discordjs/collection@0.7.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.6.0...@discordjs/collection@0.7.0) - (2022-06-04) + +## Styling + +- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629)) + +# [@discordjs/collection@0.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.5.0...@discordjs/collection@0.6.0) - (2022-04-17) + +## Features + +- Add support for module: NodeNext in TS and ESM (#7598) ([8f1986a](https://github.com/discordjs/discord.js/commit/8f1986a6aa98365e09b00e84ad5f9f354ab61f3d)) +- **builders:** Add attachment command option type (#7203) ([ae0f35f](https://github.com/discordjs/discord.js/commit/ae0f35f51d68dfa5a7dc43d161ef9365171debdb)) +- **Collection:** Add merging functions (#7299) ([e4bd07b](https://github.com/discordjs/discord.js/commit/e4bd07b2394f227ea06b72eb6999de9ab3127b25)) + +# [@discordjs/collection@0.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.4.0...@discordjs/collection@0.5.0) - (2022-01-24) + +## Refactor + +- Make `intersect` perform a true intersection (#7211) ([d8efba2](https://github.com/discordjs/discord.js/commit/d8efba24e09aa2a8dbf028fc57a561a56e7833fd)) + +## Typings + +- Add `ReadonlyCollection` (#7245) ([db25f52](https://github.com/discordjs/discord.js/commit/db25f529b26d7c819c1c42ad3e26c2263ea2da0e)) +- **Collection:** Union types on `intersect` and `difference` (#7196) ([1f9b922](https://github.com/discordjs/discord.js/commit/1f9b9225f2066e9cc66c3355417139fd25cc403c)) diff --git a/node_modules/@discordjs/collection/LICENSE b/node_modules/@discordjs/collection/LICENSE new file mode 100644 index 0000000..d21f37a --- /dev/null +++ b/node_modules/@discordjs/collection/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 2015 Amish Shah + + 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/collection/README.md b/node_modules/@discordjs/collection/README.md new file mode 100644 index 0000000..93c12e4 --- /dev/null +++ b/node_modules/@discordjs/collection/README.md @@ -0,0 +1,67 @@ +
+
+

+ discord.js +

+
+

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

+

+ Vercel +

+
+ +## About + +`@discordjs/collection` is a powerful utility data structure used in discord.js. + +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh-session +npm install @discordjs/collection +yarn add @discordjs/collection +pnpm add @discordjs/collection +``` + +## 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. +- [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/collection +[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/collection +[npm]: https://www.npmjs.com/package/@discordjs/collection +[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/collection/dist/index.d.ts b/node_modules/@discordjs/collection/dist/index.d.ts new file mode 100644 index 0000000..5d76b46 --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.d.ts @@ -0,0 +1,457 @@ +/** + * @internal + */ +interface CollectionConstructor { + new (): Collection; + new (entries?: readonly (readonly [K, V])[] | null): Collection; + new (iterable: Iterable): Collection; + readonly prototype: Collection; + readonly [Symbol.species]: CollectionConstructor; +} +/** + * Represents an immutable version of a collection + */ +type ReadonlyCollection = Omit, 'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'> & ReadonlyMap; +/** + * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself + * + * @internal + */ +interface Collection extends Map { + constructor: CollectionConstructor; +} +/** + * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has + * an ID, for significantly improved performance and ease-of-use. + * + * @typeParam K - The key type this collection holds + * @typeParam V - The value type this collection holds + */ +declare class Collection 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: K, defaultValueGenerator: (key: K, collection: this) => V): V; + /** + * 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: K[]): boolean; + /** + * 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: K[]): boolean; + /** + * Obtains the first value(s) in this collection. + * + * @param amount - Amount of values to obtain from the beginning + * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative + */ + first(): V | undefined; + first(amount: number): V[]; + /** + * Obtains the first key(s) in this collection. + * + * @param amount - Amount of keys to obtain from the beginning + * @returns A single key if no amount is provided or an array of keys, starting from the end if + * amount is negative + */ + firstKey(): K | undefined; + firstKey(amount: number): K[]; + /** + * Obtains the last value(s) in this collection. + * + * @param amount - Amount of values to obtain from the end + * @returns A single value if no amount is provided or an array of values, starting from the start if + * amount is negative + */ + last(): V | undefined; + last(amount: number): V[]; + /** + * Obtains the last key(s) in this collection. + * + * @param amount - Amount of keys to obtain from the end + * @returns A single key if no amount is provided or an array of keys, starting from the start if + * amount is negative + */ + lastKey(): K | undefined; + lastKey(amount: number): K[]; + /** + * 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: number): V | undefined; + /** + * 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: number): K | undefined; + /** + * Obtains unique random value(s) from this collection. + * + * @param amount - Amount of values to obtain randomly + * @returns A single value if no amount is provided or an array of values + */ + random(): V | undefined; + random(amount: number): V[]; + /** + * Obtains unique random key(s) from this collection. + * + * @param amount - Amount of keys to obtain randomly + * @returns A single key if no amount is provided or an array + */ + randomKey(): K | undefined; + randomKey(amount: number): K[]; + /** + * 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(): this; + /** + * Searches for a single item where the given function returns a truthy value. This behaves like + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}. + * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you + * should use the `get` method. See + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.find(user => user.username === 'Bob'); + * ``` + */ + find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined; + find(fn: (value: V, key: K, collection: this) => unknown): V | undefined; + find(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): V2 | undefined; + find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined; + /** + * Searches for the key of a single item where the given function returns a truthy value. This behaves like + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()}, + * but returns the key rather than the positional index. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.findKey(user => user.username === 'Bob'); + * ``` + */ + findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined; + findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined; + findKey(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): K2 | undefined; + findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined; + /** + * Removes items that satisfy the provided filter function. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @returns The number of removed entries + */ + sweep(fn: (value: V, key: K, collection: this) => unknown): number; + sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number; + /** + * Identical to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()}, + * but returns a Collection instead of an Array. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.filter(user => user.username === 'Bob'); + * ``` + */ + filter(fn: (value: V, key: K, collection: this) => key is K2): Collection; + filter(fn: (value: V, key: K, collection: this) => value is V2): Collection; + filter(fn: (value: V, key: K, collection: this) => unknown): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection; + /** + * Partitions the collection into two collections where the first collection + * contains the items that passed and the second contains the items that failed. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * const [big, small] = collection.partition(guild => guild.memberCount > 250); + * ``` + */ + partition(fn: (value: V, key: K, collection: this) => key is K2): [Collection, Collection, V>]; + partition(fn: (value: V, key: K, collection: this) => value is V2): [Collection, Collection>]; + partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection]; + partition(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): [Collection, Collection, V>]; + partition(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): [Collection, Collection>]; + partition(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): [Collection, Collection]; + /** + * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}. + * + * @param fn - Function that produces a new Collection + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.flatMap(guild => guild.members.cache); + * ``` + */ + flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection; + flatMap(fn: (this: This, value: V, key: K, collection: this) => Collection, thisArg: This): Collection; + /** + * Maps each item to another value into an array. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}. + * + * @param fn - Function that produces an element of the new array, taking three arguments + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.map(user => user.tag); + * ``` + */ + map(fn: (value: V, key: K, collection: this) => T): T[]; + map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[]; + /** + * Maps each item to another value into a collection. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}. + * + * @param fn - Function that produces an element of the new collection, taking three arguments + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.mapValues(user => user.tag); + * ``` + */ + mapValues(fn: (value: V, key: K, collection: this) => T): Collection; + mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection; + /** + * Checks if there exists an item that passes a test. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.some(user => user.discriminator === '0000'); + * ``` + */ + some(fn: (value: V, key: K, collection: this) => unknown): boolean; + some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean; + /** + * Checks if all items passes a test. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.every(user => !user.bot); + * ``` + */ + every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection; + every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection; + every(fn: (value: V, key: K, collection: this) => unknown): boolean; + every(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): this is Collection; + every(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): this is Collection; + every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean; + /** + * 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: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T; + /** + * Identical to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()}, + * but returns the collection instead of undefined. + * + * @param fn - Function to execute for each element + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection + * .each(user => console.log(user.username)) + * .filter(user => user.bot) + * .each(user => console.log(user.username)); + * ``` + */ + each(fn: (value: V, key: K, collection: this) => void): this; + each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this; + /** + * Runs a function on the collection and returns the collection. + * + * @param fn - Function to execute + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection + * .tap(coll => console.log(coll.size)) + * .filter(user => user.bot) + * .tap(coll => console.log(coll.size)) + * ``` + */ + tap(fn: (collection: this) => void): this; + tap(fn: (this: T, collection: this) => void, thisArg: T): this; + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ + clone(): Collection; + /** + * 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: ReadonlyCollection[]): Collection; + /** + * 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: ReadonlyCollection): boolean; + /** + * 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?: Comparator): 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: ReadonlyCollection): Collection; + /** + * 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: ReadonlyCollection): Collection; + /** + * 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: ReadonlyCollection): Collection; + /** + * 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: ReadonlyCollection, whenInSelf: (value: V, key: K) => Keep, whenInOther: (valueOther: T, key: K) => Keep, whenInBoth: (value: V, valueOther: T, key: K) => Keep): Collection; + /** + * 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?: Comparator): Collection; + toJSON(): V[]; + private static defaultSort; + /** + * 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: Iterable<[K, V]>, combine: (firstValue: V, secondValue: V, key: K) => V): Collection; +} +/** + * @internal + */ +type Keep = { + keep: false; +} | { + keep: true; + value: V; +}; +/** + * @internal + */ +type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number; + +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version + * that you are currently using. + */ +declare const version: string; + +export { Collection, CollectionConstructor, Comparator, Keep, ReadonlyCollection, version }; diff --git a/node_modules/@discordjs/collection/dist/index.js b/node_modules/@discordjs/collection/dist/index.js new file mode 100644 index 0000000..55b1b5a --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.js @@ -0,0 +1,569 @@ +"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, { + Collection: () => Collection, + version: () => version +}); +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); + if (typeof defaultValueGenerator !== "function") + throw new TypeError(`${defaultValueGenerator} is not a function`); + const defaultValue = defaultValueGenerator(key, this); + 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)); + } + /** + * 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)); + } + first(amount) { + if (amount === void 0) + return this.values().next().value; + if (amount < 0) + return this.last(amount * -1); + amount = Math.min(this.size, amount); + const iter = this.values(); + return Array.from({ + length: amount + }, () => iter.next().value); + } + firstKey(amount) { + if (amount === void 0) + return this.keys().next().value; + if (amount < 0) + return this.lastKey(amount * -1); + amount = Math.min(this.size, amount); + const iter = this.keys(); + return Array.from({ + length: amount + }, () => iter.next().value); + } + last(amount) { + const arr = [ + ...this.values() + ]; + if (amount === void 0) + return arr[arr.length - 1]; + if (amount < 0) + return this.first(amount * -1); + if (!amount) + return []; + return arr.slice(-amount); + } + lastKey(amount) { + const arr = [ + ...this.keys() + ]; + if (amount === void 0) + return arr[arr.length - 1]; + if (amount < 0) + return this.firstKey(amount * -1); + if (!amount) + 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() + ]; + return arr.at(index); + } + random(amount) { + const arr = [ + ...this.values() + ]; + if (amount === void 0) + return arr[Math.floor(Math.random() * arr.length)]; + if (!arr.length || !amount) + return []; + return Array.from({ + length: Math.min(amount, arr.length) + }, () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]); + } + randomKey(amount) { + const arr = [ + ...this.keys() + ]; + if (amount === void 0) + return arr[Math.floor(Math.random() * arr.length)]; + if (!arr.length || !amount) + return []; + return Array.from({ + length: Math.min(amount, arr.length) + }, () => 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(); + for (const [key, value] of entries) + this.set(key, value); + return this; + } + find(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return val; + } + return void 0; + } + findKey(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return key; + } + return void 0; + } + sweep(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const previousSize = this.size; + for (const [key, val] of this) { + if (fn(val, key, this)) + this.delete(key); + } + return previousSize - this.size; + } + filter(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const results = new this.constructor[Symbol.species](); + for (const [key, val] of this) { + if (fn(val, key, this)) + results.set(key, val); + } + return results; + } + partition(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const results = [ + new this.constructor[Symbol.species](), + new this.constructor[Symbol.species]() + ]; + for (const [key, val] of this) { + if (fn(val, key, this)) { + results[0].set(key, val); + } else { + results[1].set(key, val); + } + } + return results; + } + flatMap(fn, thisArg) { + const collections = this.map(fn, thisArg); + return new this.constructor[Symbol.species]().concat(...collections); + } + map(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const iter = this.entries(); + return Array.from({ + length: this.size + }, () => { + const [key, value] = iter.next().value; + return fn(value, key, this); + }); + } + mapValues(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const coll = new this.constructor[Symbol.species](); + for (const [key, val] of this) + coll.set(key, fn(val, key, this)); + return coll; + } + some(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return true; + } + return false; + } + every(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (!fn(val, key, this)) + return false; + } + 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 (initialValue !== void 0) { + accumulator = initialValue; + for (const [key, val] of this) + accumulator = fn(accumulator, val, key, this); + return accumulator; + } + let first = true; + for (const [key, val] of this) { + if (first) { + accumulator = val; + first = false; + continue; + } + accumulator = fn(accumulator, val, key, this); + } + if (first) { + throw new TypeError("Reduce of empty collection with no initial value"); + } + return accumulator; + } + each(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + this.forEach(fn, thisArg); + return this; + } + tap(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + 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) { + for (const [key, val] of coll) + newColl.set(key, val); + } + 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; + if (this === collection) + return true; + if (this.size !== collection.size) + return false; + for (const [key, value] of this) { + if (!collection.has(key) || value !== collection.get(key)) { + return false; + } + } + 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); + } + 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); + } + } + 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); + } + } + 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 [k, v] of this) { + if (!other.has(k)) + coll.set(k, v); + } + 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); + if (hasInSelf && hasInOther) { + const r = whenInBoth(this.get(k), other.get(k), k); + if (r.keep) + coll.set(k, r.value); + } else if (hasInSelf) { + const r = whenInSelf(this.get(k), k); + if (r.keep) + coll.set(k, r.value); + } else if (hasInOther) { + const r = whenInOther(other.get(k), k); + if (r.keep) + coll.set(k, r.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)); + } + toJSON() { + return [ + ...this.values() + ]; + } + 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)); + } else { + coll.set(k, v); + } + } + return coll; + } +}; +__name(Collection, "Collection"); + +// src/index.ts +var version = "[VI]{{inject}}[/VI]"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Collection, + version +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/collection/dist/index.js.map b/node_modules/@discordjs/collection/dist/index.js.map new file mode 100644 index 0000000..26bf888 --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.js.map @@ -0,0 +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\nexport const version = '[VI]{{inject}}[/VI]' as string;\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 (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\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 (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;;;;;;;;ACsCO,IAAMA,aAAN,cAA+BC,IAAAA;;;;;;;;;;;EAW9BC,OAAOC,KAAQC,uBAA2D;AAChF,QAAI,KAAKC,IAAIF,GAAAA;AAAM,aAAO,KAAKG,IAAIH,GAAAA;AACnC,QAAI,OAAOC,0BAA0B;AAAY,YAAM,IAAIG,UAAU,GAAGH,yCAAyC;AACjH,UAAMI,eAAeJ,sBAAsBD,KAAK,IAAI;AACpD,SAAKM,IAAIN,KAAKK,YAAAA;AACd,WAAOA;EACR;;;;;;;EAQOE,UAAUC,MAAW;AAC3B,WAAOA,KAAKC,MAAM,CAACC,MAAM,MAAMR,IAAIQ,CAAAA,CAAAA;EACpC;;;;;;;EAQOC,UAAUH,MAAW;AAC3B,WAAOA,KAAKI,KAAK,CAACF,MAAM,MAAMR,IAAIQ,CAAAA,CAAAA;EACnC;EAUOG,MAAMC,QAAsC;AAClD,QAAIA,WAAWC;AAAW,aAAO,KAAKC,OAAM,EAAGC,KAAI,EAAGC;AACtD,QAAIJ,SAAS;A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SACAgE,SACmB;AACnB,UAAM1C,OAAO,IAAIhE,WAAAA;AACjB,eAAW,CAACa,GAAGmE,CAAAA,KAAMtC,SAAS;AAC7B,UAAIsB,KAAK3D,IAAIQ,CAAAA,GAAI;AAChBmD,aAAKvD,IAAII,GAAG6F,QAAQ1C,KAAK1D,IAAIO,CAAAA,GAAKmE,GAAGnE,CAAAA,CAAAA;MACtC,OAAO;AACNmD,aAAKvD,IAAII,GAAGmE,CAAAA;MACb;IACD;AAEA,WAAOhB;EACR;AACD;AArxBahE;;;AD/BN,IAAM2G,UAAU;","names":["Collection","Map","ensure","key","defaultValueGenerator","has","get","TypeError","defaultValue","set","hasAll","keys","every","k","hasAny","some","first","amount","undefined","values","next","value","last","Math","min","size","iter","Array","from","length","firstKey","lastKey","arr","slice","at","index","floor","keyAt","random","splice","randomKey","reverse","entries","clear","find","fn","thisArg","bind","val","findKey","sweep","previousSize","delete","filter","results","constructor","Symbol","species","partition","flatMap","collections","map","concat","mapValues","coll","reduce","initialValue","accumulator","each","forEach","tap","clone","newColl","equals","collection","sort","compareFunction","defaultSort","a","b","v","intersect","other","Object","is","subtract","difference","merge","whenInSelf","whenInOther","whenInBoth","Set","hasInSelf","hasInOther","r","keep","sorted","av","bv","ak","bk","toJSON","firstValue","secondValue","Number","combineEntries","combine","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/dist/index.mjs b/node_modules/@discordjs/collection/dist/index.mjs new file mode 100644 index 0000000..72aa3e8 --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.mjs @@ -0,0 +1,543 @@ +var __defProp = Object.defineProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + +// 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); + if (typeof defaultValueGenerator !== "function") + throw new TypeError(`${defaultValueGenerator} is not a function`); + const defaultValue = defaultValueGenerator(key, this); + 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)); + } + /** + * 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)); + } + first(amount) { + if (amount === void 0) + return this.values().next().value; + if (amount < 0) + return this.last(amount * -1); + amount = Math.min(this.size, amount); + const iter = this.values(); + return Array.from({ + length: amount + }, () => iter.next().value); + } + firstKey(amount) { + if (amount === void 0) + return this.keys().next().value; + if (amount < 0) + return this.lastKey(amount * -1); + amount = Math.min(this.size, amount); + const iter = this.keys(); + return Array.from({ + length: amount + }, () => iter.next().value); + } + last(amount) { + const arr = [ + ...this.values() + ]; + if (amount === void 0) + return arr[arr.length - 1]; + if (amount < 0) + return this.first(amount * -1); + if (!amount) + return []; + return arr.slice(-amount); + } + lastKey(amount) { + const arr = [ + ...this.keys() + ]; + if (amount === void 0) + return arr[arr.length - 1]; + if (amount < 0) + return this.firstKey(amount * -1); + if (!amount) + 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() + ]; + return arr.at(index); + } + random(amount) { + const arr = [ + ...this.values() + ]; + if (amount === void 0) + return arr[Math.floor(Math.random() * arr.length)]; + if (!arr.length || !amount) + return []; + return Array.from({ + length: Math.min(amount, arr.length) + }, () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]); + } + randomKey(amount) { + const arr = [ + ...this.keys() + ]; + if (amount === void 0) + return arr[Math.floor(Math.random() * arr.length)]; + if (!arr.length || !amount) + return []; + return Array.from({ + length: Math.min(amount, arr.length) + }, () => 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(); + for (const [key, value] of entries) + this.set(key, value); + return this; + } + find(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return val; + } + return void 0; + } + findKey(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return key; + } + return void 0; + } + sweep(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const previousSize = this.size; + for (const [key, val] of this) { + if (fn(val, key, this)) + this.delete(key); + } + return previousSize - this.size; + } + filter(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const results = new this.constructor[Symbol.species](); + for (const [key, val] of this) { + if (fn(val, key, this)) + results.set(key, val); + } + return results; + } + partition(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const results = [ + new this.constructor[Symbol.species](), + new this.constructor[Symbol.species]() + ]; + for (const [key, val] of this) { + if (fn(val, key, this)) { + results[0].set(key, val); + } else { + results[1].set(key, val); + } + } + return results; + } + flatMap(fn, thisArg) { + const collections = this.map(fn, thisArg); + return new this.constructor[Symbol.species]().concat(...collections); + } + map(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const iter = this.entries(); + return Array.from({ + length: this.size + }, () => { + const [key, value] = iter.next().value; + return fn(value, key, this); + }); + } + mapValues(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const coll = new this.constructor[Symbol.species](); + for (const [key, val] of this) + coll.set(key, fn(val, key, this)); + return coll; + } + some(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return true; + } + return false; + } + every(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (!fn(val, key, this)) + return false; + } + 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 (initialValue !== void 0) { + accumulator = initialValue; + for (const [key, val] of this) + accumulator = fn(accumulator, val, key, this); + return accumulator; + } + let first = true; + for (const [key, val] of this) { + if (first) { + accumulator = val; + first = false; + continue; + } + accumulator = fn(accumulator, val, key, this); + } + if (first) { + throw new TypeError("Reduce of empty collection with no initial value"); + } + return accumulator; + } + each(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + this.forEach(fn, thisArg); + return this; + } + tap(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + 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) { + for (const [key, val] of coll) + newColl.set(key, val); + } + 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; + if (this === collection) + return true; + if (this.size !== collection.size) + return false; + for (const [key, value] of this) { + if (!collection.has(key) || value !== collection.get(key)) { + return false; + } + } + 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); + } + 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); + } + } + 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); + } + } + 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 [k, v] of this) { + if (!other.has(k)) + coll.set(k, v); + } + 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); + if (hasInSelf && hasInOther) { + const r = whenInBoth(this.get(k), other.get(k), k); + if (r.keep) + coll.set(k, r.value); + } else if (hasInSelf) { + const r = whenInSelf(this.get(k), k); + if (r.keep) + coll.set(k, r.value); + } else if (hasInOther) { + const r = whenInOther(other.get(k), k); + if (r.keep) + coll.set(k, r.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)); + } + toJSON() { + return [ + ...this.values() + ]; + } + 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)); + } else { + coll.set(k, v); + } + } + return coll; + } +}; +__name(Collection, "Collection"); + +// src/index.ts +var version = "[VI]{{inject}}[/VI]"; +export { + Collection, + version +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/collection/dist/index.mjs.map b/node_modules/@discordjs/collection/dist/index.mjs.map new file mode 100644 index 0000000..15bf719 --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.mjs.map @@ -0,0 +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 (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\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 (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 typ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IO,CAAAA,GAAKA,CAAAA;AACnC,YAAIiF,EAAEC;AAAM/B,eAAKvD,IAAII,GAAGiF,EAAEzE,KAAK;MAChC,WAAWwE,YAAY;AACtB,cAAMC,IAAIL,YAAYP,MAAM5E,IAAIO,CAAAA,GAAKA,CAAAA;AACrC,YAAIiF,EAAEC;AAAM/B,eAAKvD,IAAII,GAAGiF,EAAEzE,KAAK;MAChC;IACD;AAEA,WAAO2C;EACR;;;;;;;;;;;;;;EAeOgC,OAAOpB,kBAAoC5E,WAAW6E,aAAa;AACzE,WAAO,IAAI,KAAKtB,YAAYC,OAAOC,OAAO,EAAE,IAAI,EAAEkB,KAAK,CAACsB,IAAIC,IAAIC,IAAIC,OAAOxB,gBAAgBqB,IAAIC,IAAIC,IAAIC,EAAAA,CAAAA;EACxG;EAEOC,SAAS;AAEf,WAAO;SAAI,KAAKlF,OAAM;;EACvB;EAEA,OAAe0D,YAAeyB,YAAeC,aAAwB;AACpE,WAAOC,OAAOF,aAAaC,WAAAA,KAAgBC,OAAOF,eAAeC,WAAAA,IAAe;EACjF;;;;;;;;;;;;EAaA,OAAcE,eACb/D,SACAgE,SACmB;AACnB,UAAM1C,OAAO,IAAIhE,WAAAA;AACjB,eAAW,CAACa,GAAGmE,CAAAA,KAAMtC,SAAS;AAC7B,UAAIsB,KAAK3D,IAAIQ,CAAAA,GAAI;AAChBmD,aAAKvD,IAAII,GAAG6F,QAAQ1C,KAAK1D,IAAIO,CAAAA,GAAKmE,GAAGnE,CAAAA,CAAAA;MACtC,OAAO;AACNmD,aAAKvD,IAAII,GAAGmE,CAAAA;MACb;IACD;AAEA,WAAOhB;EACR;AACD;AArxBahE;;;AC/BN,IAAM2G,UAAU;","names":["Collection","Map","ensure","key","defaultValueGenerator","has","get","TypeError","defaultValue","set","hasAll","keys","every","k","hasAny","some","first","amount","undefined","values","next","value","last","Math","min","size","iter","Array","from","length","firstKey","lastKey","arr","slice","at","index","floor","keyAt","random","splice","randomKey","reverse","entries","clear","find","fn","thisArg","bind","val","findKey","sweep","previousSize","delete","filter","results","constructor","Symbol","species","partition","flatMap","collections","map","concat","mapValues","coll","reduce","initialValue","accumulator","each","forEach","tap","clone","newColl","equals","collection","sort","compareFunction","defaultSort","a","b","v","intersect","other","Object","is","subtract","difference","merge","whenInSelf","whenInOther","whenInBoth","Set","hasInSelf","hasInOther","r","keep","sorted","av","bv","ak","bk","toJSON","firstValue","secondValue","Number","combineEntries","combine","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/package.json b/node_modules/@discordjs/collection/package.json new file mode 100644 index 0000000..451c6bd --- /dev/null +++ b/node_modules/@discordjs/collection/package.json @@ -0,0 +1,74 @@ +{ + "name": "@discordjs/collection", + "version": "1.4.0", + "description": "Utility data structure used in discord.js", + "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", + "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": { + "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 ", + "Aura Román " + ], + "license": "Apache-2.0", + "keywords": [ + "map", + "collection", + "utility" + ], + "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", + "devDependencies": { + "@favware/cliff-jumper": "^1.10.0", + "@microsoft/api-extractor": "^7.34.4", + "@types/node": "16.18.13", + "@vitest/coverage-c8": "^0.29.1", + "cross-env": "^7.0.3", + "esbuild-plugin-version-injector": "^1.0.3", + "eslint": "^8.35.0", + "eslint-config-neon": "^0.1.40", + "eslint-formatter-pretty": "^4.1.0", + "prettier": "^2.8.4", + "tsup": "^6.6.3", + "typescript": "^4.9.5", + "vitest": "^0.29.1" + }, + "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..28793b0 --- /dev/null +++ b/node_modules/@discordjs/formatters/CHANGELOG.md @@ -0,0 +1,25 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@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..418d1da --- /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` set of functions to format strings for Discord. + +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh-session +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]) + See also the [Update Guide][guide-update], including updated and removed items in 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/ +[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..ac59fa3 --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.d.ts @@ -0,0 +1,444 @@ +import { URL } from 'node:url'; +import { Snowflake } from 'discord-api-types/globals'; + +interface EscapeMarkdownOptions { + /** + * Whether to escape bolds + * + * @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 escape characters + * + * @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-flavour 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 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)" +} + +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..58b2df2 --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.js @@ -0,0 +1,379 @@ +"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, e.g. 16:20 + */ + ShortTime: "t", + /** + * Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30 + */ + LongTime: "T", + /** + * Short date format, consisting of day, month, and year, e.g. 20/04/2021 + */ + ShortDate: "d", + /** + * Long date format, consisting of day, month, and year, e.g. 20 April 2021 + */ + LongDate: "D", + /** + * Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20 + */ + ShortDateTime: "f", + /** + * Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20 + */ + LongDateTime: "F", + /** + * Relative time format, consisting of a relative duration format, e.g. 2 months ago + */ + RelativeTime: "R" +}; +var Faces; +(function(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)"; +})(Faces || (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..847a228 --- /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\nexport interface EscapeMarkdownOptions {\n\t/**\n\t * Whether to escape bolds\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 escape characters\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-flavour 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 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 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 (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 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 `${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 satisfies Record;\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC2GO,SAASA,eAAeC,MAAcC,UAAiC,CAAC,GAAW;AACzF,QAAM,EACLC,WAAAA,aAAY,MACZC,YAAAA,cAAa,MACbC,MAAAA,QAAO,MACPC,QAAAA,UAAS,MACTC,YAAY,MACZC,eAAAA,iBAAgB,MAChBC,SAAAA,WAAU,MACVC,mBAAmB,MACnBC,oBAAoB,MACpBC,SAAS,MACTC,UAAU,OACVC,eAAe,OACfC,eAAe,OACfC,aAAa,MAAK,IACfd;AAEJ,MAAI,CAACQ,kBAAkB;AACtB,WAAOT,KACLgB,MAAM,KAAA,EACNC,IAAI,CAACC,WAAWC,OAAOC,UAAU;AACjC,UAAID,QAAQ,KAAKA,UAAUC,MAAMC,SAAS;AAAG,eAAOH;AACpD,aAAOnB,eAAemB,WAAW;QAChCf,YAAAA;QACAC,MAAAA;QACAC,QAAAA;QACAC;QACAC,eAAAA;QACAC,SAAAA;QACAE;QACAC;QACAC;QACAC;QACAC;QACAC;MACD,CAAA;IACD,CAAA,EACCO,KAAKpB,aAAY,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O,KAAKoB,eAAeC,uBAAuBC;EACnD;AAEA,SAAO,KAAKF,eAAeC;AAC5B;AApBgBF;AAmDT,SAASK,YAAiCC,SAAYC,WAAW,OAAmC;AAC1G,SAAO,IAAIA,WAAW,MAAM,QAAQD;AACrC;AAFgBD;AAsBT,SAASG,YACfX,WACAY,SACqF;AACrF,SAAO,gCAAgCA,WAAW,SAASZ;AAC5D;AALgBW;AA+BT,SAASE,YACfb,WACAc,WACAF,SAC+F;AAC/F,SAAO,GAAGA,YAAY5B,SAAY2B,YAAYX,SAAAA,IAAaW,YAAYX,WAAWY,OAAAA,KAAYE;AAC/F;AANgBD;AAqCT,SAASE,KAAKC,eAA+BC,OAAuC;AAC1F,MAAI,OAAOD,kBAAkB,UAAU;AAEtCA,oBAAgBE,KAAKC,OAAOH,eAAeI,QAAAA,KAAaC,KAAKC,IAAG,KAAM,GAAA;EACvE;AAEA,SAAO,OAAOL,UAAU,WAAW,MAAMD,iBAAiBC,WAAW,MAAMD;AAC5E;AAPgBD;AAYT,IAAMQ,kBAAkB;;;;EAI9BC,WAAW;;;;EAKXC,UAAU;;;;EAKVC,WAAW;;;;EAKXC,UAAU;;;;EAKVC,eAAe;;;;EAKfC,cAAc;;;;EAKdC,cAAc;AACf;IAUO;UAAKC,QAAK;AAALA,EAAAA;;;;IAIXC;EAAAA,IAAQ;AAJGD,EAAAA;;;;IASXE;EAAAA,IAAY;AATDF,EAAAA;;;;IAcXG;EAAAA,IAAS;GAdEH,UAAAA,QAAAA,CAAAA,EAAAA;","names":["escapeMarkdown","text","options","codeBlock","inlineCode","bold","italic","underline","strikethrough","spoiler","codeBlockContent","inlineCodeContent","escape","heading","bulletedList","numberedList","maskedLink","split","map","subString","index","array","length","join","res","escapeEscape","escapeInlineCode","escapeCodeBlock","escapeItalic","escapeBold","escapeUnderline","escapeStrikethrough","escapeSpoiler","escapeHeading","escapeBulletedList","escapeNumberedList","escapeMaskedLink","replaceAll","match","idx","newText","_","codeBlock","language","content","undefined","inlineCode","italic","bold","underscore","strikethrough","quote","blockQuote","hideLinkEmbed","url","hyperlink","title","spoiler","userMention","userId","channelMention","channelId","roleMention","roleId","chatInputApplicationCommandMention","commandName","subcommandGroupName","subcommandName","commandId","formatEmoji","emojiId","animated","channelLink","guildId","messageLink","messageId","time","timeOrSeconds","style","Math","floor","getTime","Date","now","TimestampStyles","ShortTime","LongTime","ShortDate","LongDate","ShortDateTime","LongDateTime","RelativeTime","Faces","Shrug","Tableflip","Unflip"]} \ 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..6c4b9eb --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.mjs @@ -0,0 +1,321 @@ +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, e.g. 16:20 + */ + ShortTime: "t", + /** + * Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30 + */ + LongTime: "T", + /** + * Short date format, consisting of day, month, and year, e.g. 20/04/2021 + */ + ShortDate: "d", + /** + * Long date format, consisting of day, month, and year, e.g. 20 April 2021 + */ + LongDate: "D", + /** + * Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20 + */ + ShortDateTime: "f", + /** + * Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20 + */ + LongDateTime: "F", + /** + * Relative time format, consisting of a relative duration format, e.g. 2 months ago + */ + RelativeTime: "R" +}; +var Faces; +(function(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)"; +})(Faces || (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..8f795b4 --- /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\nexport interface EscapeMarkdownOptions {\n\t/**\n\t * Whether to escape bolds\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 escape characters\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-flavour 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 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 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 (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 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 `${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 satisfies Record;\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"],"mappings":";;;;AA2GO,SAASA,eAAeC,MAAcC,UAAiC,CAAC,GAAW;AACzF,QAAM,EACLC,WAAAA,aAAY,MACZC,YAAAA,cAAa,MACbC,MAAAA,QAAO,MACPC,QAAAA,UAAS,MACTC,YAAY,MACZC,eAAAA,iBAAgB,MAChBC,SAAAA,WAAU,MACVC,mBAAmB,MACnBC,oBAAoB,MACpBC,SAAS,MACTC,UAAU,OACVC,eAAe,OACfC,eAAe,OACfC,aAAa,MAAK,IACfd;AAEJ,MAAI,CAACQ,kBAAkB;AACtB,WAAOT,KACLgB,MAAM,KAAA,EACNC,IAAI,CAACC,WAAWC,OAAOC,UAAU;AACjC,UAAID,QAAQ,KAAKA,UAAUC,MAAMC,SAAS;AAAG,eAAOH;AACpD,aAAOnB,eAAemB,WAAW;QAChCf,YAAAA;QACAC,MAAAA;QACAC,QAAAA;QACAC;QACAC,eAAAA;QACAC,SAAAA;QACAE;QACAC;QACAC;QAC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BC,kBAAmBC;EACtE;AAEA,MAAID,mBAAmBtB,QAAW;AACjC,WAAO,KAAKoB,eAAeC,uBAAuBC;EACnD;AAEA,SAAO,KAAKF,eAAeC;AAC5B;AApBgBF;AAmDT,SAASK,YAAiCC,SAAYC,WAAW,OAAmC;AAC1G,SAAO,IAAIA,WAAW,MAAM,QAAQD;AACrC;AAFgBD;AAsBT,SAASG,YACfX,WACAY,SACqF;AACrF,SAAO,gCAAgCA,WAAW,SAASZ;AAC5D;AALgBW;AA+BT,SAASE,YACfb,WACAc,WACAF,SAC+F;AAC/F,SAAO,GAAGA,YAAY5B,SAAY2B,YAAYX,SAAAA,IAAaW,YAAYX,WAAWY,OAAAA,KAAYE;AAC/F;AANgBD;AAqCT,SAASE,KAAKC,eAA+BC,OAAuC;AAC1F,MAAI,OAAOD,kBAAkB,UAAU;AAEtCA,oBAAgBE,KAAKC,OAAOH,eAAeI,QAAAA,KAAaC,KAAKC,IAAG,KAAM,GAAA;EACvE;AAEA,SAAO,OAAOL,UAAU,WAAW,MAAMD,iBAAiBC,WAAW,MAAMD;AAC5E;AAPgBD;AAYT,IAAMQ,kBAAkB;;;;EAI9BC,WAAW;;;;EAKXC,UAAU;;;;EAKVC,WAAW;;;;EAKXC,UAAU;;;;EAKVC,eAAe;;;;EAKfC,cAAc;;;;EAKdC,cAAc;AACf;IAUO;UAAKC,QAAK;AAALA,EAAAA;;;;IAIXC;EAAAA,IAAQ;AAJGD,EAAAA;;;;IASXE;EAAAA,IAAY;AATDF,EAAAA;;;;IAcXG;EAAAA,IAAS;GAdEH,UAAAA,QAAAA,CAAAA,EAAAA;","names":["escapeMarkdown","text","options","codeBlock","inlineCode","bold","italic","underline","strikethrough","spoiler","codeBlockContent","inlineCodeContent","escape","heading","bulletedList","numberedList","maskedLink","split","map","subString","index","array","length","join","res","escapeEscape","escapeInlineCode","escapeCodeBlock","escapeItalic","escapeBold","escapeUnderline","escapeStrikethrough","escapeSpoiler","escapeHeading","escapeBulletedList","escapeNumberedList","escapeMaskedLink","replaceAll","match","idx","newText","_","codeBlock","language","content","undefined","inlineCode","italic","bold","underscore","strikethrough","quote","blockQuote","hideLinkEmbed","url","hyperlink","title","spoiler","userMention","userId","channelMention","channelId","roleMention","roleId","chatInputApplicationCommandMention","commandName","subcommandGroupName","subcommandName","commandId","formatEmoji","emojiId","animated","channelLink","guildId","messageLink","messageId","time","timeOrSeconds","style","Math","floor","getTime","Date","now","TimestampStyles","ShortTime","LongTime","ShortDate","LongDate","ShortDateTime","LongDateTime","RelativeTime","Faces","Shrug","Tableflip","Unflip"]} \ 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..80dc328 --- /dev/null +++ b/node_modules/@discordjs/formatters/package.json @@ -0,0 +1,70 @@ +{ + "name": "@discordjs/formatters", + "version": "0.2.0", + "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", + "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": { + "import": "./dist/index.mjs", + "require": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "directories": { + "lib": "src", + "test": "__tests__" + }, + "files": [ + "dist" + ], + "contributors": [ + "Crawl ", + "SpaceEEC ", + "Vlad Frangu ", + "Aura Román " + ], + "license": "Apache-2.0", + "keywords": [], + "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": { + "discord-api-types": "^0.37.35" + }, + "devDependencies": { + "@favware/cliff-jumper": "^1.10.0", + "@microsoft/api-extractor": "^7.34.4", + "@types/node": "16.18.13", + "@vitest/coverage-c8": "^0.29.1", + "cross-env": "^7.0.3", + "eslint": "^8.35.0", + "eslint-config-neon": "^0.1.40", + "eslint-formatter-pretty": "^4.1.0", + "prettier": "^2.8.4", + "tsup": "^6.6.3", + "typescript": "^4.9.5", + "vitest": "^0.29.1" + }, + "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 new file mode 100644 index 0000000..174742e --- /dev/null +++ b/node_modules/@discordjs/rest/CHANGELOG.md @@ -0,0 +1,185 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@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 + +- **core:** Add support for role connections (#8930) ([3d6fa24](https://github.com/discordjs/discord.js/commit/3d6fa248c07b2278504bbe8bafa17a3294971fd9)) + +# [@discordjs/rest@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.3.0...@discordjs/rest@1.4.0) - (2022-11-28) + +## Bug Fixes + +- **SequentialHandler:** Downlevel ECONNRESET errors (#8785) ([5a70057](https://github.com/discordjs/discord.js/commit/5a70057826b47fb8251f3d836a536de689444ca1)) +- Make ratelimit timeout require event loop to be active (#8779) ([68d5712](https://github.com/discordjs/discord.js/commit/68d5712deae85532604d93b4505f0953d664cde7)) +- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4)) + +## Features + +- Add `@discordjs/core` (#8736) ([2127b32](https://github.com/discordjs/discord.js/commit/2127b32d26dedeb44ec43d16ec2e2046919f9bb0)) +- New select menus (#8793) ([5152abf](https://github.com/discordjs/discord.js/commit/5152abf7285581abf7689e9050fdc56c4abb1e2b)) + +## Refactor + +- Update `makeURLSearchParams` to accept readonly non-`Record`s (#8868) ([8376e2d](https://github.com/discordjs/discord.js/commit/8376e2dbcd38697ce62615d9a539fd198fbc4713)) + +# [@discordjs/rest@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.2.0...@discordjs/rest@1.3.0) - (2022-10-08) + +## Bug Fixes + +- **SequentialHandler:** Throw http error with proper name and more useful message (#8694) ([3f86561](https://github.com/discordjs/discord.js/commit/3f8656115bf9df0dbf8391de68a3401535325895)) + +## Features + +- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2)) +- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3)) +- Add `AbortSignal` support (#8672) ([3c231ae](https://github.com/discordjs/discord.js/commit/3c231ae81a52b66940ba495f35fd59a76c65e306)) + +# [@discordjs/rest@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.1.0...@discordjs/rest@1.2.0) - (2022-09-25) + +## 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 + +- **rest:** Use Agent with higher connect timeout (#8679) ([64cd53c](https://github.com/discordjs/discord.js/commit/64cd53c4c23dd9c9503fd0887ac5c542137c57e8)) + +## 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)) + +# [@discordjs/rest@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.0.1...@discordjs/rest@1.1.0) - (2022-08-22) + +## Features + +- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007)) +- **website:** Render `@defaultValue` blocks (#8527) ([8028813](https://github.com/discordjs/discord.js/commit/8028813825e7708915ea892760c1003afd60df2f)) +- **WebSocketShard:** Support new resume url (#8480) ([bc06cc6](https://github.com/discordjs/discord.js/commit/bc06cc638d2f57ab5c600e8cdb6afc8eb2180166)) + +## Refactor + +- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e)) + +# [@discordjs/rest@0.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.5.0...@discordjs/rest@0.6.0) - (2022-07-17) + +## Documentation + +- Add codecov coverage badge to readmes (#8226) ([f6db285](https://github.com/discordjs/discord.js/commit/f6db285c073898a749fe4591cbd4463d1896daf5)) + +## Features + +- **builder:** Add max min length in string option (#8214) ([96c8d21](https://github.com/discordjs/discord.js/commit/96c8d21f95eb366c46ae23505ba9054f44821b25)) +- Codecov (#8219) ([f10f4cd](https://github.com/discordjs/discord.js/commit/f10f4cdcd88ca6be7ec735ed3a415ba13da83db0)) +- **docgen:** Update typedoc ([b3346f4](https://github.com/discordjs/discord.js/commit/b3346f4b9b3d4f96443506643d4631dc1c6d7b21)) +- Website (#8043) ([127931d](https://github.com/discordjs/discord.js/commit/127931d1df7a2a5c27923c2f2151dbf3824e50cc)) +- **docgen:** Typescript support ([3279b40](https://github.com/discordjs/discord.js/commit/3279b40912e6aa61507bedb7db15a2b8668de44b)) +- Docgen package (#8029) ([8b979c0](https://github.com/discordjs/discord.js/commit/8b979c0245c42fd824d8e98745ee869f5360fc86)) +- Use vitest instead of jest for more speed ([8d8e6c0](https://github.com/discordjs/discord.js/commit/8d8e6c03decd7352a2aa180f6e5bc1a13602539b)) +- Add scripts package for locally used scripts ([f2ae1f9](https://github.com/discordjs/discord.js/commit/f2ae1f9348bfd893332a9060f71a8a5f272a1b8b)) + +## Refactor + +- **rest:** Add content-type(s) to uploads (#8290) ([103a358](https://github.com/discordjs/discord.js/commit/103a3584c95a7b7f57fa62d47b86520d5ec32303)) +- **collection:** Remove default export (#8053) ([16810f3](https://github.com/discordjs/discord.js/commit/16810f3e410bf35ed7e6e7412d517ea74c792c5d)) +- Move all the config files to root (#8033) ([769ea0b](https://github.com/discordjs/discord.js/commit/769ea0bfe78c4f1d413c6b397c604ffe91e39c6a)) + +# [@discordjs/rest@0.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.4.0...@discordjs/rest@0.5.0) - (2022-06-04) + +## Bug Fixes + +- **REST:** Remove dom types (#7922) ([e92b17d](https://github.com/discordjs/discord.js/commit/e92b17d8555164ff259e524efc6a26675660e5c2)) +- Ok statusCode can be 200..299 (#7919) ([d1504f2](https://github.com/discordjs/discord.js/commit/d1504f2ae19816b3fadcdb3ad17facc863ed7529)) + +## Features + +- **rest:** Add guild member banner cdn url (#7973) ([97eaab3](https://github.com/discordjs/discord.js/commit/97eaab35d7383ecbbd93dc623ceda969286c1554)) +- REST#raw (#7929) ([dfe449c](https://github.com/discordjs/discord.js/commit/dfe449c253b617e8f92c720a2f71135aa1601a65)) +- **rest:** Use undici (#7747) ([d1ec8c3](https://github.com/discordjs/discord.js/commit/d1ec8c37ffb7fe3b63eaa8c382f22ca1fb348c9b)) +- **REST:** Enable setting default authPrefix (#7853) ([679dcda](https://github.com/discordjs/discord.js/commit/679dcda9709376f37cc58a60f74d12d324d93e4e)) + +## Styling + +- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629)) + +# [@discordjs/rest@0.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.3.0...@discordjs/rest@0.4.0) - (2022-04-17) + +## Bug Fixes + +- **gateway:** Use version 10 (#7689) ([8880de0](https://github.com/discordjs/discord.js/commit/8880de0cecdf273fd6df23988e4cb77774a75390)) +- **RequestHandler:** Only reset tokens for authenticated 401s (#7508) ([b9ff7b0](https://github.com/discordjs/discord.js/commit/b9ff7b057379a47ce13265f78e21bf0d55feaf0a)) +- **ci:** Ci error (#7454) ([0af9bc8](https://github.com/discordjs/discord.js/commit/0af9bc841ffe1a297d308500d696bad4b85abda9)) +- Use png as extension for defaultAvatarURL (#7414) ([538e9ce](https://github.com/discordjs/discord.js/commit/538e9cef459d00d74b9bd6852da3ce2acac9bae5)) +- **rest:** Sublimit all requests on unhandled routes (#7366) ([733ac82](https://github.com/discordjs/discord.js/commit/733ac82d5dffabc622fb59e06d06e83396734dc6)) +- Fix some typos (#7393) ([92a04f4](https://github.com/discordjs/discord.js/commit/92a04f4d98f6c6760214034cc8f5a1eaa78893c7)) + +## Documentation + +- Enhance /rest README (#7757) ([a1329bd](https://github.com/discordjs/discord.js/commit/a1329bd3ebafc6d5b5e2788ff082674f01b726f3)) + +## Features + +- Add `makeURLSearchParams` utility function (#7744) ([8eaec11](https://github.com/discordjs/discord.js/commit/8eaec114a98026024c21545988860c123948c55d)) +- Add API v10 support (#7477) ([72577c4](https://github.com/discordjs/discord.js/commit/72577c4bfd02524a27afb6ff4aebba9301a690d3)) +- Add support for module: NodeNext in TS and ESM (#7598) ([8f1986a](https://github.com/discordjs/discord.js/commit/8f1986a6aa98365e09b00e84ad5f9f354ab61f3d)) +- **builders:** Add attachment command option type (#7203) ([ae0f35f](https://github.com/discordjs/discord.js/commit/ae0f35f51d68dfa5a7dc43d161ef9365171debdb)) +- **cdn:** Add support for scheduled event image covers (#7335) ([ac26d9b](https://github.com/discordjs/discord.js/commit/ac26d9b1307d63e116b043505e5f925db7ed01aa)) + +## Refactor + +- **requestmanager:** Use timestampfrom (#7459) ([3298510](https://github.com/discordjs/discord.js/commit/32985109c3b7614d364007608f8c5af4bed753ae)) +- **files:** Remove redundant file property names (#7340) ([6725038](https://github.com/discordjs/discord.js/commit/67250382f99872a9edff99ebaa482ffa895b0c37)) + +# [@discordjs/rest@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.2.0...@discordjs/rest@0.3.0) - (2022-01-24) + +## Bug Fixes + +- **rest:** Don't add empty query (#7308) ([d0fa5aa](https://github.com/discordjs/discord.js/commit/d0fa5aaa26d316608120bca3050e14eefbe2f93b)) +- **rest:** Use http agent when protocol is not https (#7309) ([d8ea572](https://github.com/discordjs/discord.js/commit/d8ea572fb8a51f2f6a902c4926e814017d115708)) +- `ref` delay for rate limited requests (#7239) ([ed0cfd9](https://github.com/discordjs/discord.js/commit/ed0cfd91edc3a2b23a34a8ecd9db38baa12b52fa)) + +## Documentation + +- Fix a typo and use milliseconds instead of ms (#7251) ([0dd56af](https://github.com/discordjs/discord.js/commit/0dd56afe1cdf16f1e7d9afe1f8c29c31d1833a25)) + +## Features + +- Rest hash and handler sweeping (#7255) ([3bb4829](https://github.com/discordjs/discord.js/commit/3bb48298004d292214c6cb8f927c2fea78a42952)) +- Rest docs (#7281) ([9054f2f](https://github.com/discordjs/discord.js/commit/9054f2f7ad7f246431e5f53403535bf301c27a80)) + +## Refactor + +- **files:** File data can be much more than buffer (#7238) ([86ab526](https://github.com/discordjs/discord.js/commit/86ab526d493415b14b79b51d08c3677897d219ee)) +- **rest:** Rename attachment to file (#7199) ([c969cbf](https://github.com/discordjs/discord.js/commit/c969cbf6524093757d47108b6a55e62dcb210e8b)) + +## Testing + +- **voice:** Fix tests ([62c74b8](https://github.com/discordjs/discord.js/commit/62c74b8333066465e5bd295b8b102b35a506751d)) diff --git a/node_modules/@discordjs/rest/LICENSE b/node_modules/@discordjs/rest/LICENSE new file mode 100644 index 0000000..f9d970e --- /dev/null +++ b/node_modules/@discordjs/rest/LICENSE @@ -0,0 +1,192 @@ + 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 +Copyright 2021 Aura Román + +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/rest/README.md b/node_modules/@discordjs/rest/README.md new file mode 100644 index 0000000..d36725a --- /dev/null +++ b/node_modules/@discordjs/rest/README.md @@ -0,0 +1,112 @@ +
+
+

+ discord.js +

+
+

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

+

+ Vercel +

+
+ +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh-session +npm install @discordjs/rest +yarn add @discordjs/rest +pnpm add @discordjs/rest +``` + +## Examples + +Install all required dependencies: + +```sh-session +npm install @discordjs/rest discord-api-types +yarn add @discordjs/rest discord-api-types +pnpm add @discordjs/rest discord-api-types +``` + +Send a basic message: + +```js +import { REST } from '@discordjs/rest'; +import { Routes } from 'discord-api-types/v10'; + +const rest = new REST({ version: '10' }).setToken(TOKEN); + +try { + await rest.post(Routes.channelMessages(CHANNEL_ID), { + body: { + content: 'A message via REST!', + }, + }); +} catch (error) { + console.error(error); +} +``` + +Create a thread from an existing message to be archived after 60 minutes of inactivity: + +```js +import { REST } from '@discordjs/rest'; +import { Routes } from 'discord-api-types/v10'; + +const rest = new REST({ version: '10' }).setToken(TOKEN); + +try { + await rest.post(Routes.threads(CHANNEL_ID, MESSAGE_ID), { + body: { + name: 'Thread', + auto_archive_duration: 60, + }, + }); +} catch (error) { + console.error(error); +} +``` + +## 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. +- [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/rest +[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/rest +[npm]: https://www.npmjs.com/package/@discordjs/rest +[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/rest/dist/index.d.ts b/node_modules/@discordjs/rest/dist/index.d.ts new file mode 100644 index 0000000..f3ea479 --- /dev/null +++ b/node_modules/@discordjs/rest/dist/index.d.ts @@ -0,0 +1,870 @@ +import { Agent, Dispatcher, request, BodyInit } from 'undici'; +import { Buffer } from 'node:buffer'; +import { EventEmitter } from 'node:events'; +import { URLSearchParams } from 'node:url'; +import { Collection } from '@discordjs/collection'; + +declare const DefaultUserAgent: `DiscordBot (https://discord.js.org, ${string})`; +declare const DefaultRestOptions: { + readonly agent: Agent; + readonly api: "https://discord.com/api"; + readonly authPrefix: "Bot"; + readonly cdn: "https://cdn.discordapp.com"; + readonly headers: {}; + readonly invalidRequestWarningInterval: 0; + readonly globalRequestsPerSecond: 50; + readonly offset: 50; + readonly rejectOnRateLimit: null; + readonly retries: 3; + readonly timeout: 15000; + readonly userAgentAppendix: `Node.js ${string}`; + readonly version: "10"; + readonly hashSweepInterval: 14400000; + readonly hashLifetime: 86400000; + readonly handlerSweepInterval: 3600000; +}; +/** + * The events that the REST manager emits + */ +declare const enum RESTEvents { + Debug = "restDebug", + HandlerSweep = "handlerSweep", + HashSweep = "hashSweep", + InvalidRequestWarning = "invalidRequestWarning", + RateLimited = "rateLimited", + Response = "response" +} +declare const ALLOWED_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif"]; +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]; +declare const OverwrittenMimeTypes: { + readonly 'image/apng': "image/png"; +}; + +/** + * The options used for image URLs + */ +interface BaseImageURLOptions { + /** + * The extension to use for the image URL + * + * @defaultValue `'webp'` + */ + extension?: ImageExtension; + /** + * The size specified in the image URL + */ + size?: ImageSize; +} +/** + * The options used for image URLs with animated content + */ +interface ImageURLOptions extends BaseImageURLOptions { + /** + * Whether or not to prefer the static version of an image asset. + */ + forceStatic?: boolean; +} +/** + * The options to use when making a CDN URL + */ +interface MakeURLOptions { + /** + * The allowed extensions that can be used + */ + allowedExtensions?: readonly string[]; + /** + * The extension to use for the image URL + * + * @defaultValue `'webp'` + */ + extension?: string | undefined; + /** + * The size specified in the image URL + */ + size?: ImageSize; +} +/** + * The CDN link builder + */ +declare class CDN { + private readonly base; + constructor(base?: string); + /** + * 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: string, assetHash: string, options?: Readonly): string; + /** + * 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: string, iconHash: string, options?: Readonly): string; + /** + * 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: string, avatarHash: string, options?: Readonly): string; + /** + * 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: string, bannerHash: string, options?: Readonly): string; + /** + * 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: string, iconHash: string, options?: Readonly): string; + /** + * Generates the default avatar URL for a discriminator. + * + * @param discriminator - The discriminator modulo 5 + */ + defaultAvatar(discriminator: number): string; + /** + * 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: string, splashHash: string, options?: Readonly): string; + /** + * Generates an emoji's URL for an emoji. + * + * @param emojiId - The emoji id + * @param extension - The extension of the emoji + */ + emoji(emojiId: string, extension?: ImageExtension): string; + /** + * 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: string, userId: string, avatarHash: string, options?: Readonly): string; + /** + * 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: string, userId: string, bannerHash: string, options?: Readonly): string; + /** + * 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: string, iconHash: string, options?: Readonly): string; + /** + * 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: string, roleIconHash: string, options?: Readonly): string; + /** + * 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: string, splashHash: string, options?: Readonly): string; + /** + * 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: string, extension?: StickerExtension): string; + /** + * Generates a sticker pack banner URL. + * + * @param bannerId - The banner id + * @param options - Optional options for the banner + */ + stickerPackBanner(bannerId: string, options?: Readonly): string; + /** + * 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: string, iconHash: string, options?: Readonly): string; + /** + * 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: string, coverHash: string, options?: Readonly): string; + /** + * 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 + */ + private dynamicMakeURL; + /** + * Constructs the URL for the resource + * + * @param route - The base cdn route + * @param options - The extension/size options for the link + */ + private makeURL; +} + +interface IHandler { + /** + * The unique id of the handler + */ + readonly id: string; + /** + * If the bucket is currently inactive (no pending requests) + */ + get inactive(): boolean; + /** + * Queues a request to be sent + * + * @param routeId - The generalized api route with literal ids for major parameters + * @param url - The url to do the request on + * @param options - All the information needed to make a request + * @param requestData - Extra data from the user's request needed for errors and additional processing + */ + queueRequest(routeId: RouteData, url: string, options: RequestOptions, requestData: HandlerRequestData): Promise; +} + +/** + * Options to be passed when creating the REST instance + */ +interface RESTOptions { + /** + * The agent to set globally + */ + agent: Dispatcher; + /** + * The base api path, without version + * + * @defaultValue `'https://discord.com/api'` + */ + api: string; + /** + * The authorization prefix to use for requests, useful if you want to use + * bearer tokens + * + * @defaultValue `'Bot'` + */ + authPrefix: 'Bearer' | 'Bot'; + /** + * The cdn path + * + * @defaultValue 'https://cdn.discordapp.com' + */ + cdn: string; + /** + * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord) + * + * @defaultValue `50` + */ + globalRequestsPerSecond: number; + /** + * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h) + * + * @defaultValue `3_600_000` + */ + handlerSweepInterval: number; + /** + * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h) + * + * @defaultValue `86_400_000` + */ + hashLifetime: number; + /** + * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h) + * + * @defaultValue `14_400_000` + */ + hashSweepInterval: number; + /** + * Additional headers to send for all API requests + * + * @defaultValue `{}` + */ + headers: Record; + /** + * 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). + * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on. + * + * @defaultValue `0` + */ + invalidRequestWarningInterval: number; + /** + * The extra offset to add to rate limits in milliseconds + * + * @defaultValue `50` + */ + offset: number; + /** + * Determines how rate limiting and pre-emptive throttling should be handled. + * When an array of strings, each element is treated as a prefix for the request route + * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`) + * for which to throw {@link RateLimitError}s. All other request routes will be queued normally + * + * @defaultValue `null` + */ + rejectOnRateLimit: RateLimitQueueFilter | string[] | null; + /** + * The number of retries for errors with the 500 code, or errors + * that timeout + * + * @defaultValue `3` + */ + retries: number; + /** + * The time to wait in milliseconds before a request is aborted + * + * @defaultValue `15_000` + */ + timeout: number; + /** + * Extra information to add to the user agent + * + * @defaultValue `Node.js ${process.version}` + */ + userAgentAppendix: string; + /** + * The version of the API to use + * + * @defaultValue `'10'` + */ + version: string; +} +/** + * Data emitted on `RESTEvents.RateLimited` + */ +interface RateLimitData { + /** + * Whether the rate limit that was reached was the global limit + */ + global: boolean; + /** + * The bucket hash for this request + */ + hash: string; + /** + * The amount of requests we can perform before locking requests + */ + limit: number; + /** + * The major parameter of the route + * + * For example, in `/channels/x`, this will be `x`. + * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`. + */ + majorParameter: string; + /** + * The HTTP method being performed + */ + method: string; + /** + * The route being hit in this request + */ + route: string; + /** + * The time, in milliseconds, until the request-lock is reset + */ + timeToReset: number; + /** + * The full URL for this request + */ + url: string; +} +/** + * A function that determines whether the rate limit hit should throw an Error + */ +type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean; +interface APIRequest { + /** + * The data that was used to form the body of this request + */ + data: HandlerRequestData; + /** + * The HTTP method used in this request + */ + method: string; + /** + * Additional HTTP options for this request + */ + options: RequestOptions; + /** + * The full path used to make the request + */ + path: RouteLike; + /** + * The number of times this request has been attempted + */ + retries: number; + /** + * The API route identifying the ratelimit for this request + */ + route: string; +} +interface InvalidRequestWarningData { + /** + * Number of invalid requests that have been made in the window + */ + count: number; + /** + * Time in milliseconds remaining before the count resets + */ + remainingTime: number; +} +interface RestEvents { + handlerSweep: [sweptHandlers: Collection]; + hashSweep: [sweptHashes: Collection]; + invalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData]; + newListener: [name: string, listener: (...args: any) => void]; + rateLimited: [rateLimitInfo: RateLimitData]; + removeListener: [name: string, listener: (...args: any) => void]; + response: [request: APIRequest, response: Dispatcher.ResponseData]; + restDebug: [info: string]; +} +type RequestOptions = Exclude[1], undefined>; +interface REST { + emit: ((event: K, ...args: RestEvents[K]) => boolean) & ((event: Exclude, ...args: any[]) => boolean); + off: ((event: K, listener: (...args: RestEvents[K]) => void) => this) & ((event: Exclude, listener: (...args: any[]) => void) => this); + on: ((event: K, listener: (...args: RestEvents[K]) => void) => this) & ((event: Exclude, listener: (...args: any[]) => void) => this); + once: ((event: K, listener: (...args: RestEvents[K]) => void) => this) & ((event: Exclude, listener: (...args: any[]) => void) => this); + removeAllListeners: ((event?: K) => this) & ((event?: Exclude) => this); +} +declare class REST extends EventEmitter { + readonly cdn: CDN; + readonly requestManager: RequestManager; + constructor(options?: Partial); + /** + * Gets the agent set for this instance + */ + getAgent(): Dispatcher | null; + /** + * Sets the default agent to use for requests performed by this instance + * + * @param agent - Sets the agent to use + */ + setAgent(agent: Dispatcher): this; + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ + setToken(token: string): this; + /** + * Runs a get request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ + get(fullRoute: RouteLike, options?: RequestData): Promise; + /** + * Runs a delete request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ + delete(fullRoute: RouteLike, options?: RequestData): Promise; + /** + * Runs a post request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ + post(fullRoute: RouteLike, options?: RequestData): Promise; + /** + * Runs a put request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ + put(fullRoute: RouteLike, options?: RequestData): Promise; + /** + * Runs a patch request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ + patch(fullRoute: RouteLike, options?: RequestData): Promise; + /** + * Runs a request from the api + * + * @param options - Request options + */ + request(options: InternalRequest): Promise; + /** + * Runs a request from the API, yielding the raw Response object + * + * @param options - Request options + */ + raw(options: InternalRequest): Promise; +} + +/** + * Represents a file to be added to the request + */ +interface RawFile { + /** + * Content-Type of the file + */ + contentType?: string; + /** + * The actual data for the file + */ + data: Buffer | boolean | number | string; + /** + * An explicit key to use for key of the formdata field for this file. + * When not provided, the index of the file in the files array is used in the form `files[${index}]`. + * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`) + */ + key?: string; + /** + * The name of the file + */ + name: string; +} +/** + * Represents possible data to be given to an endpoint + */ +interface RequestData { + /** + * Whether to append JSON data to form data instead of `payload_json` when sending files + */ + appendToFormData?: boolean; + /** + * If this request needs the `Authorization` header + * + * @defaultValue `true` + */ + auth?: boolean; + /** + * The authorization prefix to use for this request, useful if you use this with bearer tokens + * + * @defaultValue `'Bot'` + */ + authPrefix?: 'Bearer' | 'Bot'; + /** + * The body to send to this request. + * If providing as BodyInit, set `passThroughBody: true` + */ + body?: BodyInit | unknown; + /** + * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request. + */ + dispatcher?: Agent; + /** + * Files to be attached to this request + */ + files?: RawFile[] | undefined; + /** + * Additional headers to add to this request + */ + headers?: Record; + /** + * Whether to pass-through the body property directly to `fetch()`. + * This only applies when files is NOT present + */ + passThroughBody?: boolean; + /** + * Query string parameters to append to the called endpoint + */ + query?: URLSearchParams; + /** + * Reason to show in the audit logs + */ + reason?: string | undefined; + /** + * The signal to abort the queue entry or the REST call, where applicable + */ + signal?: AbortSignal | undefined; + /** + * If this request should be versioned + * + * @defaultValue `true` + */ + versioned?: boolean; +} +/** + * Possible headers for an API call + */ +interface RequestHeaders { + Authorization?: string; + 'User-Agent': string; + 'X-Audit-Log-Reason'?: string; +} +/** + * Possible API methods to be used when doing requests + */ +declare const enum RequestMethod { + Delete = "DELETE", + Get = "GET", + Patch = "PATCH", + Post = "POST", + Put = "PUT" +} +type RouteLike = `/${string}`; +/** + * Internal request options + * + * @internal + */ +interface InternalRequest extends RequestData { + fullRoute: RouteLike; + method: RequestMethod; +} +type HandlerRequestData = Pick; +/** + * Parsed route data for an endpoint + * + * @internal + */ +interface RouteData { + bucketRoute: string; + majorParameter: string; + original: RouteLike; +} +/** + * Represents a hash and its associated fields + * + * @internal + */ +interface HashData { + lastAccess: number; + value: string; +} +interface RequestManager { + emit: ((event: K, ...args: RestEvents[K]) => boolean) & ((event: Exclude, ...args: any[]) => boolean); + off: ((event: K, listener: (...args: RestEvents[K]) => void) => this) & ((event: Exclude, listener: (...args: any[]) => void) => this); + on: ((event: K, listener: (...args: RestEvents[K]) => void) => this) & ((event: Exclude, listener: (...args: any[]) => void) => this); + once: ((event: K, listener: (...args: RestEvents[K]) => void) => this) & ((event: Exclude, listener: (...args: any[]) => void) => this); + removeAllListeners: ((event?: K) => this) & ((event?: Exclude) => this); +} +/** + * Represents the class that manages handlers for endpoints + */ +declare class RequestManager extends EventEmitter { + #private; + /** + * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests + * performed by this manager. + */ + agent: Dispatcher | null; + /** + * The number of requests remaining in the global bucket + */ + globalRemaining: number; + /** + * The promise used to wait out the global rate limit + */ + globalDelay: Promise | null; + /** + * The timestamp at which the global bucket resets + */ + globalReset: number; + /** + * API bucket hashes that are cached from provided routes + */ + readonly hashes: Collection; + /** + * Request handlers created from the bucket hash and the major parameters + */ + readonly handlers: Collection; + private hashTimer; + private handlerTimer; + readonly options: RESTOptions; + constructor(options: Partial); + private setupSweepers; + /** + * Sets the default agent to use for requests performed by this manager + * + * @param agent - The agent to use + */ + setAgent(agent: Dispatcher): this; + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ + setToken(token: string): this; + /** + * Queues a request to be sent + * + * @param request - All the information needed to make a request + * @returns The response from the api request + */ + queueRequest(request: InternalRequest): Promise; + /** + * 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 + */ + private createHandler; + /** + * Formats the request data to a usable format for fetch + * + * @param request - The request data + */ + private resolveRequest; + /** + * Stops the hash sweeping interval + */ + clearHashSweeper(): void; + /** + * Stops the request handler sweeping interval + */ + clearHandlerSweeper(): void; + /** + * 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 + */ + private static generateRouteData; +} + +interface DiscordErrorFieldInformation { + code: string; + message: string; +} +interface DiscordErrorGroupWrapper { + _errors: DiscordError[]; +} +type DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { + [k: string]: DiscordError; +}; +interface DiscordErrorData { + code: number; + errors?: DiscordError; + message: string; +} +interface OAuthErrorData { + error: string; + error_description?: string; +} +interface RequestBody { + files: RawFile[] | undefined; + json: unknown | undefined; +} +/** + * Represents an API error returned by Discord + */ +declare class DiscordAPIError extends Error { + rawError: DiscordErrorData | OAuthErrorData; + code: number | string; + status: number; + method: string; + url: string; + requestBody: RequestBody; + /** + * @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: DiscordErrorData | OAuthErrorData, code: number | string, status: number, method: string, url: string, bodyData: Pick); + /** + * The name of the error + */ + get name(): string; + private static getMessage; + private static flattenDiscordError; +} + +/** + * Represents a HTTP error + */ +declare class HTTPError extends Error { + status: number; + method: string; + url: string; + requestBody: RequestBody; + name: string; + /** + * @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: number, method: string, url: string, bodyData: Pick); +} + +declare class RateLimitError extends Error implements RateLimitData { + timeToReset: number; + limit: number; + method: string; + hash: string; + url: string; + route: string; + majorParameter: string; + global: boolean; + constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData); + /** + * The name of the error + */ + get name(): string; +} + +/** + * Creates and populates an URLSearchParams instance from an object, stripping + * out null and undefined values, while also coercing non-strings to strings. + * + * @param options - The options to use + * @returns A populated URLSearchParams instance + */ +declare function makeURLSearchParams(options?: Readonly): URLSearchParams; +/** + * Converts the response to usable data + * + * @param res - The fetch response + */ +declare function parseResponse(res: Dispatcher.ResponseData): Promise; + +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version + * that you are currently using. + */ +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, 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 new file mode 100644 index 0000000..42e45b3 --- /dev/null +++ b/node_modules/@discordjs/rest/dist/index.js @@ -0,0 +1,1357 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +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 __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); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + ALLOWED_EXTENSIONS: () => ALLOWED_EXTENSIONS, + ALLOWED_SIZES: () => ALLOWED_SIZES, + ALLOWED_STICKER_EXTENSIONS: () => ALLOWED_STICKER_EXTENSIONS, + CDN: () => CDN, + DefaultRestOptions: () => DefaultRestOptions, + DefaultUserAgent: () => DefaultUserAgent, + DiscordAPIError: () => DiscordAPIError, + HTTPError: () => HTTPError, + OverwrittenMimeTypes: () => OverwrittenMimeTypes, + REST: () => REST, + RESTEvents: () => RESTEvents, + RateLimitError: () => RateLimitError, + RequestManager: () => RequestManager, + RequestMethod: () => RequestMethod, + makeURLSearchParams: () => makeURLSearchParams, + parseResponse: () => parseResponse, + version: () => version +}); +module.exports = __toCommonJS(src_exports); + +// src/lib/CDN.ts +var import_node_url = require("url"); + +// src/lib/utils/constants.ts +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, [VI]{{inject}}[/VI])`; +var DefaultRestOptions = { + get agent() { + return new import_undici.Agent({ + connect: { + timeout: 3e4 + } + }); + }, + api: "https://discord.com/api", + authPrefix: "Bot", + cdn: "https://cdn.discordapp.com", + headers: {}, + invalidRequestWarningInterval: 0, + globalRequestsPerSecond: 50, + offset: 50, + rejectOnRateLimit: null, + retries: 3, + timeout: 15e3, + userAgentAppendix: `Node.js ${import_node_process.default.version}`, + version: import_v10.APIVersion, + hashSweepInterval: 144e5, + hashLifetime: 864e5, + handlerSweepInterval: 36e5 +}; +var RESTEvents; +(function(RESTEvents2) { + RESTEvents2["Debug"] = "restDebug"; + RESTEvents2["HandlerSweep"] = "handlerSweep"; + RESTEvents2["HashSweep"] = "hashSweep"; + RESTEvents2["InvalidRequestWarning"] = "invalidRequestWarning"; + RESTEvents2["RateLimited"] = "rateLimited"; + RESTEvents2["Response"] = "response"; +})(RESTEvents || (RESTEvents = {})); +var ALLOWED_EXTENSIONS = [ + "webp", + "png", + "jpg", + "jpeg", + "gif" +]; +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" +}; + +// 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); + } + /** + * 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)) { + throw new RangeError(`Invalid extension provided: ${extension} +Must be one of: ${allowedExtensions.join(", ")}`); + } + if (size && !ALLOWED_SIZES.includes(size)) { + throw new RangeError(`Invalid size provided: ${size} +Must be one of: ${ALLOWED_SIZES.join(", ")}`); + } + const url = new import_node_url.URL(`${this.base}${route}.${extension}`); + if (size) { + url.searchParams.set("size", String(size)); + } + return url.toString(); + } +}; +__name(CDN, "CDN"); + +// src/lib/errors/DiscordAPIError.ts +function isErrorGroupWrapper(error) { + return Reflect.has(error, "_errors"); +} +__name(isErrorGroupWrapper, "isErrorGroupWrapper"); +function isErrorResponse(error) { + return typeof Reflect.get(error, "message") === "string"; +} +__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; + this.code = code; + this.status = status; + this.method = method; + this.url = url; + this.requestBody = { + files: bodyData.files, + json: bodyData.body + }; + } + /** + * The name of the error + */ + get name() { + return `${DiscordAPIError.name}[${this.code}]`; + } + static getMessage(error) { + let flattened = ""; + if ("code" in error) { + if (error.errors) { + flattened = [ + ...this.flattenDiscordError(error.errors) + ].join("\n"); + } + return error.message && flattened ? `${error.message} +${flattened}` : error.message || flattened || "Unknown Error"; + } + return error.error_description ?? "No Description"; + } + static *flattenDiscordError(obj, key = "") { + if (isErrorResponse(obj)) { + return yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim(); + } + for (const [otherKey, val] of Object.entries(obj)) { + const nextKey = otherKey.startsWith("_") ? key : key ? Number.isNaN(Number(otherKey)) ? `${key}.${otherKey}` : `${key}[${otherKey}]` : otherKey; + if (typeof val === "string") { + yield val; + } else if (isErrorGroupWrapper(val)) { + for (const error of val._errors) { + yield* this.flattenDiscordError(error, nextKey); + } + } else { + yield* this.flattenDiscordError(val, nextKey); + } + } + } +}; +__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; + this.method = method; + this.url = url; + this.name = HTTPError.name; + this.requestBody = { + files: bodyData.files, + json: bodyData.body + }; + } +}; +__name(HTTPError, "HTTPError"); + +// src/lib/errors/RateLimitError.ts +var RateLimitError = class extends Error { + constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }) { + super(); + this.timeToReset = timeToReset; + this.limit = limit; + this.method = method; + this.hash = hash; + this.url = url; + this.route = route; + this.majorParameter = majorParameter; + this.global = global; + } + /** + * The name of the error + */ + get name() { + return `${RateLimitError.name}[${this.route}]`; + } +}; +__name(RateLimitError, "RateLimitError"); + +// src/lib/RequestManager.ts +var import_node_buffer2 = require("buffer"); +var import_node_events = require("events"); +var import_node_timers2 = require("timers"); +var import_collection = require("@discordjs/collection"); +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"); +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"); +var import_node_url2 = require("url"); +var import_node_util = require("util"); +var import_undici2 = require("undici"); +function parseHeader(header) { + if (header === void 0 || typeof header === "string") { + return header; + } + return header.join(";"); +} +__name(parseHeader, "parseHeader"); +function serializeSearchParam(value) { + switch (typeof value) { + case "string": + return value; + case "number": + case "bigint": + case "boolean": + return value.toString(); + case "object": + if (value === null) + return null; + if (value instanceof Date) { + return Number.isNaN(value.getTime()) ? null : value.toISOString(); + } + if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) + return value.toString(); + return null; + default: + return null; + } +} +__name(serializeSearchParam, "serializeSearchParam"); +function makeURLSearchParams(options) { + const params = new import_node_url2.URLSearchParams(); + if (!options) + return params; + for (const [key, value] of Object.entries(options)) { + const serialized = serializeSearchParam(value); + if (serialized !== null) + params.append(key, serialized); + } + return params; +} +__name(makeURLSearchParams, "makeURLSearchParams"); +async function parseResponse(res) { + const header = parseHeader(res.headers["content-type"]); + if (header?.startsWith("application/json")) { + return res.body.json(); + } + return res.body.arrayBuffer(); +} +__name(parseResponse, "parseResponse"); +function hasSublimit(bucketRoute, body, method) { + if (bucketRoute === "/channels/:id") { + if (typeof body !== "object" || body === null) + return false; + if (method !== RequestMethod.Patch) + return false; + const castedBody = body; + return [ + "name", + "topic" + ].some((key) => Reflect.has(castedBody, key)); + } + return true; +} +__name(hasSublimit, "hasSublimit"); +async function resolveBody(body) { + if (body == null) { + return null; + } else if (typeof body === "string") { + return body; + } else if (import_node_util.types.isUint8Array(body)) { + return body; + } else if (import_node_util.types.isArrayBuffer(body)) { + return new Uint8Array(body); + } else if (body instanceof import_node_url2.URLSearchParams) { + return body.toString(); + } else if (body instanceof DataView) { + return new Uint8Array(body.buffer); + } else if (body instanceof import_node_buffer.Blob) { + return new Uint8Array(await body.arrayBuffer()); + } else if (body instanceof import_undici2.FormData) { + return body; + } else if (body[Symbol.iterator]) { + const chunks = [ + ...body + ]; + const length = chunks.reduce((a, b) => a + b.length, 0); + const uint8 = new Uint8Array(length); + let lengthUsed = 0; + return chunks.reduce((a, b) => { + a.set(b, lengthUsed); + lengthUsed += b.length; + return a; + }, uint8); + } else if (body[Symbol.asyncIterator]) { + const chunks = []; + for await (const chunk of body) { + chunks.push(chunk); + } + return import_node_buffer.Buffer.concat(chunks); + } + throw new TypeError(`Unable to resolve body.`); +} +__name(resolveBody, "resolveBody"); +function shouldRetry(error) { + if (error.name === "AbortError") + return true; + return "code" in error && error.code === "ECONNRESET" || error.message.includes("ECONNRESET"); +} +__name(shouldRetry, "shouldRetry"); + +// src/lib/handlers/SequentialHandler.ts +var invalidCount = 0; +var invalidCountResetTime = null; +var QueueType; +(function(QueueType2) { + QueueType2[QueueType2["Standard"] = 0] = "Standard"; + QueueType2[QueueType2["Sublimit"] = 1] = "Sublimit"; +})(QueueType || (QueueType = {})); +var SequentialHandler = class { + /** + * The interface used to sequence async requests sequentially + */ + #asyncQueue; + /** + * The interface used to sequence sublimited async requests sequentially + */ + #sublimitedQueue; + /** + * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed + */ + #sublimitPromise; + /** + * Whether the sublimit queue needs to be shifted in the finally block + */ + #shiftSublimit; + /** + * @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.reset = -1; + this.remaining = 1; + this.limit = Number.POSITIVE_INFINITY; + this.#asyncQueue = new import_async_queue.AsyncQueue(); + this.#sublimitedQueue = null; + this.#sublimitPromise = null; + this.#shiftSublimit = false; + this.id = `${hash}:${majorParameter}`; + } + /** + * {@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(RESTEvents.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); + this.manager.globalDelay = null; + } + /* + * Determines whether the request should be queued or whether a RateLimitError should be thrown + */ + 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; + if (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) { + queue = this.#sublimitedQueue; + queueType = 1; + } + await queue.wait({ + signal: requestData.signal + }); + if (queueType === 0) { + if (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) { + queue = this.#sublimitedQueue; + const wait = queue.wait(); + this.#asyncQueue.shift(); + await wait; + } else if (this.#sublimitPromise) { + await this.#sublimitPromise.promise; + } + } + try { + return await this.runRequest(routeId, url, options, requestData); + } finally { + queue.shift(); + if (this.#shiftSublimit) { + this.#shiftSublimit = false; + this.#sublimitedQueue?.shift(); + } + if (this.#sublimitedQueue?.remaining === 0) { + this.#sublimitPromise?.resolve(); + this.#sublimitedQueue = null; + } + } + } + /** + * 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 delay; + if (isGlobal) { + limit2 = this.manager.options.globalRequestsPerSecond; + timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + if (!this.manager.globalDelay) { + this.manager.globalDelay = this.globalDelayFor(timeout2); + } + delay = this.manager.globalDelay; + } else { + limit2 = this.limit; + timeout2 = this.timeToReset; + delay = (0, import_promises.setTimeout)(timeout2); + } + const rateLimitData = { + timeToReset: timeout2, + limit: limit2, + method: options.method ?? "get", + hash: this.hash, + url, + route: routeId.bucketRoute, + majorParameter: this.majorParameter, + global: isGlobal + }; + this.manager.emit(RESTEvents.RateLimited, rateLimitData); + await this.onRateLimit(rateLimitData); + if (isGlobal) { + this.debug(`Global rate limit hit, blocking all requests for ${timeout2}ms`); + } else { + this.debug(`Waiting ${timeout2}ms for rate limit to pass`); + } + await delay; + } + if (!this.manager.globalReset || this.manager.globalReset < Date.now()) { + this.manager.globalReset = Date.now() + 1e3; + this.manager.globalRemaining = this.manager.options.globalRequestsPerSecond; + } + 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(RESTEvents.Response)) { + this.manager.emit(RESTEvents.Response, { + method, + path: routeId.original, + route: routeId.bucketRoute, + options, + data: requestData, + retries + }, { + ...res + }); + } + const status = res.statusCode; + let retryAfter = 0; + const limit = parseHeader(res.headers["x-ratelimit-limit"]); + const remaining = parseHeader(res.headers["x-ratelimit-remaining"]); + const reset = parseHeader(res.headers["x-ratelimit-reset-after"]); + const hash = parseHeader(res.headers["x-ratelimit-bucket"]); + const retry = parseHeader(res.headers["retry-after"]); + this.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY; + this.remaining = remaining ? Number(remaining) : 1; + this.reset = reset ? Number(reset) * 1e3 + Date.now() + this.manager.options.offset : Date.now(); + if (retry) + retryAfter = Number(retry) * 1e3 + this.manager.options.offset; + if (hash && hash !== this.hash) { + this.debug([ + "Received bucket hash update", + ` Old Hash : ${this.hash}`, + ` New Hash : ${hash}` + ].join("\n")); + this.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { + value: hash, + lastAccess: Date.now() + }); + } else if (hash) { + const hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`); + if (hashData) { + hashData.lastAccess = Date.now(); + } + } + let sublimitTimeout = null; + if (retryAfter > 0) { + if (res.headers["x-ratelimit-global"] !== void 0) { + this.manager.globalRemaining = 0; + this.manager.globalReset = Date.now() + retryAfter; + } else if (!this.localLimited) { + sublimitTimeout = retryAfter; + } + } + 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(RESTEvents.InvalidRequestWarning, { + count: invalidCount, + remainingTime: invalidCountResetTime - Date.now() + }); + } + } + if (status >= 200 && status < 300) { + return res; + } else if (status === 429) { + const isGlobal = this.globalLimited; + let limit2; + let timeout2; + if (isGlobal) { + limit2 = this.manager.options.globalRequestsPerSecond; + timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + } else { + limit2 = this.limit; + timeout2 = this.timeToReset; + } + await this.onRateLimit({ + timeToReset: timeout2, + limit: limit2, + method, + hash: this.hash, + url, + route: routeId.bucketRoute, + majorParameter: this.majorParameter, + global: isGlobal + }); + this.debug([ + "Encountered unexpected 429 rate limit", + ` Global : ${isGlobal.toString()}`, + ` Method : ${method}`, + ` URL : ${url}`, + ` Bucket : ${routeId.bucketRoute}`, + ` Major parameter: ${routeId.majorParameter}`, + ` Hash : ${this.hash}`, + ` Limit : ${limit2}`, + ` Retry After : ${retryAfter}ms`, + ` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : "None"}` + ].join("\n")); + if (sublimitTimeout) { + const firstSublimit = !this.#sublimitedQueue; + if (firstSublimit) { + this.#sublimitedQueue = new import_async_queue.AsyncQueue(); + void this.#sublimitedQueue.wait(); + this.#asyncQueue.shift(); + } + this.#sublimitPromise?.resolve(); + this.#sublimitPromise = null; + await (0, import_promises.setTimeout)(sublimitTimeout); + let resolve; + const promise = new Promise((res2) => resolve = res2); + this.#sublimitPromise = { + promise, + resolve + }; + if (firstSublimit) { + await this.#asyncQueue.wait(); + this.#shiftSublimit = true; + } + } + 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); + } + return res; + } + } +}; +__name(SequentialHandler, "SequentialHandler"); + +// src/lib/RequestManager.ts +var getFileType = (0, import_util.lazy)(async () => import("file-type")); +var RequestMethod; +(function(RequestMethod2) { + RequestMethod2["Delete"] = "DELETE"; + RequestMethod2["Get"] = "GET"; + RequestMethod2["Patch"] = "PATCH"; + RequestMethod2["Post"] = "POST"; + RequestMethod2["Put"] = "PUT"; +})(RequestMethod || (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 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; + constructor(options) { + super(); + this.options = { + ...DefaultRestOptions, + ...options + }; + this.options.offset = Math.max(0, this.options.offset); + this.globalRemaining = this.options.globalRequestsPerSecond; + this.agent = options.agent ?? null; + this.setupSweepers(); + } + setupSweepers() { + const validateMaxInterval = /* @__PURE__ */ __name((interval) => { + if (interval > 144e5) { + throw new Error("Cannot set an interval greater than 4 hours"); + } + }, "validateMaxInterval"); + if (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) { + validateMaxInterval(this.options.hashSweepInterval); + this.hashTimer = (0, import_node_timers2.setInterval)(() => { + const sweptHashes = new import_collection.Collection(); + const currentDate = Date.now(); + this.hashes.sweep((val, key) => { + if (val.lastAccess === -1) + return false; + const shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime; + if (shouldSweep) { + sweptHashes.set(key, val); + } + this.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`); + return shouldSweep; + }); + this.emit(RESTEvents.HashSweep, sweptHashes); + }, this.options.hashSweepInterval).unref(); + } + if (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) { + validateMaxInterval(this.options.handlerSweepInterval); + this.handlerTimer = (0, import_node_timers2.setInterval)(() => { + const sweptHandlers = new import_collection.Collection(); + this.handlers.sweep((val, key) => { + const { inactive } = val; + if (inactive) { + sweptHandlers.set(key, val); + } + this.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`); + return inactive; + }); + this.emit(RESTEvents.HandlerSweep, sweptHandlers); + }, 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}`) ?? { + value: `Global(${request2.method}:${routeId.bucketRoute})`, + lastAccess: -1 + }; + const handler = this.handlers.get(`${hash.value}:${routeId.majorParameter}`) ?? this.createHandler(hash.value, routeId.majorParameter); + const { url, fetchOptions } = await this.resolveRequest(request2); + return handler.queueRequest(routeId, url, fetchOptions, { + body: request2.body, + files: request2.files, + auth: request2.auth !== false, + 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); + 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 = ""; + if (request2.query) { + const resolvedQuery = request2.query.toString(); + if (resolvedQuery !== "") { + query = `?${resolvedQuery}`; + } + } + const headers = { + ...this.options.headers, + "User-Agent": `${DefaultUserAgent} ${options.userAgentAppendix}`.trim() + }; + if (request2.auth !== false) { + if (!this.#token) { + throw new Error("Expected token to be set for this request, but none was present"); + } + headers.Authorization = `${request2.authPrefix ?? this.options.authPrefix} ${this.#token}`; + } + if (request2.reason?.length) { + headers["X-Audit-Log-Reason"] = encodeURIComponent(request2.reason); + } + const url = `${options.api}${request2.versioned === false ? "" : `/v${options.version}`}${request2.fullRoute}${query}`; + let finalBody; + let additionalHeaders = {}; + if (request2.files?.length) { + const formData = new import_undici4.FormData(); + for (const [index, file] of request2.files.entries()) { + const fileKey = file.key ?? `files[${index}]`; + if (import_node_buffer2.Buffer.isBuffer(file.data)) { + const { fileTypeFromBuffer } = await getFileType(); + 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); + } + } + if (request2.body != null) { + if (request2.appendToFormData) { + for (const [key, value] of Object.entries(request2.body)) { + formData.append(key, value); + } + } else { + formData.append("payload_json", JSON.stringify(request2.body)); + } + } + finalBody = formData; + } else if (request2.body != null) { + if (request2.passThroughBody) { + finalBody = request2.body; + } else { + finalBody = JSON.stringify(request2.body); + additionalHeaders = { + "Content-Type": "application/json" + }; + } + } + finalBody = await resolveBody(finalBody); + const fetchOptions = { + headers: { + ...request2.headers, + ...additionalHeaders, + ...headers + }, + method: request2.method.toUpperCase() + }; + if (finalBody !== void 0) { + fetchOptions.body = finalBody; + } + 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{17,19})/.exec(endpoint); + const majorId = majorIdMatch?.[1] ?? "global"; + const baseRoute = endpoint.replaceAll(/\d{17,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); + let exceptions = ""; + if (method === "DELETE" && baseRoute === "/channels/:id/messages/:id") { + 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"; + } + } + return { + majorParameter: majorId, + bucketRoute: baseRoute + exceptions, + original: endpoint + }; + } +}; +__name(RequestManager, "RequestManager"); + +// src/lib/REST.ts +var import_node_events2 = require("events"); +var REST = class extends import_node_events2.EventEmitter { + constructor(options = {}) { + super(); + this.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn); + this.requestManager = new RequestManager(options).on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug)).on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited)).on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning)).on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep)); + this.on("newListener", (name, listener) => { + if (name === RESTEvents.Response) + this.requestManager.on(name, listener); + }); + this.on("removeListener", (name, listener) => { + if (name === RESTEvents.Response) + 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: RequestMethod.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: RequestMethod.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: RequestMethod.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: RequestMethod.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: RequestMethod.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); + } +}; +__name(REST, "REST"); + +// src/index.ts +var version = "[VI]{{inject}}[/VI]"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ALLOWED_EXTENSIONS, + ALLOWED_SIZES, + ALLOWED_STICKER_EXTENSIONS, + CDN, + DefaultRestOptions, + DefaultUserAgent, + DiscordAPIError, + HTTPError, + OverwrittenMimeTypes, + REST, + RESTEvents, + RateLimitError, + RequestManager, + RequestMethod, + makeURLSearchParams, + parseResponse, + version +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/rest/dist/index.js.map b/node_modules/@discordjs/rest/dist/index.js.map new file mode 100644 index 0000000..6e367ff --- /dev/null +++ b/node_modules/@discordjs/rest/dist/index.js.map @@ -0,0 +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\nexport const version = '[VI]{{inject}}[/VI]' 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, [VI]{{inject}}[/VI])` as `DiscordBot (https://discord.js.org, ${string})`;\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', '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","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, OverwrittenMimeTypes, 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\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\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, 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;;;;;;;;;;;;;;;;;;;;;;;ACCA,sBAAoB;;;ACDpB,0BAAoB;AACpB,iBAA2B;AAC3B,oBAAsB;AAGf,IAAMA,mBACZ;AAEM,IAAMC,qBAAqB;EACjC,IAAIC,QAAQ;AACX,WAAO,IAAIC,oBAAM;MAChBC,SAAS;QACRC,SAAS;MACV;IACD,CAAA;EACD;EACAC,KAAK;EACLC,YAAY;EACZC,KAAK;EACLC,SAAS,CAAC;EACVC,+BAA+B;EAC/BC,yBAAyB;EACzBC,QAAQ;EACRC,mBAAmB;EACnBC,SAAS;EACTT,SAAS;EACTU,mBAAmB,WAAWC,oBAAAA,QAAQC;EACtCA,SAASC;EACTC,mBAAmB;EACnBC,cAAc;EACdC,sBAAsB;AACvB;IAKO;UAAWC,aAAU;AAAVA,EAAAA,YACjBC,OAAAA,IAAQ;AADSD,EAAAA,YAEjBE,cAAAA,IAAe;AAFEF,EAAAA,YAGjBG,WAAAA,IAAY;AAHKH,EAAAA,YAIjBI,uBAAAA,IAAwB;AAJPJ,EAAAA,YAKjBK,aAAAA,IAAc;AALGL,EAAAA,YAMjBM,UAAAA,IAAW;GANMN,eAAAA,aAAAA,CAAAA,EAAAA;AASX,IAAMO,qBAAqB;EAAC;EAAQ;EAAO;EAAO;EAAQ;;AAC1D,IAAMC,6BAA6B;EAAC;EAAO;EAAQ;;AACnD,IAAMC,gBAAgB;EAAC;EAAI;EAAI;EAAI;EAAK;EAAK;EAAK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GAAGzB;MAASwB;MAAWE,QAAQC,cAAcG;IAAO,CAAA;EAC3E;;;;;;;EAQA,MAAaC,KAAKP,WAAsBxB,UAAuB,CAAC,GAAG;AAClE,WAAO,KAAKyB,QAAQ;MAAE,GAAGzB;MAASwB;MAAWE,QAAQC,cAAcK;IAAK,CAAA;EACzE;;;;;;;EAQA,MAAaC,IAAIT,WAAsBxB,UAAuB,CAAC,GAAG;AACjE,WAAO,KAAKyB,QAAQ;MAAE,GAAGzB;MAASwB;MAAWE,QAAQC,cAAcO;IAAI,CAAA;EACxE;;;;;;;EAQA,MAAaC,MAAMX,WAAsBxB,UAAuB,CAAC,GAAG;AACnE,WAAO,KAAKyB,QAAQ;MAAE,GAAGzB;MAASwB;MAAWE,QAAQC,cAAcS;IAAM,CAAA;EAC1E;;;;;;EAOA,MAAaX,QAAQzB,SAA0B;AAC9C,UAAMqC,WAAW,MAAM,KAAKC,IAAItC,OAAAA;AAChC,WAAOuC,cAAcF,QAAAA;EACtB;;;;;;EAOA,MAAaC,IAAItC,SAA0B;AAC1C,WAAO,KAAKI,eAAeoC,aAAaxC,OAAAA;EACzC;AACD;AArHaF;;;AT/NN,IAAM2C,UAAU;","names":["DefaultUserAgent","DefaultRestOptions","agent","Agent","connect","timeout","api","authPrefix","cdn","headers","invalidRequestWarningInterval","globalRequestsPerSecond","offset","rejectOnRateLimit","retries","userAgentAppendix","process","version","APIVersion","hashSweepInterval","hashLifetime","handlerSweepInterval","RESTEvents","Debug","HandlerSweep","HashSweep","InvalidRequestWarning","RateLimited","Response","ALLOWED_EXTENSIONS","ALLOWED_STICKER_EXTENSIONS","ALLOWED_SIZES","OverwrittenMimeTypes","CDN","base","DefaultRestOptions","cdn","appAsset","clientId","assetHash","options","makeURL","appIcon","iconHash","avatar","id","avatarHash","dynamicMakeURL","banner","bannerHash","channelIcon","channelId","defaultAvatar","discriminator","extension","discoverySplash","guildId","splashHash","emoji","emojiId","guildMemberAvatar","userId","guildMemberBanner","icon","roleIcon","roleId","roleIconHash","splash","sticker","stickerId","allowedExtensions","ALLOWED_STICKER_EXTENSIONS","stickerPackBanner","bannerId","teamIcon","teamId","guildScheduledEventCover","scheduledEventId","coverHash","route","hash","forceStatic","startsWith","ALLOWED_EXTENSIONS","size","String","toLowerCase","includes","RangeError","join","ALLOWED_SIZES","url","URL","searchParams","set","toString","isErrorGroupWrapper","error","Reflect","has","isErrorResponse","get","DiscordAPIError","Error","rawError","code","status","method","url","bodyData","getMessage","requestBody","files","json","body","name","flattened","errors","flattenDiscordError","join","message","error_description","obj","key","length","trim","otherKey","val","Object","entries","nextKey","startsWith","Number","isNaN","_errors","HTTPError","Error","status","method","url","bodyData","STATUS_CODES","name","requestBody","files","json","body","RateLimitError","Error","timeToReset","limit","method","hash","url","route","majorParameter","global","name","import_node_buffer","import_node_timers","import_undici","import_undici","import_node_url","import_undici","parseHeader","header","undefined","join","serializeSearchParam","value","toString","Date","Number","isNaN","getTime","toISOString","Object","prototype","makeURLSearchParams","options","params","URLSearchParams","key","entries","serialized","append","parseResponse","res","headers","startsWith","body","json","arrayBuffer","hasSublimit","bucketRoute","method","RequestMethod","Patch","castedBody","some","Reflect","has","resolveBody","types","isUint8Array","isArrayBuffer","Uint8Array","DataView","buffer","Blob","FormData","Symbol","iterator","chunks","length","reduce","a","b","uint8","lengthUsed","set","asyncIterator","chunk","push","Buffer","concat","TypeError","shouldRetry","error","name","code","message","includes","invalidCount","invalidCountResetTime","QueueType","Standard","Sublimit","SequentialHandler","manager","hash","majorParameter","reset","remaining","limit","Number","POSITIVE_INFINITY","AsyncQueue","id","inactive","limited","globalLimited","globalRemaining","Date","now","globalReset","localLimited","timeToReset","options","offset","debug","message","emit","RESTEvents","Debug","globalDelayFor","time","sleep","globalDelay","onRateLimit","rateLimitData","rejectOnRateLimit","shouldThrow","some","route","startsWith","toLowerCase","RateLimitError","queueRequest","routeId","url","requestData","queue","queueType","hasSublimit","bucketRoute","body","method","wait","signal","shift","promise","runRequest","resolve","retries","isGlobal","timeout","delay","globalRequestsPerSecond","global","RateLimited","controller","AbortController","setTimeout","abort","unref","aborted","addEventListener","res","request","error","Error","shouldRetry","clearTimeout","listenerCount","Response","path","original","data","status","statusCode","retryAfter","parseHeader","headers","retry","join","hashes","set","value","lastAccess","hashData","get","sublimitTimeout","undefined","emitInvalid","invalidRequestWarningInterval","InvalidRequestWarning","count","remainingTime","toString","firstSublimit","Promise","HTTPError","auth","setToken","parseResponse","DiscordAPIError","code","getFileType","lazy","RequestMethod","Delete","Get","Patch","Post","Put","RequestManager","EventEmitter","agent","globalDelay","globalReset","hashes","Collection","handlers","options","DefaultRestOptions","offset","Math","max","globalRemaining","globalRequestsPerSecond","setupSweepers","validateMaxInterval","interval","Error","hashSweepInterval","Number","POSITIVE_INFINITY","hashTimer","setInterval","sweptHashes","currentDate","Date","now","sweep","val","key","lastAccess","shouldSweep","floor","hashLifetime","set","emit","RESTEvents","Debug","value","HashSweep","unref","handlerSweepInterval","handlerTimer","sweptHandlers","inactive","id","HandlerSweep","setAgent","setToken","token","queueRequest","request","routeId","generateRouteData","fullRoute","method","hash","get","bucketRoute","handler","majorParameter","createHandler","url","fetchOptions","resolveRequest","body","files","auth","signal","queue","SequentialHandler","query","resolvedQuery","toString","headers","DefaultUserAgent","userAgentAppendix","trim","Authorization","authPrefix","reason","length","encodeURIComponent","api","versioned","version","finalBody","additionalHeaders","formData","FormData","index","file","entries","fileKey","Buffer","isBuffer","data","fileTypeFromBuffer","contentType","parsedType","mime","OverwrittenMimeTypes","append","Blob","type","name","appendToFormData","Object","JSON","stringify","passThroughBody","resolveBody","toUpperCase","undefined","dispatcher","clearHashSweeper","clearInterval","clearHandlerSweeper","endpoint","majorIdMatch","exec","majorId","baseRoute","replaceAll","replace","exceptions","timestamp","DiscordSnowflake","timestampFrom","original","import_node_events","REST","EventEmitter","options","cdn","CDN","DefaultRestOptions","requestManager","RequestManager","on","RESTEvents","Debug","emit","bind","RateLimited","InvalidRequestWarning","HashSweep","name","listener","Response","off","getAgent","agent","setAgent","setToken","token","get","fullRoute","request","method","RequestMethod","Get","delete","Delete","post","Post","put","Put","patch","Patch","response","raw","parseResponse","queueRequest","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/rest/dist/index.mjs b/node_modules/@discordjs/rest/dist/index.mjs new file mode 100644 index 0000000..de35a9e --- /dev/null +++ b/node_modules/@discordjs/rest/dist/index.mjs @@ -0,0 +1,1306 @@ +var __defProp = Object.defineProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + +// src/lib/CDN.ts +import { URL } from "node:url"; + +// src/lib/utils/constants.ts +import process from "node:process"; +import { APIVersion } from "discord-api-types/v10"; +import { Agent } from "undici"; +var DefaultUserAgent = `DiscordBot (https://discord.js.org, [VI]{{inject}}[/VI])`; +var DefaultRestOptions = { + get agent() { + return new Agent({ + connect: { + timeout: 3e4 + } + }); + }, + api: "https://discord.com/api", + authPrefix: "Bot", + cdn: "https://cdn.discordapp.com", + headers: {}, + invalidRequestWarningInterval: 0, + globalRequestsPerSecond: 50, + offset: 50, + rejectOnRateLimit: null, + retries: 3, + timeout: 15e3, + userAgentAppendix: `Node.js ${process.version}`, + version: APIVersion, + hashSweepInterval: 144e5, + hashLifetime: 864e5, + handlerSweepInterval: 36e5 +}; +var RESTEvents; +(function(RESTEvents2) { + RESTEvents2["Debug"] = "restDebug"; + RESTEvents2["HandlerSweep"] = "handlerSweep"; + RESTEvents2["HashSweep"] = "hashSweep"; + RESTEvents2["InvalidRequestWarning"] = "invalidRequestWarning"; + RESTEvents2["RateLimited"] = "rateLimited"; + RESTEvents2["Response"] = "response"; +})(RESTEvents || (RESTEvents = {})); +var ALLOWED_EXTENSIONS = [ + "webp", + "png", + "jpg", + "jpeg", + "gif" +]; +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" +}; + +// 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); + } + /** + * 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)) { + throw new RangeError(`Invalid extension provided: ${extension} +Must be one of: ${allowedExtensions.join(", ")}`); + } + if (size && !ALLOWED_SIZES.includes(size)) { + throw new RangeError(`Invalid size provided: ${size} +Must be one of: ${ALLOWED_SIZES.join(", ")}`); + } + const url = new URL(`${this.base}${route}.${extension}`); + if (size) { + url.searchParams.set("size", String(size)); + } + return url.toString(); + } +}; +__name(CDN, "CDN"); + +// src/lib/errors/DiscordAPIError.ts +function isErrorGroupWrapper(error) { + return Reflect.has(error, "_errors"); +} +__name(isErrorGroupWrapper, "isErrorGroupWrapper"); +function isErrorResponse(error) { + return typeof Reflect.get(error, "message") === "string"; +} +__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; + this.code = code; + this.status = status; + this.method = method; + this.url = url; + this.requestBody = { + files: bodyData.files, + json: bodyData.body + }; + } + /** + * The name of the error + */ + get name() { + return `${DiscordAPIError.name}[${this.code}]`; + } + static getMessage(error) { + let flattened = ""; + if ("code" in error) { + if (error.errors) { + flattened = [ + ...this.flattenDiscordError(error.errors) + ].join("\n"); + } + return error.message && flattened ? `${error.message} +${flattened}` : error.message || flattened || "Unknown Error"; + } + return error.error_description ?? "No Description"; + } + static *flattenDiscordError(obj, key = "") { + if (isErrorResponse(obj)) { + return yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim(); + } + for (const [otherKey, val] of Object.entries(obj)) { + const nextKey = otherKey.startsWith("_") ? key : key ? Number.isNaN(Number(otherKey)) ? `${key}.${otherKey}` : `${key}[${otherKey}]` : otherKey; + if (typeof val === "string") { + yield val; + } else if (isErrorGroupWrapper(val)) { + for (const error of val._errors) { + yield* this.flattenDiscordError(error, nextKey); + } + } else { + yield* this.flattenDiscordError(val, nextKey); + } + } + } +}; +__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; + this.method = method; + this.url = url; + this.name = HTTPError.name; + this.requestBody = { + files: bodyData.files, + json: bodyData.body + }; + } +}; +__name(HTTPError, "HTTPError"); + +// src/lib/errors/RateLimitError.ts +var RateLimitError = class extends Error { + constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }) { + super(); + this.timeToReset = timeToReset; + this.limit = limit; + this.method = method; + this.hash = hash; + this.url = url; + this.route = route; + this.majorParameter = majorParameter; + this.global = global; + } + /** + * The name of the error + */ + get name() { + return `${RateLimitError.name}[${this.route}]`; + } +}; +__name(RateLimitError, "RateLimitError"); + +// src/lib/RequestManager.ts +import { Blob as Blob2, Buffer as Buffer3 } from "node:buffer"; +import { EventEmitter } from "node:events"; +import { setInterval, clearInterval } from "node:timers"; +import { Collection } from "@discordjs/collection"; +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"; +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"; +import { URLSearchParams } from "node:url"; +import { types } from "node:util"; +import { FormData } from "undici"; +function parseHeader(header) { + if (header === void 0 || typeof header === "string") { + return header; + } + return header.join(";"); +} +__name(parseHeader, "parseHeader"); +function serializeSearchParam(value) { + switch (typeof value) { + case "string": + return value; + case "number": + case "bigint": + case "boolean": + return value.toString(); + case "object": + if (value === null) + return null; + if (value instanceof Date) { + return Number.isNaN(value.getTime()) ? null : value.toISOString(); + } + if (typeof value.toString === "function" && value.toString !== Object.prototype.toString) + return value.toString(); + return null; + default: + return null; + } +} +__name(serializeSearchParam, "serializeSearchParam"); +function makeURLSearchParams(options) { + const params = new URLSearchParams(); + if (!options) + return params; + for (const [key, value] of Object.entries(options)) { + const serialized = serializeSearchParam(value); + if (serialized !== null) + params.append(key, serialized); + } + return params; +} +__name(makeURLSearchParams, "makeURLSearchParams"); +async function parseResponse(res) { + const header = parseHeader(res.headers["content-type"]); + if (header?.startsWith("application/json")) { + return res.body.json(); + } + return res.body.arrayBuffer(); +} +__name(parseResponse, "parseResponse"); +function hasSublimit(bucketRoute, body, method) { + if (bucketRoute === "/channels/:id") { + if (typeof body !== "object" || body === null) + return false; + if (method !== RequestMethod.Patch) + return false; + const castedBody = body; + return [ + "name", + "topic" + ].some((key) => Reflect.has(castedBody, key)); + } + return true; +} +__name(hasSublimit, "hasSublimit"); +async function resolveBody(body) { + if (body == null) { + return null; + } else if (typeof body === "string") { + return body; + } else if (types.isUint8Array(body)) { + return body; + } else if (types.isArrayBuffer(body)) { + return new Uint8Array(body); + } else if (body instanceof URLSearchParams) { + return body.toString(); + } else if (body instanceof DataView) { + return new Uint8Array(body.buffer); + } else if (body instanceof Blob) { + return new Uint8Array(await body.arrayBuffer()); + } else if (body instanceof FormData) { + return body; + } else if (body[Symbol.iterator]) { + const chunks = [ + ...body + ]; + const length = chunks.reduce((a, b) => a + b.length, 0); + const uint8 = new Uint8Array(length); + let lengthUsed = 0; + return chunks.reduce((a, b) => { + a.set(b, lengthUsed); + lengthUsed += b.length; + return a; + }, uint8); + } else if (body[Symbol.asyncIterator]) { + const chunks = []; + for await (const chunk of body) { + chunks.push(chunk); + } + return Buffer2.concat(chunks); + } + throw new TypeError(`Unable to resolve body.`); +} +__name(resolveBody, "resolveBody"); +function shouldRetry(error) { + if (error.name === "AbortError") + return true; + return "code" in error && error.code === "ECONNRESET" || error.message.includes("ECONNRESET"); +} +__name(shouldRetry, "shouldRetry"); + +// src/lib/handlers/SequentialHandler.ts +var invalidCount = 0; +var invalidCountResetTime = null; +var QueueType; +(function(QueueType2) { + QueueType2[QueueType2["Standard"] = 0] = "Standard"; + QueueType2[QueueType2["Sublimit"] = 1] = "Sublimit"; +})(QueueType || (QueueType = {})); +var SequentialHandler = class { + /** + * The interface used to sequence async requests sequentially + */ + #asyncQueue; + /** + * The interface used to sequence sublimited async requests sequentially + */ + #sublimitedQueue; + /** + * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed + */ + #sublimitPromise; + /** + * Whether the sublimit queue needs to be shifted in the finally block + */ + #shiftSublimit; + /** + * @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.reset = -1; + this.remaining = 1; + this.limit = Number.POSITIVE_INFINITY; + this.#asyncQueue = new AsyncQueue(); + this.#sublimitedQueue = null; + this.#sublimitPromise = null; + this.#shiftSublimit = false; + this.id = `${hash}:${majorParameter}`; + } + /** + * {@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(RESTEvents.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); + this.manager.globalDelay = null; + } + /* + * Determines whether the request should be queued or whether a RateLimitError should be thrown + */ + 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; + if (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) { + queue = this.#sublimitedQueue; + queueType = 1; + } + await queue.wait({ + signal: requestData.signal + }); + if (queueType === 0) { + if (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) { + queue = this.#sublimitedQueue; + const wait = queue.wait(); + this.#asyncQueue.shift(); + await wait; + } else if (this.#sublimitPromise) { + await this.#sublimitPromise.promise; + } + } + try { + return await this.runRequest(routeId, url, options, requestData); + } finally { + queue.shift(); + if (this.#shiftSublimit) { + this.#shiftSublimit = false; + this.#sublimitedQueue?.shift(); + } + if (this.#sublimitedQueue?.remaining === 0) { + this.#sublimitPromise?.resolve(); + this.#sublimitedQueue = null; + } + } + } + /** + * 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 delay; + if (isGlobal) { + limit2 = this.manager.options.globalRequestsPerSecond; + timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + if (!this.manager.globalDelay) { + this.manager.globalDelay = this.globalDelayFor(timeout2); + } + delay = this.manager.globalDelay; + } else { + limit2 = this.limit; + timeout2 = this.timeToReset; + delay = sleep(timeout2); + } + const rateLimitData = { + timeToReset: timeout2, + limit: limit2, + method: options.method ?? "get", + hash: this.hash, + url, + route: routeId.bucketRoute, + majorParameter: this.majorParameter, + global: isGlobal + }; + this.manager.emit(RESTEvents.RateLimited, rateLimitData); + await this.onRateLimit(rateLimitData); + if (isGlobal) { + this.debug(`Global rate limit hit, blocking all requests for ${timeout2}ms`); + } else { + this.debug(`Waiting ${timeout2}ms for rate limit to pass`); + } + await delay; + } + if (!this.manager.globalReset || this.manager.globalReset < Date.now()) { + this.manager.globalReset = Date.now() + 1e3; + this.manager.globalRemaining = this.manager.options.globalRequestsPerSecond; + } + 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(RESTEvents.Response)) { + this.manager.emit(RESTEvents.Response, { + method, + path: routeId.original, + route: routeId.bucketRoute, + options, + data: requestData, + retries + }, { + ...res + }); + } + const status = res.statusCode; + let retryAfter = 0; + const limit = parseHeader(res.headers["x-ratelimit-limit"]); + const remaining = parseHeader(res.headers["x-ratelimit-remaining"]); + const reset = parseHeader(res.headers["x-ratelimit-reset-after"]); + const hash = parseHeader(res.headers["x-ratelimit-bucket"]); + const retry = parseHeader(res.headers["retry-after"]); + this.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY; + this.remaining = remaining ? Number(remaining) : 1; + this.reset = reset ? Number(reset) * 1e3 + Date.now() + this.manager.options.offset : Date.now(); + if (retry) + retryAfter = Number(retry) * 1e3 + this.manager.options.offset; + if (hash && hash !== this.hash) { + this.debug([ + "Received bucket hash update", + ` Old Hash : ${this.hash}`, + ` New Hash : ${hash}` + ].join("\n")); + this.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { + value: hash, + lastAccess: Date.now() + }); + } else if (hash) { + const hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`); + if (hashData) { + hashData.lastAccess = Date.now(); + } + } + let sublimitTimeout = null; + if (retryAfter > 0) { + if (res.headers["x-ratelimit-global"] !== void 0) { + this.manager.globalRemaining = 0; + this.manager.globalReset = Date.now() + retryAfter; + } else if (!this.localLimited) { + sublimitTimeout = retryAfter; + } + } + 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(RESTEvents.InvalidRequestWarning, { + count: invalidCount, + remainingTime: invalidCountResetTime - Date.now() + }); + } + } + if (status >= 200 && status < 300) { + return res; + } else if (status === 429) { + const isGlobal = this.globalLimited; + let limit2; + let timeout2; + if (isGlobal) { + limit2 = this.manager.options.globalRequestsPerSecond; + timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + } else { + limit2 = this.limit; + timeout2 = this.timeToReset; + } + await this.onRateLimit({ + timeToReset: timeout2, + limit: limit2, + method, + hash: this.hash, + url, + route: routeId.bucketRoute, + majorParameter: this.majorParameter, + global: isGlobal + }); + this.debug([ + "Encountered unexpected 429 rate limit", + ` Global : ${isGlobal.toString()}`, + ` Method : ${method}`, + ` URL : ${url}`, + ` Bucket : ${routeId.bucketRoute}`, + ` Major parameter: ${routeId.majorParameter}`, + ` Hash : ${this.hash}`, + ` Limit : ${limit2}`, + ` Retry After : ${retryAfter}ms`, + ` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : "None"}` + ].join("\n")); + if (sublimitTimeout) { + const firstSublimit = !this.#sublimitedQueue; + if (firstSublimit) { + this.#sublimitedQueue = new AsyncQueue(); + void this.#sublimitedQueue.wait(); + this.#asyncQueue.shift(); + } + this.#sublimitPromise?.resolve(); + this.#sublimitPromise = null; + await sleep(sublimitTimeout); + let resolve; + const promise = new Promise((res2) => resolve = res2); + this.#sublimitPromise = { + promise, + resolve + }; + if (firstSublimit) { + await this.#asyncQueue.wait(); + this.#shiftSublimit = true; + } + } + 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); + } + return res; + } + } +}; +__name(SequentialHandler, "SequentialHandler"); + +// src/lib/RequestManager.ts +var getFileType = lazy(async () => import("file-type")); +var RequestMethod; +(function(RequestMethod2) { + RequestMethod2["Delete"] = "DELETE"; + RequestMethod2["Get"] = "GET"; + RequestMethod2["Patch"] = "PATCH"; + RequestMethod2["Post"] = "POST"; + RequestMethod2["Put"] = "PUT"; +})(RequestMethod || (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 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; + constructor(options) { + super(); + this.options = { + ...DefaultRestOptions, + ...options + }; + this.options.offset = Math.max(0, this.options.offset); + this.globalRemaining = this.options.globalRequestsPerSecond; + this.agent = options.agent ?? null; + this.setupSweepers(); + } + setupSweepers() { + const validateMaxInterval = /* @__PURE__ */ __name((interval) => { + if (interval > 144e5) { + throw new Error("Cannot set an interval greater than 4 hours"); + } + }, "validateMaxInterval"); + if (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) { + validateMaxInterval(this.options.hashSweepInterval); + this.hashTimer = setInterval(() => { + const sweptHashes = new Collection(); + const currentDate = Date.now(); + this.hashes.sweep((val, key) => { + if (val.lastAccess === -1) + return false; + const shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime; + if (shouldSweep) { + sweptHashes.set(key, val); + } + this.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`); + return shouldSweep; + }); + this.emit(RESTEvents.HashSweep, sweptHashes); + }, this.options.hashSweepInterval).unref(); + } + if (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) { + validateMaxInterval(this.options.handlerSweepInterval); + this.handlerTimer = setInterval(() => { + const sweptHandlers = new Collection(); + this.handlers.sweep((val, key) => { + const { inactive } = val; + if (inactive) { + sweptHandlers.set(key, val); + } + this.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`); + return inactive; + }); + this.emit(RESTEvents.HandlerSweep, sweptHandlers); + }, 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}`) ?? { + value: `Global(${request2.method}:${routeId.bucketRoute})`, + lastAccess: -1 + }; + const handler = this.handlers.get(`${hash.value}:${routeId.majorParameter}`) ?? this.createHandler(hash.value, routeId.majorParameter); + const { url, fetchOptions } = await this.resolveRequest(request2); + return handler.queueRequest(routeId, url, fetchOptions, { + body: request2.body, + files: request2.files, + auth: request2.auth !== false, + 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); + 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 = ""; + if (request2.query) { + const resolvedQuery = request2.query.toString(); + if (resolvedQuery !== "") { + query = `?${resolvedQuery}`; + } + } + const headers = { + ...this.options.headers, + "User-Agent": `${DefaultUserAgent} ${options.userAgentAppendix}`.trim() + }; + if (request2.auth !== false) { + if (!this.#token) { + throw new Error("Expected token to be set for this request, but none was present"); + } + headers.Authorization = `${request2.authPrefix ?? this.options.authPrefix} ${this.#token}`; + } + if (request2.reason?.length) { + headers["X-Audit-Log-Reason"] = encodeURIComponent(request2.reason); + } + const url = `${options.api}${request2.versioned === false ? "" : `/v${options.version}`}${request2.fullRoute}${query}`; + let finalBody; + let additionalHeaders = {}; + if (request2.files?.length) { + const formData = new FormData2(); + for (const [index, file] of request2.files.entries()) { + const fileKey = file.key ?? `files[${index}]`; + if (Buffer3.isBuffer(file.data)) { + const { fileTypeFromBuffer } = await getFileType(); + 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); + } + } + if (request2.body != null) { + if (request2.appendToFormData) { + for (const [key, value] of Object.entries(request2.body)) { + formData.append(key, value); + } + } else { + formData.append("payload_json", JSON.stringify(request2.body)); + } + } + finalBody = formData; + } else if (request2.body != null) { + if (request2.passThroughBody) { + finalBody = request2.body; + } else { + finalBody = JSON.stringify(request2.body); + additionalHeaders = { + "Content-Type": "application/json" + }; + } + } + finalBody = await resolveBody(finalBody); + const fetchOptions = { + headers: { + ...request2.headers, + ...additionalHeaders, + ...headers + }, + method: request2.method.toUpperCase() + }; + if (finalBody !== void 0) { + fetchOptions.body = finalBody; + } + 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{17,19})/.exec(endpoint); + const majorId = majorIdMatch?.[1] ?? "global"; + const baseRoute = endpoint.replaceAll(/\d{17,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); + let exceptions = ""; + if (method === "DELETE" && baseRoute === "/channels/:id/messages/:id") { + 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"; + } + } + return { + majorParameter: majorId, + bucketRoute: baseRoute + exceptions, + original: endpoint + }; + } +}; +__name(RequestManager, "RequestManager"); + +// src/lib/REST.ts +import { EventEmitter as EventEmitter2 } from "node:events"; +var REST = class extends EventEmitter2 { + constructor(options = {}) { + super(); + this.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn); + this.requestManager = new RequestManager(options).on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug)).on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited)).on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning)).on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep)); + this.on("newListener", (name, listener) => { + if (name === RESTEvents.Response) + this.requestManager.on(name, listener); + }); + this.on("removeListener", (name, listener) => { + if (name === RESTEvents.Response) + 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: RequestMethod.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: RequestMethod.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: RequestMethod.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: RequestMethod.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: RequestMethod.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); + } +}; +__name(REST, "REST"); + +// src/index.ts +var version = "[VI]{{inject}}[/VI]"; +export { + ALLOWED_EXTENSIONS, + ALLOWED_SIZES, + ALLOWED_STICKER_EXTENSIONS, + CDN, + DefaultRestOptions, + DefaultUserAgent, + DiscordAPIError, + HTTPError, + OverwrittenMimeTypes, + REST, + RESTEvents, + RateLimitError, + RequestManager, + RequestMethod, + makeURLSearchParams, + parseResponse, + version +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/rest/dist/index.mjs.map b/node_modules/@discordjs/rest/dist/index.mjs.map new file mode 100644 index 0000000..7ef62e7 --- /dev/null +++ b/node_modules/@discordjs/rest/dist/index.mjs.map @@ -0,0 +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 * @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, [VI]{{inject}}[/VI])` as `DiscordBot (https://discord.js.org, ${string})`;\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', '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","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, OverwrittenMimeTypes, 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\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\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, 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\nexport const version = '[VI]{{inject}}[/VI]' as string;\n"],"mappings":";;;;AACA,SAASA,WAAW;;;ACDpB,OAAOC,aAAa;AACpB,SAASC,kBAAkB;AAC3B,SAASC,aAAa;AAGf,IAAMC,mBACZ;AAEM,IAAMC,qBAAqB;EACjC,IAAIC,QAAQ;AACX,WAAO,IAAIH,MAAM;MAChBI,SAAS;QACRC,SAAS;MACV;IACD,CAAA;EACD;EACAC,KAAK;EACLC,YAAY;EACZC,KAAK;EACLC,SAAS,CAAC;EACVC,+BAA+B;EAC/BC,yBAAyB;EACzBC,QAAQ;EACRC,mBAAmB;EACnBC,SAAS;EACTT,SAAS;EACTU,mBAAmB,WAAWjB,QAAQkB;EACtCA,SAASjB;EACTkB,mBAAmB;EACnBC,cAAc;EACdC,sBAAsB;AACvB;IAKO;UAAWC,aAAU;AAAVA,EAAAA,YACjBC,OAAAA,IAAQ;AADSD,EAAAA,YAEjBE,cAAAA,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AC5B;;;;;;EAOOC,SAASD,OAAmB;AAClC,SAAKf,eAAegB,SAASD,KAAAA;AAC7B,WAAO;EACR;;;;;;EAOOE,SAASC,OAAe;AAC9B,SAAKlB,eAAeiB,SAASC,KAAAA;AAC7B,WAAO;EACR;;;;;;;EAQA,MAAaC,IAAIC,WAAsBxB,UAAuB,CAAC,GAAG;AACjE,WAAO,KAAKyB,QAAQ;MAAE,GAAGzB;MAASwB;MAAWE,QAAQC,cAAcC;IAAI,CAAA;EACxE;;;;;;;EAQA,MAAaC,OAAOL,WAAsBxB,UAAuB,CAAC,GAAG;AACpE,WAAO,KAAKyB,QAAQ;MAAE,GAAGzB;MAASwB;MAAWE,QAAQC,cAAcG;IAAO,CAAA;EAC3E;;;;;;;EAQA,MAAaC,KAAKP,WAAsBxB,UAAuB,CAAC,GAAG;AAClE,WAAO,KAAKyB,QAAQ;MAAE,GAAGzB;MAASwB;MAAWE,QAAQC,cAAcK;IAAK,CAAA;EACzE;;;;;;;EAQA,MAAaC,IAAIT,WAAsBxB,UAAuB,CAAC,GAAG;AACjE,WAAO,KAAKyB,QAAQ;MAAE,GAAGzB;MAASwB;MAAWE,QAAQC,cAAcO;IAAI,CAAA;EACxE;;;;;;;EAQA,MAAaC,MAAMX,WAAsBxB,UAAuB,CAAC,GAAG;AACnE,WAAO,KAAKyB,QAAQ;MAAE,GAAGzB;MAASwB;MAAWE,QAAQC,cAAcS;IAAM,CAAA;EAC1E;;;;;;EAOA,MAAaX,QAAQzB,SAA0B;AAC9C,UAAMqC,WAAW,MAAM,KAAKC,IAAItC,OAAAA;AAChC,WAAOuC,cAAcF,QAAAA;EACtB;;;;;;EAOA,MAAaC,IAAItC,SAA0B;AAC1C,WAAO,KAAKI,eAAeoC,aAAaxC,OAAAA;EACzC;AACD;AArHaF;;;AC/NN,IAAM2C,UAAU;","names":["URL","process","APIVersion","Agent","DefaultUserAgent","DefaultRestOptions","agent","connect","timeout","api","authPrefix","cdn","headers","invalidRequestWarningInterval","globalRequestsPerSecond","offset","rejectOnRateLimit","retries","userAgentAppendix","version","hashSweepInterval","hashLifetime","handlerSweepInterval","RESTEvents","Debug","HandlerSweep","HashSweep","InvalidRequestWarning","RateLimited","Response","ALLOWED_EXTENSIONS","ALLOWED_STICKER_EXTENSIONS","ALLOWED_SIZES","OverwrittenMimeTypes","CDN","base","DefaultRestOptions","cdn","appAsset","clientId","assetHash","options","makeURL","appIcon","iconHash","avatar","id","avatarHash","dynamicMakeURL","banner","bannerHash","channelIcon","channelId","defaultAvatar","discriminator","extension","discoverySplash","guildId","splashHash","emoji","emojiId","guildMemberAvatar","userId","guildMemberBanner","icon","roleIcon","roleId","roleIconHash","splash","sticker","stickerId","allowedExtensions","ALLOWED_STICKER_EXTENSIONS","stickerPackBanner","bannerId","teamIcon","teamId","guildScheduledEventCover","scheduledEventId","coverHash","route","hash","forceStatic","startsWith","ALLOWED_EXTENSIONS","size","String","toLowerCase","includes","RangeError","join","ALLOWED_SIZES","url","URL","searchParams","set","toString","isErrorGroupWrapper","error","Reflect","has","isErrorResponse","get","DiscordAPIError","Error","rawError","code","status","method","url","bodyData","getMessage","requestBody","files","json","body","name","flattened","errors","flattenDiscordError","join","message","error_description","obj","key","length","trim","otherKey","val","Object","entries","nextKey","startsWith","Number","isNaN","_errors","STATUS_CODES","HTTPError","Error","status","method","url","bodyData","STATUS_CODES","name","requestBody","files","json","body","RateLimitError","Error","timeToReset","limit","method","hash","url","route","majorParameter","global","name","Blob","Buffer","EventEmitter","setInterval","clearInterval","Collection","lazy","DiscordSnowflake","FormData","setTimeout","clearTimeout","sleep","AsyncQueue","request","Blob","Buffer","URLSearchParams","types","FormData","parseHeader","header","undefined","join","serializeSearchParam","value","toString","Date","Number","isNaN","getTime","toISOString","Object","prototype","makeURLSearchParams","options","params","URLSearchParams","key","entries","serialized","append","parseResponse","res","headers","startsWith","body","json","arrayBuffer","hasSublimit","bucketRoute","method","RequestMethod","Patch","castedBody","some","Reflect","has","resolveBody","types","isUint8Array","isArrayBuffer","Uint8Array","DataView","buffer","Blob","FormData","Symbol","iterator","chunks","length","reduce","a","b","uint8","lengthUsed","set","asyncIterator","chunk","push","Buffer","concat","TypeError","shouldRetry","error","name","code","message","includes","invalidCount","invalidCountResetTime","QueueType","Standard","Sublimit","SequentialHandler","manager","hash","majorParameter","reset","remaining","limit","Number","POSITIVE_INFINITY","AsyncQueue","id","inactive","limited","globalLimited","globalRemaining","Date","now","globalReset","localLimited","timeToReset","options","offset","debug","message","emit","RESTEvents","Debug","globalDelayFor","time","sleep","globalDelay","onRateLimit","rateLimitData","rejectOnRateLimit","shouldThrow","some","route","startsWith","toLowerCase","RateLimitError","queueRequest","routeId","url","requestData","queue","queueType","hasSublimit","bucketRoute","body","method","wait","signal","shift","promise","runRequest","resolve","retries","isGlobal","timeout","delay","globalRequestsPerSecond","global","RateLimited","controller","AbortController","setTimeout","abort","unref","aborted","addEventListener","res","request","error","Error","shouldRetry","clearTimeout","listenerCount","Response","path","original","data","status","statusCode","retryAfter","parseHeader","headers","retry","join","hashes","set","value","lastAccess","hashData","get","sublimitTimeout","undefined","emitInvalid","invalidRequestWarningInterval","InvalidRequestWarning","count","remainingTime","toString","firstSublimit","Promise","HTTPError","auth","setToken","parseResponse","DiscordAPIError","code","getFileType","lazy","RequestMethod","Delete","Get","Patch","Post","Put","RequestManager","EventEmitter","agent","globalDelay","globalReset","hashes","Collection","handlers","options","DefaultRestOptions","offset","Math","max","globalRemaining","globalRequestsPerSecond","setupSweepers","validateMaxInterval","interval","Error","hashSweepInterval","Number","POSITIVE_INFINITY","hashTimer","setInterval","sweptHashes","currentDate","Date","now","sweep","val","key","lastAccess","shouldSweep","floor","hashLifetime","set","emit","RESTEvents","Debug","value","HashSweep","unref","handlerSweepInterval","handlerTimer","sweptHandlers","inactive","id","HandlerSweep","setAgent","setToken","token","queueRequest","request","routeId","generateRouteData","fullRoute","method","hash","get","bucketRoute","handler","majorParameter","createHandler","url","fetchOptions","resolveRequest","body","files","auth","signal","queue","SequentialHandler","query","resolvedQuery","toString","headers","DefaultUserAgent","userAgentAppendix","trim","Authorization","authPrefix","reason","length","encodeURIComponent","api","versioned","version","finalBody","additionalHeaders","formData","FormData","index","file","entries","fileKey","Buffer","isBuffer","data","fileTypeFromBuffer","contentType","parsedType","mime","OverwrittenMimeTypes","append","Blob","type","name","appendToFormData","Object","JSON","stringify","passThroughBody","resolveBody","toUpperCase","undefined","dispatcher","clearHashSweeper","clearInterval","clearHandlerSweeper","endpoint","majorIdMatch","exec","majorId","baseRoute","replaceAll","replace","exceptions","timestamp","DiscordSnowflake","timestampFrom","original","EventEmitter","REST","EventEmitter","options","cdn","CDN","DefaultRestOptions","requestManager","RequestManager","on","RESTEvents","Debug","emit","bind","RateLimited","InvalidRequestWarning","HashSweep","name","listener","Response","off","getAgent","agent","setAgent","setToken","token","get","fullRoute","request","method","RequestMethod","Get","delete","Delete","post","Post","put","Put","patch","Patch","response","raw","parseResponse","queueRequest","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/rest/package.json b/node_modules/@discordjs/rest/package.json new file mode 100644 index 0000000..3dba4a4 --- /dev/null +++ b/node_modules/@discordjs/rest/package.json @@ -0,0 +1,86 @@ +{ + "name": "@discordjs/rest", + "version": "1.6.0", + "description": "The REST API for discord.js", + "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", + "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": { + "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 ", + "Aura Román " + ], + "license": "Apache-2.0", + "keywords": [ + "discord", + "api", + "rest", + "discordapp", + "discordjs" + ], + "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": { + "@discordjs/collection": "^1.4.0", + "@discordjs/util": "^0.2.0", + "@sapphire/async-queue": "^1.5.0", + "@sapphire/snowflake": "^3.4.0", + "discord-api-types": "^0.37.35", + "file-type": "^18.2.1", + "tslib": "^2.5.0", + "undici": "^5.20.0" + }, + "devDependencies": { + "@favware/cliff-jumper": "^1.10.0", + "@microsoft/api-extractor": "^7.34.4", + "@types/node": "16.18.13", + "@vitest/coverage-c8": "^0.29.1", + "cross-env": "^7.0.3", + "esbuild-plugin-version-injector": "^1.0.3", + "eslint": "^8.35.0", + "eslint-config-neon": "^0.1.40", + "eslint-formatter-pretty": "^4.1.0", + "prettier": "^2.8.4", + "tsup": "^6.6.3", + "typescript": "^4.9.5", + "vitest": "^0.29.1" + }, + "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 new file mode 100644 index 0000000..8475f50 --- /dev/null +++ b/node_modules/@discordjs/util/CHANGELOG.md @@ -0,0 +1,21 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@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 + +- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3)) diff --git a/node_modules/@discordjs/util/LICENSE b/node_modules/@discordjs/util/LICENSE new file mode 100644 index 0000000..e2822e9 --- /dev/null +++ b/node_modules/@discordjs/util/LICENSE @@ -0,0 +1,190 @@ + 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 2022 Noel Buechler + + 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/util/README.md b/node_modules/@discordjs/util/README.md new file mode 100644 index 0000000..3dccc57 --- /dev/null +++ b/node_modules/@discordjs/util/README.md @@ -0,0 +1,60 @@ +
+
+

+ discord.js +

+
+

+ Discord server + Build status +

+

+ Vercel +

+
+ +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh-session +npm install @discordjs/util +yarn add @discordjs/util +pnpm add @discordjs/util +``` + +## 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. +- [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/util +[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 new file mode 100644 index 0000000..b26d972 --- /dev/null +++ b/node_modules/@discordjs/util/dist/index.d.ts @@ -0,0 +1,104 @@ +/** + * Represents a type that may or may not be a promise + */ +type Awaitable = PromiseLike | T; + +/** + * Lazy is a wrapper around a value that is computed lazily. It is useful for + * cases where the value is expensive to compute and the computation may not + * be needed at all. + * + * @param cb - The callback to lazily evaluate + * @typeParam T - The type of the value + * @example + * ```ts + * const value = lazy(() => computeExpensiveValue()); + * ``` + */ +declare function lazy(cb: () => T): () => T; + +/** + * 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 + * + * @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 + * for (const number of range(5)) { + * console.log(number); + * } + * // Prints 0, 1, 2, 3, 4 + * ``` + * @example + * Range with a step + * ```ts + * for (const number of range({ start: 3, end: 10, step: 2 })) { + * console.log(number); + * } + * // Prints 3, 5, 7, 9 + * ``` + */ +declare function range(range: RangeOptions | number): Generator; + +declare function calculateShardId(guildId: string, shardCount: number): number; + +/** + * Represents an object capable of representing itself as a JSON object + * + * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs. + */ +interface JSONEncodable { + /** + * Transforms this object to its JSON format + */ + toJSON(): T; +} +/** + * Indicates if an object is encodable or not. + * + * @param maybeEncodable - The object to check against + */ +declare function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable; + +/** + * Represents a structure that can be checked against another + * given structure for equality + * + * @typeParam T - The type of object to compare the current object to + */ +interface Equatable { + /** + * Whether or not this is equal to another structure + */ + equals(other: T): boolean; +} +/** + * Indicates if an object is equatable or not. + * + * @param maybeEquatable - The object to check against + */ +declare function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable; + +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 new file mode 100644 index 0000000..f1c295c --- /dev/null +++ b/node_modules/@discordjs/util/dist/index.js @@ -0,0 +1,82 @@ +"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, { + calculateShardId: () => calculateShardId, + isEquatable: () => isEquatable, + isJSONEncodable: () => isJSONEncodable, + lazy: () => lazy, + range: () => range +}); +module.exports = __toCommonJS(src_exports); + +// src/functions/lazy.ts +function lazy(cb) { + let defaultValue; + return () => defaultValue ??= cb(); +} +__name(lazy, "lazy"); + +// src/functions/range.ts +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) % BigInt(shardCount)); +} +__name(calculateShardId, "calculateShardId"); + +// src/JSONEncodable.ts +function isJSONEncodable(maybeEncodable) { + return maybeEncodable !== null && typeof maybeEncodable === "object" && "toJSON" in maybeEncodable; +} +__name(isJSONEncodable, "isJSONEncodable"); + +// src/Equatable.ts +function isEquatable(maybeEquatable) { + return maybeEquatable !== null && typeof maybeEquatable === "object" && "equals" in maybeEquatable; +} +__name(isEquatable, "isEquatable"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + calculateShardId, + isEquatable, + isJSONEncodable, + lazy, + range +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/util/dist/index.js.map b/node_modules/@discordjs/util/dist/index.js.map new file mode 100644 index 0000000..08d524c --- /dev/null +++ b/node_modules/@discordjs/util/dist/index.js.map @@ -0,0 +1 @@ +{"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","export function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number((BigInt(guildId) >> 22n) % BigInt(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;;;;;;;;;;;ACaO,SAASA,KAAQC,IAAsB;AAC7C,MAAIC;AAEJ,SAAO,MAAOA,iBAAiBD,GAAAA;AAChC;AAJgBD;;;AC+BT,UAAUG,MAAMA,QAA8B;AACpD,MAAIC;AACJ,MAAIC,QAAQ;AACZ,MAAIC,OAAO;AAEX,MAAI,OAAOH,WAAU,UAAU;AAC9BC,eAAWD;EACZ,OAAO;AACNE,YAAQF,OAAME;AACdD,eAAWD,OAAMI;AACjBD,WAAOH,OAAMG,QAAQ;EACtB;AAEA,WAASE,QAAQH,OAAOG,QAAQJ,UAAUI,SAASF,MAAM;AACxD,UAAME;EACP;AACD;AAhBiBL;;;AC5CV,SAASM,iBAAiBC,SAAiBC,YAAoB;AACrE,SAAOC,QAAQC,OAAOH,OAAAA,KAAY,OAAOG,OAAOF,UAAAA,CAAAA;AACjD;AAFgBF;;;ACiBT,SAASK,gBAAgBC,gBAAmE;AAClG,SAAOA,mBAAmB,QAAQ,OAAOA,mBAAmB,YAAY,YAAYA;AACrF;AAFgBD;;;ACCT,SAASE,YAAYC,gBAA+D;AAC1F,SAAOA,mBAAmB,QAAQ,OAAOA,mBAAmB,YAAY,YAAYA;AACrF;AAFgBD;","names":["lazy","cb","defaultValue","range","rangeEnd","start","step","end","index","calculateShardId","guildId","shardCount","Number","BigInt","isJSONEncodable","maybeEncodable","isEquatable","maybeEquatable"]} \ No newline at end of file diff --git a/node_modules/@discordjs/util/dist/index.mjs b/node_modules/@discordjs/util/dist/index.mjs new file mode 100644 index 0000000..480aa6b --- /dev/null +++ b/node_modules/@discordjs/util/dist/index.mjs @@ -0,0 +1,53 @@ +var __defProp = Object.defineProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + +// src/functions/lazy.ts +function lazy(cb) { + let defaultValue; + return () => defaultValue ??= cb(); +} +__name(lazy, "lazy"); + +// src/functions/range.ts +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) % BigInt(shardCount)); +} +__name(calculateShardId, "calculateShardId"); + +// src/JSONEncodable.ts +function isJSONEncodable(maybeEncodable) { + return maybeEncodable !== null && typeof maybeEncodable === "object" && "toJSON" in maybeEncodable; +} +__name(isJSONEncodable, "isJSONEncodable"); + +// src/Equatable.ts +function isEquatable(maybeEquatable) { + return maybeEquatable !== null && typeof maybeEquatable === "object" && "equals" in maybeEquatable; +} +__name(isEquatable, "isEquatable"); +export { + calculateShardId, + isEquatable, + isJSONEncodable, + lazy, + range +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/util/dist/index.mjs.map b/node_modules/@discordjs/util/dist/index.mjs.map new file mode 100644 index 0000000..e0c47d7 --- /dev/null +++ b/node_modules/@discordjs/util/dist/index.mjs.map @@ -0,0 +1 @@ +{"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","export function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number((BigInt(guildId) >> 22n) % BigInt(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,SAASA,KAAQC,IAAsB;AAC7C,MAAIC;AAEJ,SAAO,MAAOA,iBAAiBD,GAAAA;AAChC;AAJgBD;;;AC+BT,UAAUG,MAAMA,QAA8B;AACpD,MAAIC;AACJ,MAAIC,QAAQ;AACZ,MAAIC,OAAO;AAEX,MAAI,OAAOH,WAAU,UAAU;AAC9BC,eAAWD;EACZ,OAAO;AACNE,YAAQF,OAAME;AACdD,eAAWD,OAAMI;AACjBD,WAAOH,OAAMG,QAAQ;EACtB;AAEA,WAASE,QAAQH,OAAOG,QAAQJ,UAAUI,SAASF,MAAM;AACxD,UAAME;EACP;AACD;AAhBiBL;;;AC5CV,SAASM,iBAAiBC,SAAiBC,YAAoB;AACrE,SAAOC,QAAQC,OAAOH,OAAAA,KAAY,OAAOG,OAAOF,UAAAA,CAAAA;AACjD;AAFgBF;;;ACiBT,SAASK,gBAAgBC,gBAAmE;AAClG,SAAOA,mBAAmB,QAAQ,OAAOA,mBAAmB,YAAY,YAAYA;AACrF;AAFgBD;;;ACCT,SAASE,YAAYC,gBAA+D;AAC1F,SAAOA,mBAAmB,QAAQ,OAAOA,mBAAmB,YAAY,YAAYA;AACrF;AAFgBD;","names":["lazy","cb","defaultValue","range","rangeEnd","start","step","end","index","calculateShardId","guildId","shardCount","Number","BigInt","isJSONEncodable","maybeEncodable","isEquatable","maybeEquatable"]} \ No newline at end of file diff --git a/node_modules/@discordjs/util/package.json b/node_modules/@discordjs/util/package.json new file mode 100644 index 0000000..c73a13c --- /dev/null +++ b/node_modules/@discordjs/util/package.json @@ -0,0 +1,78 @@ +{ + "name": "@discordjs/util", + "version": "0.2.0", + "description": "Utilities shared across Discord.js packages", + "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", + "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": { + "import": "./dist/index.mjs", + "require": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "directories": { + "lib": "src" + }, + "files": [ + "dist" + ], + "contributors": [ + "Crawl ", + "Amish Shah ", + "Vlad Frangu ", + "SpaceEEC ", + "Aura Román " + ], + "license": "Apache-2.0", + "keywords": [ + "api", + "bot", + "client", + "node", + "discordjs" + ], + "repository": { + "type": "git", + "url": "https://github.com/discordjs/discord.js.git" + }, + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" + }, + "homepage": "https://discord.js.org", + "devDependencies": { + "@favware/cliff-jumper": "^1.10.0", + "@microsoft/api-extractor": "^7.34.4", + "@types/node": "16.18.13", + "@vitest/coverage-c8": "^0.29.1", + "cross-env": "^7.0.3", + "eslint": "^8.35.0", + "eslint-config-neon": "^0.1.40", + "eslint-formatter-pretty": "^4.1.0", + "prettier": "^2.8.4", + "tsd": "^0.25.0", + "tsup": "^6.6.3", + "typescript": "^4.9.5", + "vitest": "^0.29.1" + }, + "engines": { + "node": ">=16.9.0" + }, + "publishConfig": { + "access": "public" + }, + "tsd": { + "directory": "__tests__/types" + } +} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/CHANGELOG.md b/node_modules/@discordjs/voice/CHANGELOG.md new file mode 100644 index 0000000..390c867 --- /dev/null +++ b/node_modules/@discordjs/voice/CHANGELOG.md @@ -0,0 +1,113 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@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 + +- **VoiceReceiver:** ParsePacket correctly (#8277) ([1a6ddbb](https://github.com/discordjs/discord.js/commit/1a6ddbbe7b99b5eff4617b99399965740c38490b)) +- **recorder-example:** Bump dependencies (#8123) ([10ba008](https://github.com/discordjs/discord.js/commit/10ba0080cc20c44389779416b6a8215603eca6ca)) +- **SpeakingMap:** Allow docgen to detect event name (#8236) ([c271e05](https://github.com/discordjs/discord.js/commit/c271e05223d84f643314be649344a2cfe514923f)) +- **codecov:** Use cobertura (#8235) ([fd1c240](https://github.com/discordjs/discord.js/commit/fd1c24036f3c1835b918a12be8760d46f80460ac)) +- **voice:** Re-add accidental removal of postbuild script ([f8739bd](https://github.com/discordjs/discord.js/commit/f8739bd9c0c691c9593761237189dc529ed0b0a3)) + +## Documentation + +- Add codecov coverage badge to readmes (#8226) ([f6db285](https://github.com/discordjs/discord.js/commit/f6db285c073898a749fe4591cbd4463d1896daf5)) +- Remove Music bot in voice examples (#8203) ([741b3c8](https://github.com/discordjs/discord.js/commit/741b3c8e279c1cc6ba862bc83299d369bc6c1bc6)) + +## Features + +- **builder:** Add max min length in string option (#8214) ([96c8d21](https://github.com/discordjs/discord.js/commit/96c8d21f95eb366c46ae23505ba9054f44821b25)) +- Add website documentation early mvp (#8183) ([d95197c](https://github.com/discordjs/discord.js/commit/d95197cc78593df4d0a8d1cc492b0e41b4ab58b8)) +- **docgen:** Proper event parsing for typescript ([d4b41dd](https://github.com/discordjs/discord.js/commit/d4b41dd0815b493b599d4f4d1b6dd18cd99f91ea)) +- **docgen:** Update typedoc ([b3346f4](https://github.com/discordjs/discord.js/commit/b3346f4b9b3d4f96443506643d4631dc1c6d7b21)) +- Website (#8043) ([127931d](https://github.com/discordjs/discord.js/commit/127931d1df7a2a5c27923c2f2151dbf3824e50cc)) +- **docgen:** Typescript support ([3279b40](https://github.com/discordjs/discord.js/commit/3279b40912e6aa61507bedb7db15a2b8668de44b)) +- Docgen package (#8029) ([8b979c0](https://github.com/discordjs/discord.js/commit/8b979c0245c42fd824d8e98745ee869f5360fc86)) +- Add scripts package for locally used scripts ([f2ae1f9](https://github.com/discordjs/discord.js/commit/f2ae1f9348bfd893332a9060f71a8a5f272a1b8b)) + +## Refactor + +- Move all the config files to root (#8033) ([769ea0b](https://github.com/discordjs/discord.js/commit/769ea0bfe78c4f1d413c6b397c604ffe91e39c6a)) + +## Typings + +- **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.8.0...@discordjs/voice@0.10.0) - (2022-06-04) + +## Bug Fixes + +- Fix some typos (#7393) ([92a04f4](https://github.com/discordjs/discord.js/commit/92a04f4d98f6c6760214034cc8f5a1eaa78893c7)) + +## Features + +- Support sodium-native lib for voice (#7698) ([f0d0242](https://github.com/discordjs/discord.js/commit/f0d0242c76a455bb7a5ea7bd95ca62907c7e9d62)) +- Add API v10 support (#7477) ([72577c4](https://github.com/discordjs/discord.js/commit/72577c4bfd02524a27afb6ff4aebba9301a690d3)) +- Add support for module: NodeNext in TS and ESM (#7598) ([8f1986a](https://github.com/discordjs/discord.js/commit/8f1986a6aa98365e09b00e84ad5f9f354ab61f3d)) +- **builders:** Add attachment command option type (#7203) ([ae0f35f](https://github.com/discordjs/discord.js/commit/ae0f35f51d68dfa5a7dc43d161ef9365171debdb)) + +## Styling + +- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629)) + +# [@discordjs/voice@0.8.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.7.5...@discordjs/voice@0.8.0) - (2022-01-24) + +## Refactor + +- PresenceUpdate and demuxProbe (#7248) ([1745973](https://github.com/discordjs/discord.js/commit/174597302408f13c5bb685e2fb02ae2137cb481d)) + +## Testing + +- **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)) diff --git a/node_modules/@discordjs/voice/LICENSE b/node_modules/@discordjs/voice/LICENSE new file mode 100644 index 0000000..1675b6c --- /dev/null +++ b/node_modules/@discordjs/voice/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 2022 Noel Buechler + Copyright 2020 Amish Shah + + 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/voice/README.md b/node_modules/@discordjs/voice/README.md new file mode 100644 index 0000000..6e01211 --- /dev/null +++ b/node_modules/@discordjs/voice/README.md @@ -0,0 +1,106 @@ +
+
+

+ 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. + +**Features:** + +- Send and receive\* audio in Discord voice-based channels +- A strong focus on reliability and predictable behaviour +- Horizontal scalability and libraries other than [discord.js](https://discord.js.org/) are supported with custom adapters +- A robust audio processing system that can handle a wide range of audio sources + +\*_Audio receive is not documented by Discord so stable support is not guaranteed_ + +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh-session +npm install @discordjs/voice +yarn add @discordjs/voice +pnpm add @discordjs/voice +``` + +## Dependencies + +This library has several optional dependencies to support a variety +of different platforms. Install one dependency from each of the +categories shown below. The dependencies are listed in order of +preference for performance. If you can't install one of the options, +try installing another. + +**Encryption Libraries (npm install):** + +- `sodium-native`: ^3.3.0 +- `sodium`: ^3.0.2 +- `tweetnacl`: ^1.0.3 +- `libsodium-wrappers`: ^0.7.9 + +**Opus Libraries (npm install):** + +- `@discordjs/opus`: ^0.4.0 +- `opusscript`: ^0.0.7 + +**FFmpeg:** + +- [`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][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. +- [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/voice +[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 new file mode 100644 index 0000000..7b1cdbd --- /dev/null +++ b/node_modules/@discordjs/voice/dist/index.d.ts @@ -0,0 +1,1636 @@ +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'; +import { GatewayVoiceServerUpdateDispatchData, GatewayVoiceStateUpdateDispatchData } from 'discord-api-types/v10'; + +/** + * The different types of stream that can exist within the pipeline. + * + * @remarks + * - `Arbitrary` - the type of the stream at this point is unknown. + * - `Raw` - the stream at this point is s16le PCM. + * - `OggOpus` - the stream at this point is Opus audio encoded in an Ogg wrapper. + * - `WebmOpus` - the stream at this point is Opus audio encoded in a WebM wrapper. + * - `Opus` - the stream at this point is Opus audio, and the stream is in object-mode. This is ready to play. + */ +declare enum StreamType { + Arbitrary = "arbitrary", + OggOpus = "ogg/opus", + Opus = "opus", + Raw = "raw", + WebmOpus = "webm/opus" +} +/** + * The different types of transformers that can exist within the pipeline. + */ +declare enum TransformerType { + FFmpegOgg = "ffmpeg ogg", + FFmpegPCM = "ffmpeg pcm", + InlineVolume = "volume transformer", + OggOpusDemuxer = "ogg/opus demuxer", + 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; + transformer(input: Readable | string): Readable; + type: TransformerType; +} +/** + * Represents a type of stream within the graph, e.g. an Opus stream, or a stream of raw audio. + */ +declare class Node { + /** + * The outbound edges from this node. + */ + readonly edges: Edge[]; + /** + * The type of stream for this node. + */ + readonly type: StreamType; + constructor(type: StreamType); + /** + * Creates an outbound edge from this node. + * + * @param edge - The edge to create + */ + addEdge(edge: Omit): void; +} + +/** + * Options that are set when creating a new 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`. + */ + inputType?: StreamType; + /** + * Optional metadata that can be attached to the resource (e.g. track title, random id). + * This is useful for identification purposes when the resource is passed around in events. + * See {@link AudioResource.metadata} + */ + metadata?: T; + /** + * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches. + * Defaults to 5. + */ + silencePaddingFrames?: number; +} +/** + * Represents an audio resource that can be played by an audio player. + * + * @typeParam T - the type for the metadata (if any) of the audio resource + */ +declare class AudioResource { + /** + * An object-mode Readable stream that emits Opus packets. This is what is played by audio players. + */ + readonly playStream: Readable; + /** + * 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. + */ + readonly edges: readonly Edge[]; + /** + * Optional metadata that can be used to identify the resource. + */ + metadata: T; + /** + * 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. + */ + readonly volume?: prism.VolumeTransformer; + /** + * 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. + */ + readonly encoder?: prism.opus.Encoder; + /** + * The audio player that the resource is subscribed to, if any. + */ + audioPlayer?: AudioPlayer | undefined; + /** + * The playback duration of this audio resource, given in milliseconds. + */ + playbackDuration: number; + /** + * Whether or not the stream for this resource has started (data has become readable) + */ + started: boolean; + /** + * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches. + */ + readonly silencePaddingFrames: number; + /** + * The number of remaining silence frames to play. If -1, the frames have not yet started playing. + */ + silenceRemaining: number; + constructor(edges: readonly Edge[], streams: readonly Readable[], metadata: T, silencePaddingFrames: number); + /** + * 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(): boolean; + /** + * Whether this resource has ended or not. + */ + get ended(): boolean; + /** + * 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(): Buffer | null; +} +/** + * Creates an audio resource that can be played by audio players. + * + * @remarks + * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used. + * + * 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 + * @typeParam T - the type for the metadata (if any) of the audio resource + */ +declare function createAudioResource(input: Readable | string, options: CreateAudioResourceOptions & Pick : Required>, 'metadata'>): AudioResource; +/** + * Creates an audio resource that can be played by audio players. + * + * @remarks + * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used. + * + * 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 + * @typeParam T - the type for the metadata (if any) of the audio resource + */ +declare function createAudioResource(input: Readable | string, options?: Omit, 'metadata'>): AudioResource; + +/** + * An error emitted by an AudioPlayer. Contains an attached resource to aid with + * debugging and identifying where the error came from. + */ +declare class AudioPlayerError extends Error { + /** + * The resource associated with the audio player at the time the error was thrown. + */ + readonly resource: AudioResource; + constructor(error: Error, resource: AudioResource); +} + +/** + * Represents a subscription of a voice connection to an audio player, allowing + * the audio player to play audio on the voice connection. + */ +declare class PlayerSubscription { + /** + * The voice connection of this subscription. + */ + readonly connection: VoiceConnection; + /** + * The audio player of this subscription. + */ + readonly player: AudioPlayer; + constructor(connection: VoiceConnection, player: AudioPlayer); + /** + * Unsubscribes the connection from the audio player, meaning that the + * audio player cannot stream audio to it until a new subscription is made. + */ + unsubscribe(): void; +} + +/** + * Describes the behavior of the player when an audio packet is played but there are no available + * voice connections to play to. + */ +declare enum NoSubscriberBehavior { + /** + * Pauses playing the stream until a voice connection becomes available. + */ + Pause = "pause", + /** + * Continues to play through the resource regardless. + */ + Play = "play", + /** + * The player stops and enters the Idle state. + */ + Stop = "stop" +} +declare enum AudioPlayerStatus { + /** + * When the player has paused itself. Only possible with the "pause" no subscriber behavior. + */ + 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. + */ + Paused = "paused", + /** + * When the player is actively playing an audio resource. + */ + Playing = "playing" +} +/** + * Options that can be passed when creating an audio player, used to specify its behavior. + */ +interface CreateAudioPlayerOptions { + behaviors?: { + 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. + */ +interface AudioPlayerIdleState { + status: AudioPlayerStatus.Idle; +} +/** + * The state that an AudioPlayer is in when it is waiting for a resource to become readable. Once this + * happens, the AudioPlayer will enter the Playing state. If the resource ends/errors before this, then + * it will re-enter the Idle state. + */ +interface AudioPlayerBufferingState { + onFailureCallback: () => void; + onReadableCallback: () => void; + onStreamError: (error: Error) => void; + /** + * The resource that the AudioPlayer is waiting for + */ + resource: AudioResource; + 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 { + /** + * 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. + */ + playbackDuration: number; + /** + * The resource that is being played. + */ + resource: AudioResource; + 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 { + 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. + */ + playbackDuration: number; + /** + * The current resource of the audio player. + */ + resource: AudioResource; + /** + * 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. + */ +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 + * + * @eventProperty + */ + on(event: 'error', listener: (error: AudioPlayerError) => void): this; + /** + * Emitted debugging information about the audio player + * + * @eventProperty + */ + on(event: 'debug', listener: (message: string) => void): this; + /** + * Emitted when the state of the audio player changes + * + * @eventProperty + */ + on(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this; + /** + * Emitted when the audio player is subscribed to a voice connection + * + * @eventProperty + */ + on(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this; + /** + * Emitted when the status of state changes to a specific status + * + * @eventProperty + */ + on(event: T, listener: (oldState: AudioPlayerState, newState: AudioPlayerState & { + status: T; + }) => void): this; +} +/** + * Used to play audio resources (i.e. tracks, streams) to voice connections. + * + * @remarks + * Audio players are designed to be re-used - even if a resource has finished playing, the player itself + * can still be used. + * + * The AudioPlayer drives the timing of playback, and therefore is unaffected by voice connections + * becoming unavailable. Its behavior in these scenarios can be configured. + */ +declare class AudioPlayer extends EventEmitter { + /** + * The state that the AudioPlayer is in. + */ + private _state; + /** + * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio + * to the streams in this list. + */ + private readonly subscribers; + /** + * The behavior that the player should follow when it enters certain situations. + */ + private readonly behaviors; + /** + * The debug logger function, if debugging is enabled. + */ + private readonly debug; + /** + * Creates a new AudioPlayer. + */ + constructor(options?: CreateAudioPlayerOptions); + /** + * A list of subscribed voice connections that can currently receive audio to play. + */ + get playable(): VoiceConnection[]; + /** + * 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 + */ + private subscribe; + /** + * 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 + */ + private unsubscribe; + /** + * The state that the player is in. + */ + get state(): AudioPlayerState; + /** + * Sets a new state for the player, performing clean-up operations where necessary. + */ + set state(newState: AudioPlayerState); + /** + * 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: AudioResource): void; + /** + * 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; + /** + * Unpauses playback of the current resource, if any. + * + * @returns `true` if the player was successfully unpaused, otherwise `false` + */ + unpause(): boolean; + /** + * 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?: boolean): boolean; + /** + * Checks whether the underlying resource (if any) is playable (readable) + * + * @returns `true` if the resource is playable, otherwise `false` + */ + checkPlayable(): boolean; + /** + * 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. + */ + private _stepDispatch; + /** + * 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. + */ + private _stepPrepare; + /** + * 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. + */ + private _signalStopSpeaking; + /** + * 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 + */ + private _preparePacket; +} +/** + * Creates a new AudioPlayer to be used. + */ +declare function createAudioPlayer(options?: CreateAudioPlayerOptions): AudioPlayer; + +interface JoinConfig { + channelId: string | null; + group: string; + guildId: string; + selfDeaf: boolean; + selfMute: boolean; +} +/** + * Retrieves the map of group names to maps of voice connections. By default, all voice connections + * are created under the 'default' group. + * + * @returns The group map + */ +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; +/** + * Retrieves all the voice connections under the given group name. + * + * @param group - The group to look up + * @returns The map of voice connections + */ +declare function getVoiceConnections(group: string): Map | undefined; +/** + * Finds a voice connection with the given guild id and group. Defaults to the 'default' group. + * + * @param guildId - The guild id of the voice connection + * @param group - the group that the voice connection was registered with + * @returns The voice connection, if it exists + */ +declare function getVoiceConnection(guildId: string, group?: string): VoiceConnection | undefined; + +/** + * Stores an IP address and port. Used to store socket details for the local client as well as + * for Discord. + */ +interface SocketConfig { + ip: string; + port: number; +} +interface VoiceUDPSocket extends EventEmitter { + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'debug', listener: (message: string) => void): this; + on(event: 'message', listener: (message: Buffer) => void): this; +} +/** + * Manages the UDP networking for a voice connection. + */ +declare class VoiceUDPSocket extends EventEmitter { + /** + * The underlying network Socket for the VoiceUDPSocket. + */ + private readonly socket; + /** + * The socket details for Discord (remote) + */ + private readonly remote; + /** + * The counter used in the keep alive mechanism. + */ + private keepAliveCounter; + /** + * The buffer used to write the keep alive counter into. + */ + private readonly keepAliveBuffer; + /** + * The Node.js interval for the keep-alive mechanism. + */ + 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; + /** + * Creates a new VoiceUDPSocket. + * + * @param remote - Details of the remote socket + */ + constructor(remote: SocketConfig); + /** + * Called when a message is received on the UDP socket. + * + * @param buffer - The received buffer + */ + private onMessage; + /** + * Called at a regular interval to check whether we are still able to send datagrams to Discord. + */ + private keepAlive; + /** + * Sends a buffer to Discord. + * + * @param buffer - The buffer to send + */ + send(buffer: Buffer): void; + /** + * Closes the socket, the instance will not be able to be reused. + */ + destroy(): void; + /** + * Performs IP discovery to discover the local address and port to be used for the voice connection. + * + * @param ssrc - The SSRC received from Discord + */ + performIPDiscovery(ssrc: number): Promise; +} + +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. + * + * @eventProperty + */ + on(event: 'debug', listener: (message: string) => void): this; + /** + * Packet event. + * + * @eventProperty + */ + on(event: 'packet', listener: (packet: any) => void): this; +} +/** + * An extension of the WebSocket class to provide helper functionality when interacting + * with the Discord Voice gateway. + */ +declare class VoiceWebSocket extends EventEmitter { + /** + * The current heartbeat interval, if any. + */ + private 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. + */ + private 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. + */ + private lastHeartbeatSend; + /** + * The number of consecutively missed heartbeats. + */ + private missedHeartbeats; + /** + * The last recorded ping. + */ + ping?: number; + /** + * The debug logger function, if debugging is enabled. + */ + private readonly debug; + /** + * The underlying WebSocket of this wrapper. + */ + private readonly ws; + /** + * Creates a new VoiceWebSocket. + * + * @param address - The address to connect to + */ + constructor(address: string, debug: boolean); + /** + * Destroys the VoiceWebSocket. The heartbeat interval is cleared, and the connection is closed. + */ + destroy(): void; + /** + * Handles message events on the WebSocket. Attempts to JSON parse the messages and emit them + * as packets. + * + * @param event - The message event + */ + onMessage(event: MessageEvent): void; + /** + * Sends a JSON-stringifiable packet over the WebSocket. + * + * @param packet - The packet to send + */ + sendPacket(packet: any): void; + /** + * Sends a heartbeat over the WebSocket. + */ + private sendHeartbeat; + /** + * 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: number): void; +} + +/** + * The different statuses that a networking instance can hold. The order + * of the states between OpeningWs and Ready is chronological (first the + * instance enters OpeningWs, then it enters Identifying etc.) + */ +declare enum NetworkingStatusCode { + OpeningWs = 0, + Identifying = 1, + UdpHandshaking = 2, + SelectingProtocol = 3, + Ready = 4, + Resuming = 5, + Closed = 6 +} +/** + * The initial Networking state. Instances will be in this state when a WebSocket connection to a Discord + * voice gateway is being opened. + */ +interface NetworkingOpeningWsState { + code: NetworkingStatusCode.OpeningWs; + 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; + connectionOptions: ConnectionOptions; + ws: VoiceWebSocket; +} +/** + * The state that a Networking instance will be in when opening a UDP connection to the IP and port provided + * by Discord, as well as performing IP discovery. + */ +interface NetworkingUdpHandshakingState { + code: NetworkingStatusCode.UdpHandshaking; + 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; + 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 + * voice server. + */ +interface NetworkingReadyState { + code: NetworkingStatusCode.Ready; + connectionData: ConnectionData; + 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 + * is attempting to resume an existing session. + */ +interface NetworkingResumingState { + code: NetworkingStatusCode.Resuming; + connectionData: ConnectionData; + 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 + * state. + */ +interface NetworkingClosedState { + code: NetworkingStatusCode.Closed; +} +/** + * The various states that a networking instance can be in. + */ +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; + sessionId: string; + token: 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 { + encryptionMode: string; + nonce: number; + nonceBuffer: Buffer; + packetsPlayed: number; + secretKey: Uint8Array; + sequence: number; + speaking: boolean; + ssrc: number; + timestamp: number; +} +interface Networking extends EventEmitter { + /** + * Debug event for Networking. + * + * @eventProperty + */ + on(event: 'debug', listener: (message: string) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'stateChange', listener: (oldState: NetworkingState, newState: NetworkingState) => void): this; + on(event: 'close', listener: (code: number) => void): this; +} +/** + * Manages the networking required to maintain a voice connection and dispatch audio packets + */ +declare class Networking extends EventEmitter { + private _state; + /** + * The debug logger function, if debugging is enabled. + */ + private readonly debug; + /** + * Creates a new Networking instance. + */ + constructor(options: ConnectionOptions, debug: boolean); + /** + * Destroys the Networking instance, transitioning it into the Closed state. + */ + destroy(): void; + /** + * The current state of the networking instance. + */ + get state(): NetworkingState; + /** + * Sets a new state for the networking instance, performing clean-up operations where necessary. + */ + set state(newState: NetworkingState); + /** + * Creates a new WebSocket to a Discord Voice gateway. + * + * @param endpoint - The endpoint to connect to + */ + private createWebSocket; + /** + * Propagates errors from the children VoiceWebSocket and VoiceUDPSocket. + * + * @param error - The error that was emitted by a child + */ + private onChildError; + /** + * 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. + */ + private onWsOpen; + /** + * 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 + */ + private onWsClose; + /** + * Called when the UDP socket has closed itself if it has stopped receiving replies from Discord. + */ + private onUdpClose; + /** + * Called when a packet is received on the connection's WebSocket. + * + * @param packet - The received packet + */ + private onWsPacket; + /** + * Propagates debug messages from the child WebSocket. + * + * @param message - The emitted debug message + */ + private onWsDebug; + /** + * Propagates debug messages from the child UDPSocket. + * + * @param message - The emitted debug message + */ + private onUdpDebug; + /** + * 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: Buffer): Buffer | undefined; + /** + * Dispatches the audio packet previously prepared by prepareAudioPacket(opusPacket). The audio packet + * is consumed and cannot be dispatched again. + */ + dispatchAudio(): boolean; + /** + * Plays an audio packet, updating timing metadata used for playback. + * + * @param audioPacket - The audio packet to play + */ + private playAudioPacket; + /** + * 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: boolean): void; + /** + * 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 + */ + private createAudioPacket; + /** + * 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 + */ + private encryptOpusPacket; +} + +/** + * The different behaviors an audio receive stream can have for deciding when to end. + */ +declare enum EndBehaviorType { + /** + * The stream will only end when manually destroyed. + */ + Manual = 0, + /** + * The stream will end after a given time period of silence/no audio packets. + */ + AfterSilence = 1, + /** + * The stream will end after a given time period of no audio packets. + */ + AfterInactivity = 2 +} +type EndBehavior = { + behavior: EndBehaviorType.AfterInactivity | EndBehaviorType.AfterSilence; + duration: number; +} | { + behavior: EndBehaviorType.Manual; +}; +interface AudioReceiveStreamOptions extends ReadableOptions { + end: EndBehavior; +} +declare function createDefaultAudioReceiveStreamOptions(): AudioReceiveStreamOptions; +/** + * A readable stream of Opus packets received from a specific entity + * in a Discord voice connection. + */ +declare class AudioReceiveStream extends Readable { + /** + * The end behavior of the receive stream. + */ + readonly end: EndBehavior; + private endTimeout?; + constructor({ end, ...options }: AudioReceiveStreamOptions); + push(buffer: Buffer | null): boolean; + private renewEndTimeout; + _read(): void; +} + +/** + * The known data for a user in a Discord voice connection. + */ +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; +} +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; +} +/** + * Maps audio SSRCs to data of users in voice connections. + */ +declare class SSRCMap extends EventEmitter { + /** + * The underlying map. + */ + private readonly map; + constructor(); + /** + * Updates the map with new user data + * + * @param data - The data to update with + */ + update(data: VoiceUserData): void; + /** + * Gets the stored voice data of a user. + * + * @param target - The target, either their user id or audio SSRC + */ + get(target: number | string): VoiceUserData | undefined; + /** + * 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 { + /** + * Emitted when a user starts speaking. + * + * @eventProperty + */ + on(event: 'start', listener: (userId: string) => void): this; + /** + * Emitted when a user ends speaking. + * + * @eventProperty + */ + on(event: 'end', listener: (userId: string) => void): this; +} +/** + * Tracks the speaking states of users in a voice channel. + */ +declare class SpeakingMap extends EventEmitter { + /** + * The delay after a packet is received from a user until they're marked as not speaking anymore. + */ + static readonly DELAY = 100; + /** + * The currently speaking users, mapped to the milliseconds since UNIX epoch at which they started speaking. + */ + readonly users: Map; + private readonly speakingTimeouts; + constructor(); + onPacket(userId: string): void; + private startTimeout; +} + +/** + * Attaches to a VoiceConnection, allowing you to receive audio packets from other + * users that are speaking. + * + * @beta + */ +declare class VoiceReceiver { + /** + * The attached connection of this receiver. + */ + readonly voiceConnection: VoiceConnection; + /** + * Maps SSRCs to Discord user ids. + */ + readonly ssrcMap: SSRCMap; + /** + * The current audio subscriptions of this receiver. + */ + readonly subscriptions: Map; + /** + * The connection data of the receiver. + * + * @internal + */ + connectionData: Partial; + /** + * The speaking map of the receiver. + */ + readonly speaking: SpeakingMap; + constructor(voiceConnection: VoiceConnection); + /** + * Called when a packet is received on the attached connection's WebSocket. + * + * @param packet - The received packet + * @internal + */ + onWsPacket(packet: any): void; + private decrypt; + /** + * 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 + */ + private parsePacket; + /** + * Called when the UDP socket of the attached connection receives a message. + * + * @param msg - The received message + * @internal + */ + onUdpMessage(msg: Buffer): void; + /** + * 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; +} + +/** + * Methods that are provided by the \@discordjs/voice library to implementations of + * 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; + /** + * 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; +} +/** + * 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; +} +/** + * A function used to build adapters. It accepts a methods parameter that contains functions that + * can be called by the implementer when new data is received on its gateway connection. In return, + * 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. + */ +type DiscordGatewayAdapterCreator = (methods: DiscordGatewayAdapterLibraryMethods) => DiscordGatewayAdapterImplementerMethods; + +/** + * The various status codes a voice connection can hold at any one time. + */ +declare enum VoiceConnectionStatus { + /** + * The `VOICE_SERVER_UPDATE` and `VOICE_STATE_UPDATE` packets have been received, now attempting to establish a voice connection. + */ + Connecting = "connecting", + /** + * The voice connection has been destroyed and untracked, it cannot be reused. + */ + Destroyed = "destroyed", + /** + * The voice connection has either been severed or not established. + */ + Disconnected = "disconnected", + /** + * A voice connection has been established, and is ready to be used. + */ + 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 { + adapter: DiscordGatewayAdapterImplementerMethods; + status: VoiceConnectionStatus.Signalling; + subscription?: PlayerSubscription | undefined; +} +/** + * The reasons a voice connection can be in the disconnected state. + */ +declare enum VoiceConnectionDisconnectReason { + /** + * When the WebSocket connection has been closed. + */ + WebSocketClose = 0, + /** + * When the adapter was unable to send a message requested by the VoiceConnection. + */ + AdapterUnavailable = 1, + /** + * When a VOICE_SERVER_UPDATE packet is received with a null endpoint, causing the connection to be severed. + */ + EndpointRemoved = 2, + /** + * When a manual disconnect was requested. + */ + Manual = 3 +} +/** + * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is + * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect. + */ +interface VoiceConnectionDisconnectedBaseState { + 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 + * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect. + */ +interface VoiceConnectionDisconnectedOtherState extends VoiceConnectionDisconnectedBaseState { + reason: Exclude; +} +/** + * The state that a VoiceConnection will be in when its WebSocket connection was closed. + * You can manually attempt to reconnect using VoiceConnection#reconnect. + */ +interface VoiceConnectionDisconnectedWebSocketState extends VoiceConnectionDisconnectedBaseState { + /** + * 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. + */ +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 { + 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 { + 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 + * user and untracked by the library. It cannot be reconnected, instead, a new VoiceConnection + * needs to be established. + */ +interface VoiceConnectionDestroyedState { + status: VoiceConnectionStatus.Destroyed; +} +/** + * The various states that a voice connection can be in. + */ +type VoiceConnectionState = VoiceConnectionConnectingState | VoiceConnectionDestroyedState | VoiceConnectionDisconnectedState | VoiceConnectionReadyState | VoiceConnectionSignallingState; +interface VoiceConnection extends EventEmitter { + /** + * Emitted when there is an error emitted from the voice connection + * + * @eventProperty + */ + on(event: 'error', listener: (error: Error) => void): this; + /** + * Emitted debugging information about the voice connection + * + * @eventProperty + */ + on(event: 'debug', listener: (message: string) => void): this; + /** + * Emitted when the state of the voice connection changes + * + * @eventProperty + */ + on(event: 'stateChange', listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState) => void): this; + /** + * Emitted when the state of the voice connection changes to a specific status + * + * @eventProperty + */ + on(event: T, listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState & { + status: T; + }) => void): this; +} +/** + * A connection to the voice server of a Guild, can be used to play audio in voice channels. + */ +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. + */ + rejoinAttempts: number; + /** + * The state of the voice connection. + */ + private _state; + /** + * A configuration storing all the data needed to reconnect to a Guild's voice server. + * + * @internal + */ + readonly joinConfig: 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. + */ + private readonly packets; + /** + * The receiver of this voice connection. You should join the voice channel with `selfDeaf` set + * to false for this feature to work properly. + */ + readonly receiver: VoiceReceiver; + /** + * The debug logger function, if debugging is enabled. + */ + private readonly 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: JoinConfig, options: CreateVoiceConnectionOptions); + /** + * The current state of the voice connection. + */ + get state(): VoiceConnectionState; + /** + * Updates the state of the voice connection, performing clean-up operations where necessary. + */ + set state(newState: VoiceConnectionState); + /** + * 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 + */ + private addServerPacket; + /** + * 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 + */ + private addStatePacket; + /** + * 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 + */ + private updateReceiveBindings; + /** + * 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(): void; + /** + * 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 + */ + private onNetworkingClose; + /** + * 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 + */ + private onNetworkingStateChange; + /** + * Propagates errors from the underlying network instance. + * + * @param error - The error to propagate + */ + private onNetworkingError; + /** + * Propagates debug messages from the underlying network instance. + * + * @param message - The debug message to propagate + */ + private onNetworkingDebug; + /** + * Prepares an audio packet for dispatch. + * + * @param buffer - The Opus packet to prepare + */ + prepareAudioPacket(buffer: Buffer): Buffer | undefined; + /** + * Dispatches the previously prepared audio packet (if any) + */ + dispatchAudio(): boolean | undefined; + /** + * Prepares an audio packet and dispatches it immediately. + * + * @param buffer - The Opus packet to play + */ + playOpusPacket(buffer: Buffer): boolean | undefined; + /** + * 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?: boolean): void; + /** + * Disconnects the VoiceConnection, allowing the possibility of rejoining later on. + * + * @returns `true` if the connection was successfully disconnected + */ + disconnect(): boolean; + /** + * 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?: 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. + * + * @param enabled - Whether or not to show as speaking + */ + setSpeaking(enabled: boolean): false | void; + /** + * 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; + /** + * 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(): { + ws: number | undefined; + udp: number | undefined; + }; + /** + * Called when a subscription of this voice connection to an audio player is removed. + * + * @param subscription - The removed subscription + */ + 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 | undefined; +} +/** + * The options that can be given when joining a voice channel. + */ +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. + */ + guildId: string; + /** + * Whether to join the channel deafened (defaults to true) + */ + selfDeaf?: boolean; + /** + * Whether to join the channel muted (defaults to true) + */ + selfMute?: boolean; +} +/** + * Creates a VoiceConnection to a Discord voice channel. + * + * @param options - the options for joining the voice channel + */ +declare function joinVoiceChannel(options: CreateVoiceConnectionOptions & JoinVoiceChannelOptions): VoiceConnection; + +/** + * Generates a report of the dependencies used by the \@discordjs/voice module. + * Useful for debugging. + */ +declare function generateDependencyReport(): string; + +/** + * Allows a voice connection a specified amount of time to enter a given state, otherwise rejects with an error. + * + * @param target - The voice connection that we want to observe the state change for + * @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: AbortSignal | number): Promise; +/** + * Allows an audio player a specified amount of time to enter a given state, otherwise rejects with an error. + * + * @param target - The audio player that we want to observe the state change for + * @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: 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; +/** + * The resulting information after probing an audio stream + */ +interface ProbeInfo { + /** + * The readable audio stream to use. You should use this rather than the input stream, as the probing + * function can sometimes read the input stream to its end and cause the stream to close. + */ + stream: Readable; + /** + * The recommended stream type for this audio stream. + */ + type: StreamType; +} +/** + * Attempt to probe a readable stream to figure out whether it can be demuxed using an Ogg or WebM Opus demuxer. + * + * @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; + +/** + * 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 new file mode 100644 index 0000000..190e985 --- /dev/null +++ b/node_modules/@discordjs/voice/dist/index.js @@ -0,0 +1,2671 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +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 __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 __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; +}; + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + AudioPlayer: () => AudioPlayer, + AudioPlayerError: () => AudioPlayerError, + AudioPlayerStatus: () => AudioPlayerStatus, + AudioReceiveStream: () => AudioReceiveStream, + AudioResource: () => AudioResource, + EndBehaviorType: () => EndBehaviorType, + NoSubscriberBehavior: () => NoSubscriberBehavior, + PlayerSubscription: () => PlayerSubscription, + SSRCMap: () => SSRCMap, + SpeakingMap: () => SpeakingMap, + StreamType: () => StreamType, + VoiceConnection: () => VoiceConnection, + VoiceConnectionDisconnectReason: () => VoiceConnectionDisconnectReason, + VoiceConnectionStatus: () => VoiceConnectionStatus, + VoiceReceiver: () => VoiceReceiver, + createAudioPlayer: () => createAudioPlayer, + createAudioResource: () => createAudioResource, + createDefaultAudioReceiveStreamOptions: () => createDefaultAudioReceiveStreamOptions, + demuxProbe: () => demuxProbe, + entersState: () => entersState, + generateDependencyReport: () => generateDependencyReport, + getGroups: () => getGroups, + getVoiceConnection: () => getVoiceConnection, + getVoiceConnections: () => getVoiceConnections, + joinVoiceChannel: () => joinVoiceChannel, + validateDiscordOpusHead: () => validateDiscordOpusHead, + version: () => version2 +}); +module.exports = __toCommonJS(src_exports); + +// src/VoiceConnection.ts +var import_node_events7 = require("events"); + +// src/DataStore.ts +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, + self_deaf: config.selfDeaf, + self_mute: config.selfMute + } + }; +} +__name(createJoinVoiceChannelPayload, "createJoinVoiceChannelPayload"); +var groups = /* @__PURE__ */ new Map(); +groups.set("default", /* @__PURE__ */ new Map()); +function getOrCreateGroup(group) { + const existing = groups.get(group); + if (existing) + return existing; + const map = /* @__PURE__ */ new Map(); + groups.set(group, map); + return map; +} +__name(getOrCreateGroup, "getOrCreateGroup"); +function getGroups() { + return groups; +} +__name(getGroups, "getGroups"); +function getVoiceConnections(group = "default") { + return groups.get(group); +} +__name(getVoiceConnections, "getVoiceConnections"); +function getVoiceConnection(guildId, group = "default") { + return getVoiceConnections(group)?.get(guildId); +} +__name(getVoiceConnection, "getVoiceConnection"); +function untrackVoiceConnection(voiceConnection) { + return getVoiceConnections(voiceConnection.joinConfig.group)?.delete(voiceConnection.joinConfig.guildId); +} +__name(untrackVoiceConnection, "untrackVoiceConnection"); +function trackVoiceConnection(voiceConnection) { + return getOrCreateGroup(voiceConnection.joinConfig.group).set(voiceConnection.joinConfig.guildId, voiceConnection); +} +__name(trackVoiceConnection, "trackVoiceConnection"); +var FRAME_LENGTH = 20; +var audioCycleInterval; +var nextTime = -1; +var audioPlayers = []; +function audioCycleStep() { + if (nextTime === -1) + return; + nextTime += FRAME_LENGTH; + const available = audioPlayers.filter((player) => player.checkPlayable()); + for (const player of available) { + player["_stepDispatch"](); + } + prepareNextAudioFrame(available); +} +__name(audioCycleStep, "audioCycleStep"); +function prepareNextAudioFrame(players) { + const nextPlayer = players.shift(); + if (!nextPlayer) { + if (nextTime !== -1) { + audioCycleInterval = setTimeout(() => audioCycleStep(), nextTime - Date.now()); + } + return; + } + nextPlayer["_stepPrepare"](); + setImmediate(() => prepareNextAudioFrame(players)); +} +__name(prepareNextAudioFrame, "prepareNextAudioFrame"); +function hasAudioPlayer(target) { + return audioPlayers.includes(target); +} +__name(hasAudioPlayer, "hasAudioPlayer"); +function addAudioPlayer(player) { + if (hasAudioPlayer(player)) + return player; + audioPlayers.push(player); + if (audioPlayers.length === 1) { + nextTime = Date.now(); + setImmediate(() => audioCycleStep()); + } + return player; +} +__name(addAudioPlayer, "addAudioPlayer"); +function deleteAudioPlayer(player) { + const index = audioPlayers.indexOf(player); + if (index === -1) + return; + audioPlayers.splice(index, 1); + if (audioPlayers.length === 0) { + nextTime = -1; + if (typeof audioCycleInterval !== "undefined") + 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 = 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"); + } + const port = packet.readUInt16BE(packet.length - 2); + return { + ip, + port + }; +} +__name(parseLocalPacket, "parseLocalPacket"); +var KEEP_ALIVE_INTERVAL = 5e3; +var MAX_COUNTER_VALUE = 2 ** 32 - 1; +var VoiceUDPSocket = class extends import_node_events.EventEmitter { + /** + * The counter used in the keep alive mechanism. + */ + keepAliveCounter = 0; + /** + * Creates a new VoiceUDPSocket. + * + * @param remote - Details of the remote socket + */ + constructor(remote) { + super(); + 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.keepAliveBuffer = import_node_buffer2.Buffer.alloc(8); + this.keepAliveInterval = setInterval(() => this.keepAlive(), KEEP_ALIVE_INTERVAL); + setImmediate(() => this.keepAlive()); + } + /** + * Called when a message is received on the UDP socket. + * + * @param buffer - The received buffer + */ + onMessage(buffer) { + this.emit("message", buffer); + } + /** + * Called at a regular interval to check whether we are still able to send datagrams to Discord. + */ + keepAlive() { + this.keepAliveBuffer.writeUInt32LE(this.keepAliveCounter, 0); + this.send(this.keepAliveBuffer); + this.keepAliveCounter++; + if (this.keepAliveCounter > MAX_COUNTER_VALUE) { + this.keepAliveCounter = 0; + } + } + /** + * Sends a buffer to Discord. + * + * @param buffer - The buffer to send + */ + send(buffer) { + 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(); + } catch { + } + clearInterval(this.keepAliveInterval); + } + /** + * 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 { + if (message.readUInt16BE(0) !== 2) + return; + const packet = parseLocalPacket(message); + this.socket.off("message", listener); + resolve2(packet); + } catch { + } + }, "listener"); + this.socket.on("message", listener); + this.socket.once("close", () => reject(new Error("Cannot perform IP discovery - socket closed"))); + const discoveryBuffer = import_node_buffer2.Buffer.alloc(74); + discoveryBuffer.writeUInt16BE(1, 0); + discoveryBuffer.writeUInt16BE(70, 2); + discoveryBuffer.writeUInt32BE(ssrc, 4); + this.send(discoveryBuffer); + }); + } +}; +__name(VoiceUDPSocket, "VoiceUDPSocket"); + +// src/networking/VoiceWebSocket.ts +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 number of consecutively missed heartbeats. + */ + missedHeartbeats = 0; + /** + * Creates a new VoiceWebSocket. + * + * @param address - The address to connect to + */ + constructor(address, debug) { + super(); + this.ws = new import_ws.default(address); + 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 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; + this.debug?.(`<< ${event.data}`); + let packet; + try { + packet = JSON.parse(event.data); + } catch (error) { + const err = error; + this.emit("error", err); + return; + } + if (packet.op === import_v4.VoiceOpcodes.HeartbeatAck) { + this.lastHeartbeatAck = Date.now(); + this.missedHeartbeats = 0; + this.ping = this.lastHeartbeatAck - this.lastHeartbeatSend; + } + 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}`); + this.ws.send(stringified); + return; + } catch (error) { + const err = error; + this.emit("error", err); + } + } + /** + * Sends a heartbeat over the WebSocket. + */ + sendHeartbeat() { + this.lastHeartbeatSend = Date.now(); + this.missedHeartbeats++; + const nonce2 = this.lastHeartbeatSend; + 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") + clearInterval(this.heartbeatInterval); + if (ms > 0) { + this.heartbeatInterval = setInterval(() => { + if (this.lastHeartbeatSend !== 0 && this.missedHeartbeats >= 3) { + this.ws.close(); + this.setHeartbeatInterval(-1); + } + this.sendHeartbeat(); + }, ms); + } + } +}; +__name(VoiceWebSocket, "VoiceWebSocket"); + +// 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 NetworkingStatusCode; +(function(NetworkingStatusCode2) { + NetworkingStatusCode2[NetworkingStatusCode2["OpeningWs"] = 0] = "OpeningWs"; + NetworkingStatusCode2[NetworkingStatusCode2["Identifying"] = 1] = "Identifying"; + NetworkingStatusCode2[NetworkingStatusCode2["UdpHandshaking"] = 2] = "UdpHandshaking"; + NetworkingStatusCode2[NetworkingStatusCode2["SelectingProtocol"] = 3] = "SelectingProtocol"; + NetworkingStatusCode2[NetworkingStatusCode2["Ready"] = 4] = "Ready"; + NetworkingStatusCode2[NetworkingStatusCode2["Resuming"] = 5] = "Resuming"; + NetworkingStatusCode2[NetworkingStatusCode2["Closed"] = 6] = "Closed"; +})(NetworkingStatusCode || (NetworkingStatusCode = {})); +var nonce = import_node_buffer3.Buffer.alloc(24); +function stringifyState(state) { + return JSON.stringify({ + ...state, + ws: Reflect.has(state, "ws"), + udp: Reflect.has(state, "udp") + }); +} +__name(stringifyState, "stringifyState"); +function chooseEncryptionMode(options) { + const option = options.find((option2) => SUPPORTED_ENCRYPTION_MODES.includes(option2)); + if (!option) { + throw new Error(`No compatible encryption modes. Available include: ${options.join(", ")}`); + } + return option; +} +__name(chooseEncryptionMode, "chooseEncryptionMode"); +function randomNBit(numberOfBits) { + return Math.floor(Math.random() * 2 ** numberOfBits); +} +__name(randomNBit, "randomNBit"); +var Networking = class extends import_node_events3.EventEmitter { + /** + * Creates a new Networking instance. + */ + constructor(options, debug) { + super(); + this.onWsOpen = this.onWsOpen.bind(this); + this.onChildError = this.onChildError.bind(this); + this.onWsPacket = this.onWsPacket.bind(this); + this.onWsClose = this.onWsClose.bind(this); + this.onWsDebug = this.onWsDebug.bind(this); + this.onUdpDebug = this.onUdpDebug.bind(this); + this.onUdpClose = this.onUdpClose.bind(this); + this.debug = debug ? (message) => this.emit("debug", message) : null; + this._state = { + code: NetworkingStatusCode.OpeningWs, + ws: this.createWebSocket(options.endpoint), + connectionOptions: options + }; + } + /** + * Destroys the Networking instance, transitioning it into the Closed state. + */ + destroy() { + this.state = { + code: NetworkingStatusCode.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"); + if (oldWs && oldWs !== newWs) { + oldWs.off("debug", this.onWsDebug); + oldWs.on("error", noop); + oldWs.off("error", this.onChildError); + oldWs.off("open", this.onWsOpen); + oldWs.off("packet", this.onWsPacket); + oldWs.off("close", this.onWsClose); + oldWs.destroy(); + } + const oldUdp = Reflect.get(this._state, "udp"); + const newUdp = Reflect.get(newState, "udp"); + if (oldUdp && oldUdp !== newUdp) { + oldUdp.on("error", noop); + oldUdp.off("error", this.onChildError); + oldUdp.off("close", this.onUdpClose); + oldUdp.off("debug", this.onUdpDebug); + oldUdp.destroy(); + } + const oldState = this._state; + this._state = newState; + this.emit("stateChange", oldState, newState); + this.debug?.(`state change: +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); + ws.once("open", this.onWsOpen); + ws.on("packet", this.onWsPacket); + ws.once("close", this.onWsClose); + 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 === NetworkingStatusCode.OpeningWs) { + const packet = { + op: import_v42.VoiceOpcodes.Identify, + d: { + server_id: this.state.connectionOptions.serverId, + user_id: this.state.connectionOptions.userId, + session_id: this.state.connectionOptions.sessionId, + token: this.state.connectionOptions.token + } + }; + this.state.ws.sendPacket(packet); + this.state = { + ...this.state, + code: NetworkingStatusCode.Identifying + }; + } else if (this.state.code === NetworkingStatusCode.Resuming) { + const packet = { + op: import_v42.VoiceOpcodes.Resume, + d: { + server_id: this.state.connectionOptions.serverId, + session_id: this.state.connectionOptions.sessionId, + token: this.state.connectionOptions.token + } + }; + 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 === NetworkingStatusCode.Ready) { + this.state = { + ...this.state, + code: NetworkingStatusCode.Resuming, + ws: this.createWebSocket(this.state.connectionOptions.endpoint) + }; + } else if (this.state.code !== NetworkingStatusCode.Closed) { + this.destroy(); + 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 === NetworkingStatusCode.Ready) { + this.state = { + ...this.state, + code: NetworkingStatusCode.Resuming, + ws: this.createWebSocket(this.state.connectionOptions.endpoint) + }; + } + } + /** + * 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 !== NetworkingStatusCode.Closed) { + this.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval); + } else if (packet.op === import_v42.VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) { + const { ip, port, ssrc, modes } = packet.d; + const udp = new VoiceUDPSocket({ + ip, + port + }); + udp.on("error", this.onChildError); + udp.on("debug", this.onUdpDebug); + udp.once("close", this.onUdpClose); + udp.performIPDiscovery(ssrc).then((localConfig) => { + if (this.state.code !== NetworkingStatusCode.UdpHandshaking) + return; + this.state.ws.sendPacket({ + op: import_v42.VoiceOpcodes.SelectProtocol, + d: { + protocol: "udp", + data: { + address: localConfig.ip, + port: localConfig.port, + mode: chooseEncryptionMode(modes) + } + } + }); + this.state = { + ...this.state, + code: NetworkingStatusCode.SelectingProtocol + }; + }).catch((error) => this.emit("error", error)); + this.state = { + ...this.state, + code: NetworkingStatusCode.UdpHandshaking, + udp, + connectionData: { + ssrc + } + }; + } else if (packet.op === import_v42.VoiceOpcodes.SessionDescription && this.state.code === NetworkingStatusCode.SelectingProtocol) { + const { mode: encryptionMode, secret_key: secretKey } = packet.d; + this.state = { + ...this.state, + code: NetworkingStatusCode.Ready, + connectionData: { + ...this.state.connectionData, + encryptionMode, + secretKey: new Uint8Array(secretKey), + sequence: randomNBit(16), + timestamp: randomNBit(32), + nonce: 0, + nonceBuffer: import_node_buffer3.Buffer.alloc(24), + speaking: false, + packetsPlayed: 0 + } + }; + } else if (packet.op === import_v42.VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) { + this.state = { + ...this.state, + code: NetworkingStatusCode.Ready + }; + 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 !== NetworkingStatusCode.Ready) + return; + 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 !== NetworkingStatusCode.Ready) + return false; + if (typeof state.preparedPacket !== "undefined") { + 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 !== NetworkingStatusCode.Ready) + return; + const { connectionData } = state; + connectionData.packetsPlayed++; + connectionData.sequence++; + connectionData.timestamp += TIMESTAMP_INC; + if (connectionData.sequence >= 2 ** 16) + connectionData.sequence = 0; + if (connectionData.timestamp >= 2 ** 32) + connectionData.timestamp = 0; + 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 !== NetworkingStatusCode.Ready) + return; + if (state.connectionData.speaking === speaking) + return; + state.connectionData.speaking = speaking; + state.ws.sendPacket({ + op: import_v42.VoiceOpcodes.Speaking, + d: { + speaking: speaking ? 1 : 0, + delay: 0, + ssrc: state.connectionData.ssrc + } + }); + } + /** + * 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 = import_node_buffer3.Buffer.alloc(12); + packetBuffer[0] = 128; + packetBuffer[1] = 120; + const { sequence, timestamp, ssrc } = connectionData; + packetBuffer.writeUIntBE(sequence, 2, 2); + packetBuffer.writeUIntBE(timestamp, 4, 4); + packetBuffer.writeUIntBE(ssrc, 8, 4); + packetBuffer.copy(nonce, 0, 0, 12); + 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") { + connectionData.nonce++; + if (connectionData.nonce > MAX_NONCE_SIZE) + connectionData.nonce = 0; + connectionData.nonceBuffer.writeUInt32BE(connectionData.nonce, 0); + return [ + methods.close(opusPacket, connectionData.nonceBuffer, secretKey), + connectionData.nonceBuffer.slice(0, 4) + ]; + } else if (encryptionMode === "xsalsa20_poly1305_suffix") { + const random = methods.random(24, connectionData.nonceBuffer); + return [ + methods.close(opusPacket, random, secretKey), + random + ]; + } + return [ + methods.close(opusPacket, nonce, secretKey) + ]; + } +}; +__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_buffer4 = require("buffer"); +var import_node_events4 = require("events"); + +// src/audio/AudioPlayerError.ts +var AudioPlayerError = class extends Error { + constructor(error, resource) { + super(error.message); + this.resource = resource; + this.name = error.name; + this.stack = error.stack; + } +}; +__name(AudioPlayerError, "AudioPlayerError"); + +// src/audio/PlayerSubscription.ts +var PlayerSubscription = class { + constructor(connection, 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); + } +}; +__name(PlayerSubscription, "PlayerSubscription"); + +// src/audio/AudioPlayer.ts +var SILENCE_FRAME = import_node_buffer4.Buffer.from([ + 248, + 255, + 254 +]); +var NoSubscriberBehavior; +(function(NoSubscriberBehavior2) { + NoSubscriberBehavior2[ + /** + * Pauses playing the stream until a voice connection becomes available. + */ + "Pause" + ] = "pause"; + NoSubscriberBehavior2[ + /** + * Continues to play through the resource regardless. + */ + "Play" + ] = "play"; + NoSubscriberBehavior2[ + /** + * The player stops and enters the Idle state. + */ + "Stop" + ] = "stop"; +})(NoSubscriberBehavior || (NoSubscriberBehavior = {})); +var AudioPlayerStatus; +(function(AudioPlayerStatus2) { + AudioPlayerStatus2[ + /** + * When the player has paused itself. Only possible with the "pause" no subscriber behavior. + */ + "AutoPaused" + ] = "autopaused"; + AudioPlayerStatus2[ + /** + * When the player is waiting for an audio resource to become readable before transitioning to Playing. + */ + "Buffering" + ] = "buffering"; + AudioPlayerStatus2[ + /** + * When there is currently no resource for the player to be playing. + */ + "Idle" + ] = "idle"; + AudioPlayerStatus2[ + /** + * When the player has been manually paused. + */ + "Paused" + ] = "paused"; + AudioPlayerStatus2[ + /** + * When the player is actively playing an audio resource. + */ + "Playing" + ] = "playing"; +})(AudioPlayerStatus || (AudioPlayerStatus = {})); +function stringifyState2(state) { + return JSON.stringify({ + ...state, + resource: Reflect.has(state, "resource"), + stepTimeout: Reflect.has(state, "stepTimeout") + }); +} +__name(stringifyState2, "stringifyState"); +var AudioPlayer = class extends import_node_events4.EventEmitter { + /** + * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio + * to the streams in this list. + */ + subscribers = []; + /** + * Creates a new AudioPlayer. + */ + constructor(options = {}) { + super(); + this._state = { + status: AudioPlayerStatus.Idle + }; + this.behaviors = { + noSubscriber: NoSubscriberBehavior.Pause, + maxMissedFrames: 5, + ...options.behaviors + }; + 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 === VoiceConnectionStatus.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) { + const subscription = new PlayerSubscription(connection, this); + this.subscribers.push(subscription); + setImmediate(() => this.emit("subscribe", subscription)); + return subscription; + } + 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; + if (exists) { + this.subscribers.splice(index, 1); + subscription.connection.setSpeaking(false); + this.emit("unsubscribe", subscription); + } + 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"); + if (oldState.status !== AudioPlayerStatus.Idle && oldState.resource !== newResource) { + oldState.resource.playStream.on("error", noop); + oldState.resource.playStream.off("error", oldState.onStreamError); + oldState.resource.audioPlayer = void 0; + oldState.resource.playStream.destroy(); + oldState.resource.playStream.read(); + } + if (oldState.status === AudioPlayerStatus.Buffering && (newState.status !== AudioPlayerStatus.Buffering || newState.resource !== oldState.resource)) { + oldState.resource.playStream.off("end", oldState.onFailureCallback); + oldState.resource.playStream.off("close", oldState.onFailureCallback); + oldState.resource.playStream.off("finish", oldState.onFailureCallback); + oldState.resource.playStream.off("readable", oldState.onReadableCallback); + } + if (newState.status === AudioPlayerStatus.Idle) { + this._signalStopSpeaking(); + deleteAudioPlayer(this); + } + if (newResource) { + addAudioPlayer(this); + } + const didChangeResources = oldState.status !== AudioPlayerStatus.Idle && newState.status === AudioPlayerStatus.Playing && oldState.resource !== newState.resource; + this._state = newState; + this.emit("stateChange", oldState, this._state); + if (oldState.status !== newState.status || didChangeResources) { + this.emit(newState.status, oldState, this._state); + } + this.debug?.(`state change: +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."); + } + if (resource.audioPlayer) { + if (resource.audioPlayer === this) { + return; + } + throw new Error("Resource is already being played by another audio player."); + } + resource.audioPlayer = this; + const onStreamError = /* @__PURE__ */ __name((error) => { + if (this.state.status !== AudioPlayerStatus.Idle) { + this.emit("error", new AudioPlayerError(error, this.state.resource)); + } + if (this.state.status !== AudioPlayerStatus.Idle && this.state.resource === resource) { + this.state = { + status: AudioPlayerStatus.Idle + }; + } + }, "onStreamError"); + resource.playStream.once("error", onStreamError); + if (resource.started) { + this.state = { + status: AudioPlayerStatus.Playing, + missedFrames: 0, + playbackDuration: 0, + resource, + onStreamError + }; + } else { + const onReadableCallback = /* @__PURE__ */ __name(() => { + if (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) { + this.state = { + status: AudioPlayerStatus.Playing, + missedFrames: 0, + playbackDuration: 0, + resource, + onStreamError + }; + } + }, "onReadableCallback"); + const onFailureCallback = /* @__PURE__ */ __name(() => { + if (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) { + this.state = { + status: AudioPlayerStatus.Idle + }; + } + }, "onFailureCallback"); + resource.playStream.once("readable", onReadableCallback); + resource.playStream.once("end", onFailureCallback); + resource.playStream.once("close", onFailureCallback); + resource.playStream.once("finish", onFailureCallback); + this.state = { + status: AudioPlayerStatus.Buffering, + resource, + onReadableCallback, + onFailureCallback, + onStreamError + }; + } + } + /** + * 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 !== AudioPlayerStatus.Playing) + return false; + this.state = { + ...this.state, + status: AudioPlayerStatus.Paused, + silencePacketsRemaining: interpolateSilence ? 5 : 0 + }; + 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 !== AudioPlayerStatus.Paused) + return false; + this.state = { + ...this.state, + status: AudioPlayerStatus.Playing, + missedFrames: 0 + }; + 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 === AudioPlayerStatus.Idle) + return false; + if (force || this.state.resource.silencePaddingFrames === 0) { + this.state = { + status: AudioPlayerStatus.Idle + }; + } else if (this.state.resource.silenceRemaining === -1) { + this.state.resource.silenceRemaining = this.state.resource.silencePaddingFrames; + } + 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 === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) + return false; + if (!state.resource.readable) { + this.state = { + status: AudioPlayerStatus.Idle + }; + return false; + } + 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 === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) + return; + 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 === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) + return; + const playable = this.playable; + if (state.status === AudioPlayerStatus.AutoPaused && playable.length > 0) { + this.state = { + ...state, + status: AudioPlayerStatus.Playing, + missedFrames: 0 + }; + } + if (state.status === AudioPlayerStatus.Paused || state.status === AudioPlayerStatus.AutoPaused) { + if (state.silencePacketsRemaining > 0) { + state.silencePacketsRemaining--; + this._preparePacket(SILENCE_FRAME, playable, state); + if (state.silencePacketsRemaining === 0) { + this._signalStopSpeaking(); + } + } + return; + } + if (playable.length === 0) { + if (this.behaviors.noSubscriber === NoSubscriberBehavior.Pause) { + this.state = { + ...state, + status: AudioPlayerStatus.AutoPaused, + silencePacketsRemaining: 5 + }; + return; + } else if (this.behaviors.noSubscriber === NoSubscriberBehavior.Stop) { + this.stop(true); + } + } + const packet = state.resource.read(); + if (state.status === AudioPlayerStatus.Playing) { + if (packet) { + this._preparePacket(packet, playable, state); + state.missedFrames = 0; + } else { + this._preparePacket(SILENCE_FRAME, playable, state); + state.missedFrames++; + if (state.missedFrames >= this.behaviors.maxMissedFrames) { + this.stop(); + } + } + } + } + /** + * 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() { + 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; + for (const connection of receivers) { + connection.prepareAudioPacket(packet); + } + } +}; +__name(AudioPlayer, "AudioPlayer"); +function createAudioPlayer(options) { + return new AudioPlayer(options); +} +__name(createAudioPlayer, "createAudioPlayer"); + +// src/receive/AudioReceiveStream.ts +var EndBehaviorType; +(function(EndBehaviorType2) { + EndBehaviorType2[EndBehaviorType2[ + /** + * The stream will only end when manually destroyed. + */ + "Manual" + ] = 0] = "Manual"; + EndBehaviorType2[EndBehaviorType2[ + /** + * The stream will end after a given time period of silence/no audio packets. + */ + "AfterSilence" + ] = 1] = "AfterSilence"; + EndBehaviorType2[EndBehaviorType2[ + /** + * The stream will end after a given time period of no audio packets. + */ + "AfterInactivity" + ] = 2] = "AfterInactivity"; +})(EndBehaviorType || (EndBehaviorType = {})); +function createDefaultAudioReceiveStreamOptions() { + return { + end: { + behavior: EndBehaviorType.Manual + } + }; +} +__name(createDefaultAudioReceiveStreamOptions, "createDefaultAudioReceiveStreamOptions"); +var AudioReceiveStream = class extends import_node_stream.Readable { + constructor({ end, ...options }) { + super({ + ...options, + objectMode: true + }); + this.end = end; + } + push(buffer) { + if (buffer && (this.end.behavior === EndBehaviorType.AfterInactivity || this.end.behavior === EndBehaviorType.AfterSilence && (buffer.compare(SILENCE_FRAME) !== 0 || typeof this.endTimeout === "undefined"))) { + this.renewEndTimeout(this.end); + } + return super.push(buffer); + } + renewEndTimeout(end) { + if (this.endTimeout) { + clearTimeout(this.endTimeout); + } + this.endTimeout = setTimeout(() => this.push(null), end.duration); + } + _read() { + } +}; +__name(AudioReceiveStream, "AudioReceiveStream"); + +// src/receive/SSRCMap.ts +var import_node_events5 = require("events"); +var SSRCMap = class extends import_node_events5.EventEmitter { + constructor() { + super(); + 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 = { + ...this.map.get(data.audioSSRC), + ...data + }; + this.map.set(data.audioSSRC, newValue); + if (!existing) + 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); + } + for (const data of this.map.values()) { + if (data.userId === target) { + return data; + } + } + 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); + if (existing) { + this.map.delete(target); + this.emit("delete", existing); + } + return existing; + } + for (const [audioSSRC, data] of this.map.entries()) { + if (data.userId === target) { + this.map.delete(audioSSRC); + this.emit("delete", data); + return data; + } + } + return void 0; + } +}; +__name(SSRCMap, "SSRCMap"); + +// src/receive/SpeakingMap.ts +var import_node_events6 = require("events"); +var _SpeakingMap = class extends import_node_events6.EventEmitter { + constructor() { + super(); + this.users = /* @__PURE__ */ new Map(); + this.speakingTimeouts = /* @__PURE__ */ new Map(); + } + onPacket(userId) { + const timeout = this.speakingTimeouts.get(userId); + if (timeout) { + clearTimeout(timeout); + } else { + this.users.set(userId, Date.now()); + this.emit("start", userId); + } + this.startTimeout(userId); + } + startTimeout(userId) { + 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 { + constructor(voiceConnection) { + this.voiceConnection = voiceConnection; + this.ssrcMap = new SSRCMap(); + this.speaking = new SpeakingMap(); + this.subscriptions = /* @__PURE__ */ new Map(); + this.connectionData = {}; + 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); + } else if (packet.op === import_v43.VoiceOpcodes.Speaking && typeof packet.d?.user_id === "string" && typeof packet.d?.ssrc === "number") { + this.ssrcMap.update({ + userId: packet.d.user_id, + audioSSRC: packet.d.ssrc + }); + } else if (packet.op === import_v43.VoiceOpcodes.ClientConnect && typeof packet.d?.user_id === "string" && typeof packet.d?.audio_ssrc === "number") { + this.ssrcMap.update({ + userId: packet.d.user_id, + audioSSRC: packet.d.audio_ssrc, + videoSSRC: packet.d.video_ssrc === 0 ? void 0 : packet.d.video_ssrc + }); + } + } + decrypt(buffer, mode, nonce2, secretKey) { + let end; + if (mode === "xsalsa20_poly1305_lite") { + buffer.copy(nonce2, 0, buffer.length - 4); + end = buffer.length - 4; + } else if (mode === "xsalsa20_poly1305_suffix") { + buffer.copy(nonce2, 0, buffer.length - 24); + end = buffer.length - 24; + } else { + buffer.copy(nonce2, 0, 0, 12); + } + const decrypted = methods.open(buffer.slice(12, end), nonce2, secretKey); + if (!decrypted) + return; + 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) + return; + if (packet[0] === 190 && packet[1] === 222) { + const headerExtensionLength = packet.readUInt16BE(2); + packet = packet.subarray(4 + 4 * headerExtensionLength); + } + 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; + const ssrc = msg.readUInt32BE(8); + const userData = this.ssrcMap.get(ssrc); + if (!userData) + return; + this.speaking.onPacket(userData.userId); + const stream = this.subscriptions.get(userData.userId); + 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); + if (packet) { + stream.push(packet); + } else { + stream.destroy(new Error("Failed to parse packet")); + } + } + } + /** + * 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) + return existing; + const stream = new AudioReceiveStream({ + ...createDefaultAudioReceiveStreamOptions(), + ...options + }); + stream.once("close", () => this.subscriptions.delete(userId)); + this.subscriptions.set(userId, stream); + return stream; + } +}; +__name(VoiceReceiver, "VoiceReceiver"); + +// src/VoiceConnection.ts +var VoiceConnectionStatus; +(function(VoiceConnectionStatus2) { + VoiceConnectionStatus2[ + /** + * The `VOICE_SERVER_UPDATE` and `VOICE_STATE_UPDATE` packets have been received, now attempting to establish a voice connection. + */ + "Connecting" + ] = "connecting"; + VoiceConnectionStatus2[ + /** + * The voice connection has been destroyed and untracked, it cannot be reused. + */ + "Destroyed" + ] = "destroyed"; + VoiceConnectionStatus2[ + /** + * The voice connection has either been severed or not established. + */ + "Disconnected" + ] = "disconnected"; + VoiceConnectionStatus2[ + /** + * A voice connection has been established, and is ready to be used. + */ + "Ready" + ] = "ready"; + VoiceConnectionStatus2[ + /** + * Sending a packet to the main Discord gateway to indicate we want to change our voice state. + */ + "Signalling" + ] = "signalling"; +})(VoiceConnectionStatus || (VoiceConnectionStatus = {})); +var VoiceConnectionDisconnectReason; +(function(VoiceConnectionDisconnectReason2) { + VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2[ + /** + * When the WebSocket connection has been closed. + */ + "WebSocketClose" + ] = 0] = "WebSocketClose"; + VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2[ + /** + * When the adapter was unable to send a message requested by the VoiceConnection. + */ + "AdapterUnavailable" + ] = 1] = "AdapterUnavailable"; + VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2[ + /** + * When a VOICE_SERVER_UPDATE packet is received with a null endpoint, causing the connection to be severed. + */ + "EndpointRemoved" + ] = 2] = "EndpointRemoved"; + VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2[ + /** + * When a manual disconnect was requested. + */ + "Manual" + ] = 3] = "Manual"; +})(VoiceConnectionDisconnectReason || (VoiceConnectionDisconnectReason = {})); +var VoiceConnection = class extends import_node_events7.EventEmitter { + /** + * 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(); + 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 = options.adapterCreator({ + onVoiceServerUpdate: (data) => this.addServerPacket(data), + onVoiceStateUpdate: (data) => this.addStatePacket(data), + destroy: () => this.destroy(false) + }); + this._state = { + status: VoiceConnectionStatus.Signalling, + adapter + }; + this.packets = { + server: void 0, + state: void 0 + }; + 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"); + const newNetworking = Reflect.get(newState, "networking"); + const oldSubscription = Reflect.get(oldState, "subscription"); + const newSubscription = Reflect.get(newState, "subscription"); + if (oldNetworking !== newNetworking) { + if (oldNetworking) { + oldNetworking.on("error", noop); + oldNetworking.off("debug", this.onNetworkingDebug); + oldNetworking.off("error", this.onNetworkingError); + oldNetworking.off("close", this.onNetworkingClose); + oldNetworking.off("stateChange", this.onNetworkingStateChange); + oldNetworking.destroy(); + } + if (newNetworking) + this.updateReceiveBindings(newNetworking.state, oldNetworking?.state); + } + if (newState.status === VoiceConnectionStatus.Ready) { + this.rejoinAttempts = 0; + } else if (newState.status === VoiceConnectionStatus.Destroyed) { + for (const stream of this.receiver.subscriptions.values()) { + if (!stream.destroyed) + stream.destroy(); + } + } + if (oldState.status !== VoiceConnectionStatus.Destroyed && newState.status === VoiceConnectionStatus.Destroyed) { + oldState.adapter.destroy(); + } + this._state = newState; + if (oldSubscription && oldSubscription !== newSubscription) { + oldSubscription.unsubscribe(); + } + this.emit("stateChange", oldState, newState); + if (oldState.status !== newState.status) { + 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) { + this.configureNetworking(); + } else if (this.state.status !== VoiceConnectionStatus.Destroyed) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.EndpointRemoved + }; + } + } + /** + * 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") + this.joinConfig.selfDeaf = packet.self_deaf; + if (typeof packet.self_mute !== "undefined") + 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"); + const oldUdp = Reflect.get(oldState ?? {}, "udp"); + const newUdp = Reflect.get(newState, "udp"); + if (oldWs !== newWs) { + oldWs?.off("packet", this.receiver.onWsPacket); + newWs?.on("packet", this.receiver.onWsPacket); + } + if (oldUdp !== newUdp) { + oldUdp?.off("message", this.receiver.onUdpMessage); + newUdp?.on("message", this.receiver.onUdpMessage); + } + 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 === VoiceConnectionStatus.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)); + networking.once("close", this.onNetworkingClose); + networking.on("stateChange", this.onNetworkingStateChange); + networking.on("error", this.onNetworkingError); + networking.on("debug", this.onNetworkingDebug); + this.state = { + ...this.state, + status: VoiceConnectionStatus.Connecting, + 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 === VoiceConnectionStatus.Destroyed) + return; + if (code === 4014) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.WebSocketClose, + closeCode: code + }; + } else { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Signalling + }; + this.rejoinAttempts++; + if (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + } + } + } + /** + * 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) + return; + if (this.state.status !== VoiceConnectionStatus.Connecting && this.state.status !== VoiceConnectionStatus.Ready) + return; + if (newState.code === NetworkingStatusCode.Ready) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Ready + }; + } else if (newState.code !== NetworkingStatusCode.Closed) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Connecting + }; + } + } + /** + * 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 !== VoiceConnectionStatus.Ready) + return; + return state.networking.prepareAudioPacket(buffer); + } + /** + * Dispatches the previously prepared audio packet (if any) + */ + dispatchAudio() { + const state = this.state; + if (state.status !== VoiceConnectionStatus.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 !== VoiceConnectionStatus.Ready) + return; + 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 === VoiceConnectionStatus.Destroyed) { + throw new Error("Cannot destroy VoiceConnection - it has already been destroyed"); + } + if (getVoiceConnection(this.joinConfig.guildId, this.joinConfig.group) === this) { + untrackVoiceConnection(this); + } + if (adapterAvailable) { + this.state.adapter.sendPayload(createJoinVoiceChannelPayload({ + ...this.joinConfig, + channelId: null + })); + } + this.state = { + status: VoiceConnectionStatus.Destroyed + }; + } + /** + * Disconnects the VoiceConnection, allowing the possibility of rejoining later on. + * + * @returns `true` if the connection was successfully disconnected + */ + disconnect() { + if (this.state.status === VoiceConnectionStatus.Destroyed || this.state.status === VoiceConnectionStatus.Signalling) { + return false; + } + this.joinConfig.channelId = null; + if (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) { + this.state = { + adapter: this.state.adapter, + subscription: this.state.subscription, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + return false; + } + this.state = { + adapter: this.state.adapter, + reason: VoiceConnectionDisconnectReason.Manual, + status: VoiceConnectionStatus.Disconnected + }; + 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 === VoiceConnectionStatus.Destroyed) { + return false; + } + const notReady = this.state.status !== VoiceConnectionStatus.Ready; + if (notReady) + this.rejoinAttempts++; + Object.assign(this.joinConfig, joinConfig); + if (this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) { + if (notReady) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Signalling + }; + } + return true; + } + this.state = { + adapter: this.state.adapter, + subscription: this.state.subscription, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + 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 !== VoiceConnectionStatus.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 === VoiceConnectionStatus.Destroyed) + return; + const subscription = player["subscribe"](this); + this.state = { + ...this.state, + subscription + }; + 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 === VoiceConnectionStatus.Ready && this.state.networking.state.code === NetworkingStatusCode.Ready) { + return { + ws: this.state.networking.state.ws.ping, + udp: this.state.networking.state.udp.ping + }; + } + return { + ws: void 0, + 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 !== VoiceConnectionStatus.Destroyed && this.state.subscription === subscription) { + this.state = { + ...this.state, + subscription: void 0 + }; + } + } +}; +__name(VoiceConnection, "VoiceConnection"); +function createVoiceConnection(joinConfig, options) { + const payload = createJoinVoiceChannelPayload(joinConfig); + const existing = getVoiceConnection(joinConfig.guildId, joinConfig.group); + if (existing && existing.state.status !== VoiceConnectionStatus.Destroyed) { + if (existing.state.status === VoiceConnectionStatus.Disconnected) { + existing.rejoin({ + channelId: joinConfig.channelId, + selfDeaf: joinConfig.selfDeaf, + selfMute: joinConfig.selfMute + }); + } else if (!existing.state.adapter.sendPayload(payload)) { + existing.state = { + ...existing.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + } + return existing; + } + const voiceConnection = new VoiceConnection(joinConfig, options); + trackVoiceConnection(voiceConnection); + if (voiceConnection.state.status !== VoiceConnectionStatus.Destroyed && !voiceConnection.state.adapter.sendPayload(payload)) { + voiceConnection.state = { + ...voiceConnection.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + } + return voiceConnection; +} +__name(createVoiceConnection, "createVoiceConnection"); + +// src/joinVoiceChannel.ts +function joinVoiceChannel(options) { + const joinConfig = { + selfDeaf: true, + selfMute: false, + group: "default", + ...options + }; + return createVoiceConnection(joinConfig, { + adapterCreator: options.adapterCreator, + debug: options.debug + }); +} +__name(joinVoiceChannel, "joinVoiceChannel"); + +// src/audio/AudioResource.ts +var import_node_stream2 = require("stream"); +var import_prism_media2 = __toESM(require("prism-media")); + +// src/audio/TransformerGraph.ts +var import_prism_media = __toESM(require("prism-media")); +var FFMPEG_PCM_ARGUMENTS = [ + "-analyzeduration", + "0", + "-loglevel", + "0", + "-f", + "s16le", + "-ar", + "48000", + "-ac", + "2" +]; +var FFMPEG_OPUS_ARGUMENTS = [ + "-analyzeduration", + "0", + "-loglevel", + "0", + "-acodec", + "libopus", + "-f", + "opus", + "-ar", + "48000", + "-ac", + "2" +]; +var StreamType; +(function(StreamType2) { + StreamType2["Arbitrary"] = "arbitrary"; + StreamType2["OggOpus"] = "ogg/opus"; + StreamType2["Opus"] = "opus"; + StreamType2["Raw"] = "raw"; + StreamType2["WebmOpus"] = "webm/opus"; +})(StreamType || (StreamType = {})); +var TransformerType; +(function(TransformerType2) { + TransformerType2["FFmpegOgg"] = "ffmpeg ogg"; + TransformerType2["FFmpegPCM"] = "ffmpeg pcm"; + TransformerType2["InlineVolume"] = "volume transformer"; + TransformerType2["OggOpusDemuxer"] = "ogg/opus demuxer"; + TransformerType2["OpusDecoder"] = "opus decoder"; + TransformerType2["OpusEncoder"] = "opus encoder"; + TransformerType2["WebmOpusDemuxer"] = "webm/opus demuxer"; +})(TransformerType || (TransformerType = {})); +var Node = class { + /** + * The outbound edges from this node. + */ + edges = []; + constructor(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 + }); + } +}; +__name(Node, "Node"); +var NODES = /* @__PURE__ */ new Map(); +for (const streamType of Object.values(StreamType)) { + NODES.set(streamType, new Node(streamType)); +} +function getNode(type) { + const node = NODES.get(type); + if (!node) + throw new Error(`Node type '${type}' does not exist!`); + return node; +} +__name(getNode, "getNode"); +getNode(StreamType.Raw).addEdge({ + type: TransformerType.OpusEncoder, + to: getNode(StreamType.Opus), + cost: 1.5, + transformer: () => new import_prism_media.default.opus.Encoder({ + rate: 48e3, + channels: 2, + frameSize: 960 + }) +}); +getNode(StreamType.Opus).addEdge({ + type: TransformerType.OpusDecoder, + to: getNode(StreamType.Raw), + cost: 1.5, + transformer: () => new import_prism_media.default.opus.Decoder({ + rate: 48e3, + channels: 2, + frameSize: 960 + }) +}); +getNode(StreamType.OggOpus).addEdge({ + type: TransformerType.OggOpusDemuxer, + to: getNode(StreamType.Opus), + cost: 1, + transformer: () => new import_prism_media.default.opus.OggDemuxer() +}); +getNode(StreamType.WebmOpus).addEdge({ + type: TransformerType.WebmOpusDemuxer, + to: getNode(StreamType.Opus), + cost: 1, + transformer: () => new import_prism_media.default.opus.WebmDemuxer() +}); +var FFMPEG_PCM_EDGE = { + type: TransformerType.FFmpegPCM, + to: getNode(StreamType.Raw), + cost: 2, + transformer: (input) => new import_prism_media.default.FFmpeg({ + args: typeof input === "string" ? [ + "-i", + input, + ...FFMPEG_PCM_ARGUMENTS + ] : FFMPEG_PCM_ARGUMENTS + }) +}; +getNode(StreamType.Arbitrary).addEdge(FFMPEG_PCM_EDGE); +getNode(StreamType.OggOpus).addEdge(FFMPEG_PCM_EDGE); +getNode(StreamType.WebmOpus).addEdge(FFMPEG_PCM_EDGE); +getNode(StreamType.Raw).addEdge({ + type: TransformerType.InlineVolume, + to: getNode(StreamType.Raw), + cost: 0.5, + transformer: () => new import_prism_media.default.VolumeTransformer({ + type: "s16le" + }) +}); +function canEnableFFmpegOptimizations() { + try { + return import_prism_media.default.FFmpeg.getInfo().output.includes("--enable-libopus"); + } catch { + } + return false; +} +__name(canEnableFFmpegOptimizations, "canEnableFFmpegOptimizations"); +if (canEnableFFmpegOptimizations()) { + const FFMPEG_OGG_EDGE = { + type: TransformerType.FFmpegOgg, + to: getNode(StreamType.OggOpus), + cost: 2, + transformer: (input) => new import_prism_media.default.FFmpeg({ + args: typeof input === "string" ? [ + "-i", + input, + ...FFMPEG_OPUS_ARGUMENTS + ] : FFMPEG_OPUS_ARGUMENTS + }) + }; + getNode(StreamType.Arbitrary).addEdge(FFMPEG_OGG_EDGE); + getNode(StreamType.OggOpus).addEdge(FFMPEG_OGG_EDGE); + getNode(StreamType.WebmOpus).addEdge(FFMPEG_OGG_EDGE); +} +function findPath(from, constraints, goal = getNode(StreamType.Opus), path = [], depth = 5) { + if (from === goal && constraints(path)) { + return { + cost: 0 + }; + } else if (depth === 0) { + return { + cost: Number.POSITIVE_INFINITY + }; + } + let currentBest; + for (const edge of from.edges) { + if (currentBest && edge.cost > currentBest.cost) + continue; + const next = findPath(edge.to, constraints, goal, [ + ...path, + edge + ], depth - 1); + const cost = edge.cost + next.cost; + if (!currentBest || cost < currentBest.cost) { + currentBest = { + cost, + edge, + next + }; + } + } + return currentBest ?? { + cost: Number.POSITIVE_INFINITY + }; +} +__name(findPath, "findPath"); +function constructPipeline(step) { + const edges = []; + let current = step; + while (current?.edge) { + edges.push(current.edge); + current = current.next; + } + return edges; +} +__name(constructPipeline, "constructPipeline"); +function findPipeline(from, constraint) { + return constructPipeline(findPath(getNode(from), constraint)); +} +__name(findPipeline, "findPipeline"); + +// src/audio/AudioResource.ts +var AudioResource = class { + /** + * 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 remaining silence frames to play. If -1, the frames have not yet started playing. + */ + silenceRemaining = -1; + constructor(edges, streams, metadata, silencePaddingFrames) { + this.edges = edges; + this.playStream = streams.length > 1 ? (0, import_node_stream2.pipeline)(streams, noop) : streams[0]; + this.metadata = metadata; + this.silencePaddingFrames = silencePaddingFrames; + for (const stream of streams) { + if (stream instanceof import_prism_media2.default.VolumeTransformer) { + this.volume = stream; + } else if (stream instanceof import_prism_media2.default.opus.Encoder) { + this.encoder = stream; + } + } + 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; + const real = this.playStream.readable; + if (!real) { + if (this.silenceRemaining === -1) + this.silenceRemaining = this.silencePaddingFrames; + return this.silenceRemaining !== 0; + } + 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; + } else if (this.silenceRemaining > 0) { + this.silenceRemaining--; + return SILENCE_FRAME; + } + const packet = this.playStream.read(); + if (packet) { + this.playbackDuration += 20; + } + return packet; + } +}; +__name(AudioResource, "AudioResource"); +var VOLUME_CONSTRAINT = /* @__PURE__ */ __name((path) => path.some((edge) => edge.type === TransformerType.InlineVolume), "VOLUME_CONSTRAINT"); +var NO_CONSTRAINT = /* @__PURE__ */ __name(() => true, "NO_CONSTRAINT"); +function inferStreamType(stream) { + if (stream instanceof import_prism_media2.default.opus.Encoder) { + return { + streamType: StreamType.Opus, + hasVolume: false + }; + } else if (stream instanceof import_prism_media2.default.opus.Decoder) { + return { + streamType: StreamType.Raw, + hasVolume: false + }; + } else if (stream instanceof import_prism_media2.default.VolumeTransformer) { + return { + streamType: StreamType.Raw, + hasVolume: true + }; + } else if (stream instanceof import_prism_media2.default.opus.OggDemuxer) { + return { + streamType: StreamType.Opus, + hasVolume: false + }; + } else if (stream instanceof import_prism_media2.default.opus.WebmDemuxer) { + return { + streamType: StreamType.Opus, + hasVolume: false + }; + } + return { + streamType: StreamType.Arbitrary, + hasVolume: false + }; +} +__name(inferStreamType, "inferStreamType"); +function createAudioResource(input, options = {}) { + let inputType = options.inputType; + let needsInlineVolume = Boolean(options.inlineVolume); + if (typeof input === "string") { + inputType = StreamType.Arbitrary; + } else if (typeof inputType === "undefined") { + const analysis = inferStreamType(input); + inputType = analysis.streamType; + needsInlineVolume = needsInlineVolume && !analysis.hasVolume; + } + const transformerPipeline = findPipeline(inputType, needsInlineVolume ? VOLUME_CONSTRAINT : NO_CONSTRAINT); + if (transformerPipeline.length === 0) { + if (typeof input === "string") + throw new Error(`Invalid pipeline constructed for string resource '${input}'`); + return new AudioResource([], [ + input + ], options.metadata ?? null, options.silencePaddingFrames ?? 5); + } + 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); +} +__name(createAudioResource, "createAudioResource"); + +// src/util/generateDependencyReport.ts +var import_node_path = require("path"); +var import_prism_media3 = __toESM(require("prism-media")); +function findPackageJSON(dir, packageName, depth) { + if (depth === 0) + return void 0; + const attemptedPath = (0, import_node_path.resolve)(dir, "./package.json"); + try { + const pkg = require(attemptedPath); + if (pkg.name !== packageName) + throw new Error("package.json does not match"); + return pkg; + } catch { + return findPackageJSON((0, import_node_path.resolve)(dir, ".."), packageName, depth - 1); + } +} +__name(findPackageJSON, "findPackageJSON"); +function version(name) { + try { + if (name === "@discordjs/voice") { + return "[VI]{{inject}}[/VI]"; + } + const pkg = findPackageJSON((0, import_node_path.dirname)(require.resolve(name)), name, 3); + return pkg?.version ?? "not found"; + } catch { + return "not found"; + } +} +__name(version, "version"); +function generateDependencyReport() { + const report = []; + const addVersion = /* @__PURE__ */ __name((name) => report.push(`- ${name}: ${version(name)}`), "addVersion"); + report.push("Core Dependencies"); + addVersion("@discordjs/voice"); + addVersion("prism-media"); + report.push(""); + report.push("Opus Libraries"); + addVersion("@discordjs/opus"); + addVersion("opusscript"); + report.push(""); + report.push("Encryption Libraries"); + addVersion("sodium-native"); + addVersion("sodium"); + addVersion("libsodium-wrappers"); + addVersion("tweetnacl"); + report.push(""); + report.push("FFmpeg"); + try { + const info = import_prism_media3.default.FFmpeg.getInfo(); + report.push(`- version: ${info.version}`); + report.push(`- libopus: ${info.output.includes("--enable-libopus") ? "yes" : "no"}`); + } catch { + report.push("- not found"); + } + return [ + "-".repeat(50), + ...report, + "-".repeat(50) + ].join("\n"); +} +__name(generateDependencyReport, "generateDependencyReport"); + +// src/util/entersState.ts +var import_node_events8 = require("events"); + +// src/util/abortAfter.ts +function abortAfter(delay) { + const ac = new AbortController(); + const timeout = setTimeout(() => ac.abort(), delay); + ac.signal.addEventListener("abort", () => clearTimeout(timeout)); + return [ + ac, + ac.signal + ]; +} +__name(abortAfter, "abortAfter"); + +// src/util/entersState.ts +async function entersState(target, status, timeoutOrSignal) { + if (target.state.status !== status) { + const [ac, signal] = typeof timeoutOrSignal === "number" ? abortAfter(timeoutOrSignal) : [ + void 0, + timeoutOrSignal + ]; + try { + await (0, import_node_events8.once)(target, status, { + signal + }); + } finally { + ac?.abort(); + } + } + return target; +} +__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) { + const channels = opusHead.readUInt8(9); + const sampleRate = opusHead.readUInt32LE(12); + return channels === 2 && sampleRate === 48e3; +} +__name(validateDiscordOpusHead, "validateDiscordOpusHead"); +async function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHead) { + return new Promise((resolve2, reject) => { + 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); + stream.off("end", onClose); + stream.pause(); + resolved = type; + if (stream.readableEnded) { + resolve2({ + stream: import_node_stream3.Readable.from(readBuffer), + type + }); + } else { + if (readBuffer.length > 0) { + stream.push(readBuffer); + } + resolve2({ + stream, + type + }); + } + }, "finish"); + const foundHead = /* @__PURE__ */ __name((type) => (head) => { + if (validator(head)) { + finish(type); + } + }, "foundHead"); + const webm = new import_prism_media4.default.opus.WebmDemuxer(); + webm.once("error", noop); + webm.on("head", foundHead(StreamType.WebmOpus)); + const ogg = new import_prism_media4.default.opus.OggDemuxer(); + ogg.once("error", noop); + ogg.on("head", foundHead(StreamType.OggOpus)); + const onClose = /* @__PURE__ */ __name(() => { + if (!resolved) { + finish(StreamType.Arbitrary); + } + }, "onClose"); + const onData = /* @__PURE__ */ __name((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(); + import_node_process.default.nextTick(onClose); + } + }, "onData"); + stream.once("error", reject); + stream.on("data", onData); + stream.once("close", onClose); + stream.once("end", onClose); + }); +} +__name(demuxProbe, "demuxProbe"); + +// src/index.ts +var version2 = "[VI]{{inject}}[/VI]"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AudioPlayer, + AudioPlayerError, + AudioPlayerStatus, + AudioReceiveStream, + AudioResource, + EndBehaviorType, + NoSubscriberBehavior, + PlayerSubscription, + SSRCMap, + SpeakingMap, + StreamType, + VoiceConnection, + VoiceConnectionDisconnectReason, + VoiceConnectionStatus, + VoiceReceiver, + createAudioPlayer, + createAudioResource, + createDefaultAudioReceiveStreamOptions, + demuxProbe, + entersState, + generateDependencyReport, + getGroups, + getVoiceConnection, + getVoiceConnections, + joinVoiceChannel, + 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 new file mode 100644 index 0000000..08204cf --- /dev/null +++ b/node_modules/@discordjs/voice/dist/index.js.map @@ -0,0 +1 @@ +{"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 = '[VI]{{inject}}[/VI]' 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 (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 *\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 (typeof 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 (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\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 (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\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 || typeof 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 (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\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 '[VI]{{inject}}[/VI]';\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAAA;;AAAA;;;ACEA,IAAAC,sBAA6B;;;ACF7B,iBAA+B;AAkBxB,SAASC,8BAA8BC,QAAoB;AACjE,SAAO;IACNC,IAAIC,0BAAeC;;IAEnBC,GAAG;MACFC,UAAUL,OAAOM;MACjBC,YAAYP,OAAOQ;MACnBC,WAAWT,OAAOU;MAClBC,WAAWX,OAAOY;IACnB;EACD;AACD;AAXgBb;AAchB,IAAMc,SAAS,oBAAIC,IAAAA;AACnBD,OAAOE,IAAI,WAAW,oBAAID,IAAAA,CAAAA;AAE1B,SAASE,iBAAiBC,OAAe;AACxC,QAAMC,WAAWL,OAAOM,IAAIF,KAAAA;AAC5B,MAAIC;AAAU,WAAOA;AACrB,QAAME,MAAM,oBAAIN,IAAAA;AAChBD,SAAOE,IAAIE,OAAOG,GAAAA;AAClB,SAAOA;AACR;AANSJ;AAcF,SAASK,YAAY;AAC3B,SAAOR;AACR;AAFgBQ;AA0BT,SAASC,oBAAoBL,QAAQ,WAAW;AACtD,SAAOJ,OAAOM,IAAIF,KAAAA;AACnB;AAFgBK;AAWT,SAASC,mBAAmBjB,SAAiBW,QAAQ,WAAW;AACtE,SAAOK,oBAAoBL,KAAAA,GAAQE,IAAIb,OAAAA;AACxC;AAFgBiB;AAIT,SAASC,uBAAuBC,iBAAkC;AACxE,SAAOH,oBAAoBG,gBAAgBC,WAAWT,KAAK,GAAGU,OAAOF,gBAAgBC,WAAWpB,OAAO;AACxG;AAFgBkB;AAIT,SAASI,qBAAqBH,iBAAkC;AACtE,SAAOT,iBAAiBS,gBAAgBC,WAAWT,KAAK,EAAEF,IAAIU,gBAAgBC,WAAWpB,SAASmB,eAAAA;AACnG;AAFgBG;AAOhB,IAAMC,eAAe;AA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,WAAW;AACnCD,eAAOe,IAAI,QAAQC,MAAAA;AACnBhB,eAAOkB,MAAK;AACZuB,4BAAAA,QAAQC,SAASzB,OAAAA;MAClB;IACD,GAXe;AAafjB,WAAO6B,KAAK,SAASxB,MAAAA;AACrBL,WAAO+B,GAAG,QAAQf,MAAAA;AAClBhB,WAAO6B,KAAK,SAASZ,OAAAA;AACrBjB,WAAO6B,KAAK,OAAOZ,OAAAA;EACpB,CAAA;AACD;AArFsBlB;;;ArBhBf,IAAM4C,WAAU;","names":["version","import_node_events","createJoinVoiceChannelPayload","config","op","GatewayOpcodes","VoiceStateUpdate","d","guild_id","guildId","channel_id","channelId","self_deaf","selfDeaf","self_mute","selfMute","groups","Map","set","getOrCreateGroup","group","existing","get","map","getGroups","getVoiceConnections","getVoiceConnection","untrackVoiceConnection","voiceConnection","joinConfig","delete","trackVoiceConnection","FRAME_LENGTH","audioCycleInterval","nextTime","audioPlayers","audioCycleStep","available","filter","player","checkPlayable","prepareNextAudioFrame","players","nextPlayer","shift","setTimeout","Date","now","setImmediate","hasAudioPlayer","target","includes","addAudioPlayer","push","length","deleteAudioPlayer","index","indexOf","splice","clearTimeout","import_node_buffer","import_node_events","import_v4","libs","sodium","open","buffer","nonce","secretKey","output","Buffer","allocUnsafe","length","crypto_box_MACBYTES","crypto_secretbox_open_easy","close","opusPacket","crypto_secretbox_easy","random","num","randombytes_buf","api","tweetnacl","secretbox","randomBytes","fallbackError","Error","methods","libName","Object","keys","lib","require","ready","assign","noop","import_node_buffer","parseLocalPacket","message","packet","Buffer","from","ip","slice","indexOf","toString","isIPv4","Error","port","readUInt16BE","length","KEEP_ALIVE_INTERVAL","MAX_COUNTER_VALUE","VoiceUDPSocket","EventEmitter","keepAliveCounter","remote","socket","createSocket","on","error","emit","buffer","onMessage","keepAliveBuffer","alloc","keepAliveInterval","setInterval","keepAlive","setImmediate","writeUInt32LE","send","destroy","close","clearInterval","performIPDiscovery","ssrc","Promise","resolve","reject","listener","off","once","discoveryBuffer","writeUInt16BE","writeUInt32BE","import_node_events","VoiceWebSocket","EventEmitter","missedHeartbeats","address","debug","ws","WebSocket","onmessage","err","onMessage","onopen","emit","onerror","Error","error","onclose","lastHeartbeatAck","lastHeartbeatSend","message","destroy","setHeartbeatInterval","close","event","data","packet","JSON","parse","op","VoiceOpcodes","HeartbeatAck","Date","now","ping","sendPacket","stringified","stringify","send","sendHeartbeat","nonce","Heartbeat","d","ms","heartbeatInterval","clearInterval","setInterval","CHANNELS","TIMESTAMP_INC","MAX_NONCE_SIZE","SUPPORTED_ENCRYPTION_MODES","NetworkingStatusCode","OpeningWs","Identifying","UdpHandshaking","SelectingProtocol","Ready","Resuming","Closed","nonce","Buffer","alloc","stringifyState","state","JSON","stringify","ws","Reflect","has","udp","chooseEncryptionMode","options","option","find","includes","Error","join","randomNBit","numberOfBits","Math","floor","random","Networking","EventEmitter","debug","onWsOpen","bind","onChildError","onWsPacket","onWsClose","onWsDebug","onUdpDebug","onUdpClose","message","emit","_state","code","createWebSocket","endpoint","connectionOptions","destroy","newState","oldWs","get","newWs","off","on","noop","oldUdp","newUdp","oldState","VoiceWebSocket","Boolean","once","error","packet","op","VoiceOpcodes","Identify","d","server_id","serverId","user_id","userId","session_id","sessionId","token","sendPacket","Resume","canResume","Hello","setHeartbeatInterval","heartbeat_interval","ip","port","ssrc","modes","VoiceUDPSocket","performIPDiscovery","then","localConfig","SelectProtocol","protocol","data","address","mode","catch","connectionData","SessionDescription","encryptionMode","secret_key","secretKey","Uint8Array","sequence","timestamp","nonceBuffer","speaking","packetsPlayed","Resumed","prepareAudioPacket","opusPacket","preparedPacket","createAudioPacket","dispatchAudio","playAudioPacket","undefined","audioPacket","setSpeaking","send","Speaking","delay","packetBuffer","writeUIntBE","copy","concat","encryptOpusPacket","writeUInt32BE","methods","close","slice","import_node_buffer","import_v4","import_node_buffer","import_node_events","AudioPlayerError","Error","error","resource","message","name","stack","PlayerSubscription","connection","player","unsubscribe","SILENCE_FRAME","Buffer","from","NoSubscriberBehavior","Pause","Play","Stop","AudioPlayerStatus","AutoPaused","Buffering","Idle","Paused","Playing","stringifyState","state","JSON","stringify","resource","Reflect","has","stepTimeout","AudioPlayer","EventEmitter","subscribers","options","_state","status","behaviors","noSubscriber","maxMissedFrames","debug","message","emit","playable","filter","connection","VoiceConnectionStatus","Ready","map","subscribe","existingSubscription","find","subscription","PlayerSubscription","push","setImmediate","unsubscribe","index","indexOf","exists","splice","setSpeaking","newState","oldState","newResource","get","playStream","on","noop","off","onStreamError","audioPlayer","undefined","destroy","read","onFailureCallback","onReadableCallback","_signalStopSpeaking","deleteAudioPlayer","addAudioPlayer","didChangeResources","play","ended","Error","error","AudioPlayerError","once","started","missedFrames","playbackDuration","pause","interpolateSilence","silencePacketsRemaining","unpause","stop","force","silencePaddingFrames","silenceRemaining","checkPlayable","readable","_stepDispatch","dispatchAudio","_stepPrepare","length","_preparePacket","packet","receivers","prepareAudioPacket","createAudioPlayer","EndBehaviorType","Manual","AfterSilence","AfterInactivity","createDefaultAudioReceiveStreamOptions","end","behavior","AudioReceiveStream","Readable","options","objectMode","push","buffer","compare","SILENCE_FRAME","endTimeout","renewEndTimeout","clearTimeout","setTimeout","duration","_read","import_node_events","SSRCMap","EventEmitter","map","Map","update","data","existing","get","audioSSRC","newValue","set","emit","target","values","userId","undefined","delete","entries","import_node_events","SpeakingMap","EventEmitter","users","Map","speakingTimeouts","onPacket","userId","timeout","get","clearTimeout","set","Date","now","emit","startTimeout","setTimeout","delete","DELAY","VoiceReceiver","voiceConnection","ssrcMap","SSRCMap","speaking","SpeakingMap","subscriptions","Map","connectionData","onWsPacket","bind","onUdpMessage","packet","op","VoiceOpcodes","ClientDisconnect","d","user_id","delete","Speaking","ssrc","update","userId","audioSSRC","ClientConnect","audio_ssrc","videoSSRC","video_ssrc","undefined","decrypt","buffer","mode","nonce","secretKey","end","copy","length","decrypted","methods","open","slice","Buffer","from","parsePacket","headerExtensionLength","readUInt16BE","subarray","msg","readUInt32BE","userData","get","onPacket","stream","encryptionMode","nonceBuffer","push","destroy","Error","subscribe","options","existing","AudioReceiveStream","createDefaultAudioReceiveStreamOptions","once","set","VoiceConnectionStatus","Connecting","Destroyed","Disconnected","Ready","Signalling","VoiceConnectionDisconnectReason","WebSocketClose","AdapterUnavailable","EndpointRemoved","Manual","VoiceConnection","EventEmitter","joinConfig","options","debug","message","emit","rejoinAttempts","receiver","VoiceReceiver","onNetworkingClose","bind","onNetworkingStateChange","onNetworkingError","onNetworkingDebug","adapter","adapterCreator","onVoiceServerUpdate","data","addServerPacket","onVoiceStateUpdate","addStatePacket","destroy","_state","status","packets","server","undefined","state","newState","oldState","oldNetworking","Reflect","get","newNetworking","oldSubscription","newSubscription","on","noop","off","updateReceiveBindings","stream","subscriptions","values","destroyed","unsubscribe","packet","endpoint","configureNetworking","reason","self_deaf","selfDeaf","self_mute","selfMute","channel_id","channelId","oldWs","newWs","oldUdp","newUdp","onWsPacket","onUdpMessage","connectionData","networking","Networking","serverId","guild_id","token","sessionId","session_id","userId","user_id","Boolean","once","code","closeCode","sendPayload","createJoinVoiceChannelPayload","NetworkingStatusCode","Closed","error","prepareAudioPacket","buffer","dispatchAudio","playOpusPacket","adapterAvailable","Error","getVoiceConnection","guildId","group","untrackVoiceConnection","disconnect","subscription","rejoin","notReady","Object","assign","setSpeaking","enabled","subscribe","player","ping","ws","udp","onSubscriptionRemoved","createVoiceConnection","payload","existing","voiceConnection","trackVoiceConnection","joinVoiceChannel","options","joinConfig","selfDeaf","selfMute","group","createVoiceConnection","adapterCreator","debug","import_node_stream","import_prism_media","FFMPEG_PCM_ARGUMENTS","FFMPEG_OPUS_ARGUMENTS","StreamType","Arbitrary","OggOpus","Opus","Raw","WebmOpus","TransformerType","FFmpegOgg","FFmpegPCM","InlineVolume","OggOpusDemuxer","OpusDecoder","OpusEncoder","WebmOpusDemuxer","Node","edges","type","addEdge","edge","push","from","NODES","Map","streamType","Object","values","set","getNode","node","get","Error","to","cost","transformer","prism","opus","Encoder","rate","channels","frameSize","Decoder","OggDemuxer","WebmDemuxer","FFMPEG_PCM_EDGE","input","FFmpeg","args","VolumeTransformer","canEnableFFmpegOptimizations","getInfo","output","includes","FFMPEG_OGG_EDGE","findPath","constraints","goal","path","depth","Number","POSITIVE_INFINITY","currentBest","next","constructPipeline","step","current","findPipeline","constraint","AudioResource","playbackDuration","started","silenceRemaining","edges","streams","metadata","silencePaddingFrames","playStream","length","pipeline","noop","stream","prism","VolumeTransformer","volume","opus","Encoder","encoder","once","readable","real","ended","readableEnded","destroyed","read","SILENCE_FRAME","packet","VOLUME_CONSTRAINT","path","some","edge","type","TransformerType","InlineVolume","NO_CONSTRAINT","inferStreamType","streamType","StreamType","Opus","hasVolume","Decoder","Raw","OggDemuxer","WebmDemuxer","Arbitrary","createAudioResource","input","options","inputType","needsInlineVolume","Boolean","inlineVolume","analysis","transformerPipeline","findPipeline","Error","map","transformer","unshift","import_prism_media","findPackageJSON","dir","packageName","depth","undefined","attemptedPath","resolve","pkg","require","name","Error","version","dirname","generateDependencyReport","report","addVersion","push","info","prism","FFmpeg","getInfo","output","includes","repeat","join","import_node_events","abortAfter","delay","ac","AbortController","timeout","setTimeout","abort","signal","addEventListener","clearTimeout","entersState","target","status","timeoutOrSignal","state","ac","signal","abortAfter","undefined","once","abort","import_node_buffer","import_node_stream","import_prism_media","validateDiscordOpusHead","opusHead","channels","readUInt8","sampleRate","readUInt32LE","demuxProbe","stream","probeSize","validator","Promise","resolve","reject","readableObjectMode","Error","readableEnded","readBuffer","Buffer","alloc","resolved","finish","type","off","onData","onClose","pause","Readable","from","length","push","foundHead","head","webm","prism","opus","WebmDemuxer","once","noop","on","StreamType","WebmOpus","ogg","OggDemuxer","OggOpus","Arbitrary","buffer","concat","write","process","nextTick","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 new file mode 100644 index 0000000..1d8ef9b --- /dev/null +++ b/node_modules/@discordjs/voice/dist/index.mjs @@ -0,0 +1,2617 @@ +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, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw new Error('Dynamic require of "' + x + '" is not supported'); +}); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/VoiceConnection.ts +import { EventEmitter as EventEmitter7 } from "node:events"; + +// src/DataStore.ts +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, + self_deaf: config.selfDeaf, + self_mute: config.selfMute + } + }; +} +__name(createJoinVoiceChannelPayload, "createJoinVoiceChannelPayload"); +var groups = /* @__PURE__ */ new Map(); +groups.set("default", /* @__PURE__ */ new Map()); +function getOrCreateGroup(group) { + const existing = groups.get(group); + if (existing) + return existing; + const map = /* @__PURE__ */ new Map(); + groups.set(group, map); + return map; +} +__name(getOrCreateGroup, "getOrCreateGroup"); +function getGroups() { + return groups; +} +__name(getGroups, "getGroups"); +function getVoiceConnections(group = "default") { + return groups.get(group); +} +__name(getVoiceConnections, "getVoiceConnections"); +function getVoiceConnection(guildId, group = "default") { + return getVoiceConnections(group)?.get(guildId); +} +__name(getVoiceConnection, "getVoiceConnection"); +function untrackVoiceConnection(voiceConnection) { + return getVoiceConnections(voiceConnection.joinConfig.group)?.delete(voiceConnection.joinConfig.guildId); +} +__name(untrackVoiceConnection, "untrackVoiceConnection"); +function trackVoiceConnection(voiceConnection) { + return getOrCreateGroup(voiceConnection.joinConfig.group).set(voiceConnection.joinConfig.guildId, voiceConnection); +} +__name(trackVoiceConnection, "trackVoiceConnection"); +var FRAME_LENGTH = 20; +var audioCycleInterval; +var nextTime = -1; +var audioPlayers = []; +function audioCycleStep() { + if (nextTime === -1) + return; + nextTime += FRAME_LENGTH; + const available = audioPlayers.filter((player) => player.checkPlayable()); + for (const player of available) { + player["_stepDispatch"](); + } + prepareNextAudioFrame(available); +} +__name(audioCycleStep, "audioCycleStep"); +function prepareNextAudioFrame(players) { + const nextPlayer = players.shift(); + if (!nextPlayer) { + if (nextTime !== -1) { + audioCycleInterval = setTimeout(() => audioCycleStep(), nextTime - Date.now()); + } + return; + } + nextPlayer["_stepPrepare"](); + setImmediate(() => prepareNextAudioFrame(players)); +} +__name(prepareNextAudioFrame, "prepareNextAudioFrame"); +function hasAudioPlayer(target) { + return audioPlayers.includes(target); +} +__name(hasAudioPlayer, "hasAudioPlayer"); +function addAudioPlayer(player) { + if (hasAudioPlayer(player)) + return player; + audioPlayers.push(player); + if (audioPlayers.length === 1) { + nextTime = Date.now(); + setImmediate(() => audioCycleStep()); + } + return player; +} +__name(addAudioPlayer, "addAudioPlayer"); +function deleteAudioPlayer(player) { + const index = audioPlayers.indexOf(player); + if (index === -1) + return; + audioPlayers.splice(index, 1); + if (audioPlayers.length === 0) { + nextTime = -1; + if (typeof audioCycleInterval !== "undefined") + 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 = Buffer3.from(message); + const ip = packet.slice(8, packet.indexOf(0, 8)).toString("utf8"); + if (!isIPv4(ip)) { + throw new Error("Malformed IP address"); + } + const port = packet.readUInt16BE(packet.length - 2); + return { + ip, + port + }; +} +__name(parseLocalPacket, "parseLocalPacket"); +var KEEP_ALIVE_INTERVAL = 5e3; +var MAX_COUNTER_VALUE = 2 ** 32 - 1; +var VoiceUDPSocket = class extends EventEmitter { + /** + * The counter used in the keep alive mechanism. + */ + keepAliveCounter = 0; + /** + * Creates a new VoiceUDPSocket. + * + * @param remote - Details of the remote socket + */ + constructor(remote) { + super(); + 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.keepAliveBuffer = Buffer3.alloc(8); + this.keepAliveInterval = setInterval(() => this.keepAlive(), KEEP_ALIVE_INTERVAL); + setImmediate(() => this.keepAlive()); + } + /** + * Called when a message is received on the UDP socket. + * + * @param buffer - The received buffer + */ + onMessage(buffer) { + this.emit("message", buffer); + } + /** + * Called at a regular interval to check whether we are still able to send datagrams to Discord. + */ + keepAlive() { + this.keepAliveBuffer.writeUInt32LE(this.keepAliveCounter, 0); + this.send(this.keepAliveBuffer); + this.keepAliveCounter++; + if (this.keepAliveCounter > MAX_COUNTER_VALUE) { + this.keepAliveCounter = 0; + } + } + /** + * Sends a buffer to Discord. + * + * @param buffer - The buffer to send + */ + send(buffer) { + 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(); + } catch { + } + clearInterval(this.keepAliveInterval); + } + /** + * 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 { + if (message.readUInt16BE(0) !== 2) + return; + const packet = parseLocalPacket(message); + this.socket.off("message", listener); + resolve2(packet); + } catch { + } + }, "listener"); + this.socket.on("message", listener); + this.socket.once("close", () => reject(new Error("Cannot perform IP discovery - socket closed"))); + const discoveryBuffer = Buffer3.alloc(74); + discoveryBuffer.writeUInt16BE(1, 0); + discoveryBuffer.writeUInt16BE(70, 2); + discoveryBuffer.writeUInt32BE(ssrc, 4); + this.send(discoveryBuffer); + }); + } +}; +__name(VoiceUDPSocket, "VoiceUDPSocket"); + +// src/networking/VoiceWebSocket.ts +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 number of consecutively missed heartbeats. + */ + missedHeartbeats = 0; + /** + * Creates a new VoiceWebSocket. + * + * @param address - The address to connect to + */ + constructor(address, debug) { + super(); + this.ws = new WebSocket(address); + 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 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; + this.debug?.(`<< ${event.data}`); + let packet; + try { + packet = JSON.parse(event.data); + } catch (error) { + const err = error; + this.emit("error", err); + return; + } + if (packet.op === VoiceOpcodes.HeartbeatAck) { + this.lastHeartbeatAck = Date.now(); + this.missedHeartbeats = 0; + this.ping = this.lastHeartbeatAck - this.lastHeartbeatSend; + } + 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}`); + this.ws.send(stringified); + return; + } catch (error) { + const err = error; + this.emit("error", err); + } + } + /** + * Sends a heartbeat over the WebSocket. + */ + sendHeartbeat() { + this.lastHeartbeatSend = Date.now(); + this.missedHeartbeats++; + const nonce2 = this.lastHeartbeatSend; + 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") + clearInterval(this.heartbeatInterval); + if (ms > 0) { + this.heartbeatInterval = setInterval(() => { + if (this.lastHeartbeatSend !== 0 && this.missedHeartbeats >= 3) { + this.ws.close(); + this.setHeartbeatInterval(-1); + } + this.sendHeartbeat(); + }, ms); + } + } +}; +__name(VoiceWebSocket, "VoiceWebSocket"); + +// 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 NetworkingStatusCode; +(function(NetworkingStatusCode2) { + NetworkingStatusCode2[NetworkingStatusCode2["OpeningWs"] = 0] = "OpeningWs"; + NetworkingStatusCode2[NetworkingStatusCode2["Identifying"] = 1] = "Identifying"; + NetworkingStatusCode2[NetworkingStatusCode2["UdpHandshaking"] = 2] = "UdpHandshaking"; + NetworkingStatusCode2[NetworkingStatusCode2["SelectingProtocol"] = 3] = "SelectingProtocol"; + NetworkingStatusCode2[NetworkingStatusCode2["Ready"] = 4] = "Ready"; + NetworkingStatusCode2[NetworkingStatusCode2["Resuming"] = 5] = "Resuming"; + NetworkingStatusCode2[NetworkingStatusCode2["Closed"] = 6] = "Closed"; +})(NetworkingStatusCode || (NetworkingStatusCode = {})); +var nonce = Buffer4.alloc(24); +function stringifyState(state) { + return JSON.stringify({ + ...state, + ws: Reflect.has(state, "ws"), + udp: Reflect.has(state, "udp") + }); +} +__name(stringifyState, "stringifyState"); +function chooseEncryptionMode(options) { + const option = options.find((option2) => SUPPORTED_ENCRYPTION_MODES.includes(option2)); + if (!option) { + throw new Error(`No compatible encryption modes. Available include: ${options.join(", ")}`); + } + return option; +} +__name(chooseEncryptionMode, "chooseEncryptionMode"); +function randomNBit(numberOfBits) { + return Math.floor(Math.random() * 2 ** numberOfBits); +} +__name(randomNBit, "randomNBit"); +var Networking = class extends EventEmitter3 { + /** + * Creates a new Networking instance. + */ + constructor(options, debug) { + super(); + this.onWsOpen = this.onWsOpen.bind(this); + this.onChildError = this.onChildError.bind(this); + this.onWsPacket = this.onWsPacket.bind(this); + this.onWsClose = this.onWsClose.bind(this); + this.onWsDebug = this.onWsDebug.bind(this); + this.onUdpDebug = this.onUdpDebug.bind(this); + this.onUdpClose = this.onUdpClose.bind(this); + this.debug = debug ? (message) => this.emit("debug", message) : null; + this._state = { + code: NetworkingStatusCode.OpeningWs, + ws: this.createWebSocket(options.endpoint), + connectionOptions: options + }; + } + /** + * Destroys the Networking instance, transitioning it into the Closed state. + */ + destroy() { + this.state = { + code: NetworkingStatusCode.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"); + if (oldWs && oldWs !== newWs) { + oldWs.off("debug", this.onWsDebug); + oldWs.on("error", noop); + oldWs.off("error", this.onChildError); + oldWs.off("open", this.onWsOpen); + oldWs.off("packet", this.onWsPacket); + oldWs.off("close", this.onWsClose); + oldWs.destroy(); + } + const oldUdp = Reflect.get(this._state, "udp"); + const newUdp = Reflect.get(newState, "udp"); + if (oldUdp && oldUdp !== newUdp) { + oldUdp.on("error", noop); + oldUdp.off("error", this.onChildError); + oldUdp.off("close", this.onUdpClose); + oldUdp.off("debug", this.onUdpDebug); + oldUdp.destroy(); + } + const oldState = this._state; + this._state = newState; + this.emit("stateChange", oldState, newState); + this.debug?.(`state change: +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); + ws.once("open", this.onWsOpen); + ws.on("packet", this.onWsPacket); + ws.once("close", this.onWsClose); + 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 === NetworkingStatusCode.OpeningWs) { + const packet = { + op: VoiceOpcodes2.Identify, + d: { + server_id: this.state.connectionOptions.serverId, + user_id: this.state.connectionOptions.userId, + session_id: this.state.connectionOptions.sessionId, + token: this.state.connectionOptions.token + } + }; + this.state.ws.sendPacket(packet); + this.state = { + ...this.state, + code: NetworkingStatusCode.Identifying + }; + } else if (this.state.code === NetworkingStatusCode.Resuming) { + const packet = { + op: VoiceOpcodes2.Resume, + d: { + server_id: this.state.connectionOptions.serverId, + session_id: this.state.connectionOptions.sessionId, + token: this.state.connectionOptions.token + } + }; + 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 === NetworkingStatusCode.Ready) { + this.state = { + ...this.state, + code: NetworkingStatusCode.Resuming, + ws: this.createWebSocket(this.state.connectionOptions.endpoint) + }; + } else if (this.state.code !== NetworkingStatusCode.Closed) { + this.destroy(); + 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 === NetworkingStatusCode.Ready) { + this.state = { + ...this.state, + code: NetworkingStatusCode.Resuming, + ws: this.createWebSocket(this.state.connectionOptions.endpoint) + }; + } + } + /** + * 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 !== NetworkingStatusCode.Closed) { + this.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval); + } else if (packet.op === VoiceOpcodes2.Ready && this.state.code === NetworkingStatusCode.Identifying) { + const { ip, port, ssrc, modes } = packet.d; + const udp = new VoiceUDPSocket({ + ip, + port + }); + udp.on("error", this.onChildError); + udp.on("debug", this.onUdpDebug); + udp.once("close", this.onUdpClose); + udp.performIPDiscovery(ssrc).then((localConfig) => { + if (this.state.code !== NetworkingStatusCode.UdpHandshaking) + return; + this.state.ws.sendPacket({ + op: VoiceOpcodes2.SelectProtocol, + d: { + protocol: "udp", + data: { + address: localConfig.ip, + port: localConfig.port, + mode: chooseEncryptionMode(modes) + } + } + }); + this.state = { + ...this.state, + code: NetworkingStatusCode.SelectingProtocol + }; + }).catch((error) => this.emit("error", error)); + this.state = { + ...this.state, + code: NetworkingStatusCode.UdpHandshaking, + udp, + connectionData: { + ssrc + } + }; + } else if (packet.op === VoiceOpcodes2.SessionDescription && this.state.code === NetworkingStatusCode.SelectingProtocol) { + const { mode: encryptionMode, secret_key: secretKey } = packet.d; + this.state = { + ...this.state, + code: NetworkingStatusCode.Ready, + connectionData: { + ...this.state.connectionData, + encryptionMode, + secretKey: new Uint8Array(secretKey), + sequence: randomNBit(16), + timestamp: randomNBit(32), + nonce: 0, + nonceBuffer: Buffer4.alloc(24), + speaking: false, + packetsPlayed: 0 + } + }; + } else if (packet.op === VoiceOpcodes2.Resumed && this.state.code === NetworkingStatusCode.Resuming) { + this.state = { + ...this.state, + code: NetworkingStatusCode.Ready + }; + 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 !== NetworkingStatusCode.Ready) + return; + 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 !== NetworkingStatusCode.Ready) + return false; + if (typeof state.preparedPacket !== "undefined") { + 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 !== NetworkingStatusCode.Ready) + return; + const { connectionData } = state; + connectionData.packetsPlayed++; + connectionData.sequence++; + connectionData.timestamp += TIMESTAMP_INC; + if (connectionData.sequence >= 2 ** 16) + connectionData.sequence = 0; + if (connectionData.timestamp >= 2 ** 32) + connectionData.timestamp = 0; + 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 !== NetworkingStatusCode.Ready) + return; + if (state.connectionData.speaking === speaking) + return; + state.connectionData.speaking = speaking; + state.ws.sendPacket({ + op: VoiceOpcodes2.Speaking, + d: { + speaking: speaking ? 1 : 0, + delay: 0, + ssrc: state.connectionData.ssrc + } + }); + } + /** + * 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 = Buffer4.alloc(12); + packetBuffer[0] = 128; + packetBuffer[1] = 120; + const { sequence, timestamp, ssrc } = connectionData; + packetBuffer.writeUIntBE(sequence, 2, 2); + packetBuffer.writeUIntBE(timestamp, 4, 4); + packetBuffer.writeUIntBE(ssrc, 8, 4); + packetBuffer.copy(nonce, 0, 0, 12); + 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") { + connectionData.nonce++; + if (connectionData.nonce > MAX_NONCE_SIZE) + connectionData.nonce = 0; + connectionData.nonceBuffer.writeUInt32BE(connectionData.nonce, 0); + return [ + methods.close(opusPacket, connectionData.nonceBuffer, secretKey), + connectionData.nonceBuffer.slice(0, 4) + ]; + } else if (encryptionMode === "xsalsa20_poly1305_suffix") { + const random = methods.random(24, connectionData.nonceBuffer); + return [ + methods.close(opusPacket, random, secretKey), + random + ]; + } + return [ + methods.close(opusPacket, nonce, secretKey) + ]; + } +}; +__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 { Buffer as Buffer5 } from "node:buffer"; +import { EventEmitter as EventEmitter4 } from "node:events"; + +// src/audio/AudioPlayerError.ts +var AudioPlayerError = class extends Error { + constructor(error, resource) { + super(error.message); + this.resource = resource; + this.name = error.name; + this.stack = error.stack; + } +}; +__name(AudioPlayerError, "AudioPlayerError"); + +// src/audio/PlayerSubscription.ts +var PlayerSubscription = class { + constructor(connection, 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); + } +}; +__name(PlayerSubscription, "PlayerSubscription"); + +// src/audio/AudioPlayer.ts +var SILENCE_FRAME = Buffer5.from([ + 248, + 255, + 254 +]); +var NoSubscriberBehavior; +(function(NoSubscriberBehavior2) { + NoSubscriberBehavior2[ + /** + * Pauses playing the stream until a voice connection becomes available. + */ + "Pause" + ] = "pause"; + NoSubscriberBehavior2[ + /** + * Continues to play through the resource regardless. + */ + "Play" + ] = "play"; + NoSubscriberBehavior2[ + /** + * The player stops and enters the Idle state. + */ + "Stop" + ] = "stop"; +})(NoSubscriberBehavior || (NoSubscriberBehavior = {})); +var AudioPlayerStatus; +(function(AudioPlayerStatus2) { + AudioPlayerStatus2[ + /** + * When the player has paused itself. Only possible with the "pause" no subscriber behavior. + */ + "AutoPaused" + ] = "autopaused"; + AudioPlayerStatus2[ + /** + * When the player is waiting for an audio resource to become readable before transitioning to Playing. + */ + "Buffering" + ] = "buffering"; + AudioPlayerStatus2[ + /** + * When there is currently no resource for the player to be playing. + */ + "Idle" + ] = "idle"; + AudioPlayerStatus2[ + /** + * When the player has been manually paused. + */ + "Paused" + ] = "paused"; + AudioPlayerStatus2[ + /** + * When the player is actively playing an audio resource. + */ + "Playing" + ] = "playing"; +})(AudioPlayerStatus || (AudioPlayerStatus = {})); +function stringifyState2(state) { + return JSON.stringify({ + ...state, + resource: Reflect.has(state, "resource"), + stepTimeout: Reflect.has(state, "stepTimeout") + }); +} +__name(stringifyState2, "stringifyState"); +var AudioPlayer = class extends EventEmitter4 { + /** + * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio + * to the streams in this list. + */ + subscribers = []; + /** + * Creates a new AudioPlayer. + */ + constructor(options = {}) { + super(); + this._state = { + status: AudioPlayerStatus.Idle + }; + this.behaviors = { + noSubscriber: NoSubscriberBehavior.Pause, + maxMissedFrames: 5, + ...options.behaviors + }; + 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 === VoiceConnectionStatus.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) { + const subscription = new PlayerSubscription(connection, this); + this.subscribers.push(subscription); + setImmediate(() => this.emit("subscribe", subscription)); + return subscription; + } + 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; + if (exists) { + this.subscribers.splice(index, 1); + subscription.connection.setSpeaking(false); + this.emit("unsubscribe", subscription); + } + 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"); + if (oldState.status !== AudioPlayerStatus.Idle && oldState.resource !== newResource) { + oldState.resource.playStream.on("error", noop); + oldState.resource.playStream.off("error", oldState.onStreamError); + oldState.resource.audioPlayer = void 0; + oldState.resource.playStream.destroy(); + oldState.resource.playStream.read(); + } + if (oldState.status === AudioPlayerStatus.Buffering && (newState.status !== AudioPlayerStatus.Buffering || newState.resource !== oldState.resource)) { + oldState.resource.playStream.off("end", oldState.onFailureCallback); + oldState.resource.playStream.off("close", oldState.onFailureCallback); + oldState.resource.playStream.off("finish", oldState.onFailureCallback); + oldState.resource.playStream.off("readable", oldState.onReadableCallback); + } + if (newState.status === AudioPlayerStatus.Idle) { + this._signalStopSpeaking(); + deleteAudioPlayer(this); + } + if (newResource) { + addAudioPlayer(this); + } + const didChangeResources = oldState.status !== AudioPlayerStatus.Idle && newState.status === AudioPlayerStatus.Playing && oldState.resource !== newState.resource; + this._state = newState; + this.emit("stateChange", oldState, this._state); + if (oldState.status !== newState.status || didChangeResources) { + this.emit(newState.status, oldState, this._state); + } + this.debug?.(`state change: +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."); + } + if (resource.audioPlayer) { + if (resource.audioPlayer === this) { + return; + } + throw new Error("Resource is already being played by another audio player."); + } + resource.audioPlayer = this; + const onStreamError = /* @__PURE__ */ __name((error) => { + if (this.state.status !== AudioPlayerStatus.Idle) { + this.emit("error", new AudioPlayerError(error, this.state.resource)); + } + if (this.state.status !== AudioPlayerStatus.Idle && this.state.resource === resource) { + this.state = { + status: AudioPlayerStatus.Idle + }; + } + }, "onStreamError"); + resource.playStream.once("error", onStreamError); + if (resource.started) { + this.state = { + status: AudioPlayerStatus.Playing, + missedFrames: 0, + playbackDuration: 0, + resource, + onStreamError + }; + } else { + const onReadableCallback = /* @__PURE__ */ __name(() => { + if (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) { + this.state = { + status: AudioPlayerStatus.Playing, + missedFrames: 0, + playbackDuration: 0, + resource, + onStreamError + }; + } + }, "onReadableCallback"); + const onFailureCallback = /* @__PURE__ */ __name(() => { + if (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) { + this.state = { + status: AudioPlayerStatus.Idle + }; + } + }, "onFailureCallback"); + resource.playStream.once("readable", onReadableCallback); + resource.playStream.once("end", onFailureCallback); + resource.playStream.once("close", onFailureCallback); + resource.playStream.once("finish", onFailureCallback); + this.state = { + status: AudioPlayerStatus.Buffering, + resource, + onReadableCallback, + onFailureCallback, + onStreamError + }; + } + } + /** + * 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 !== AudioPlayerStatus.Playing) + return false; + this.state = { + ...this.state, + status: AudioPlayerStatus.Paused, + silencePacketsRemaining: interpolateSilence ? 5 : 0 + }; + 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 !== AudioPlayerStatus.Paused) + return false; + this.state = { + ...this.state, + status: AudioPlayerStatus.Playing, + missedFrames: 0 + }; + 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 === AudioPlayerStatus.Idle) + return false; + if (force || this.state.resource.silencePaddingFrames === 0) { + this.state = { + status: AudioPlayerStatus.Idle + }; + } else if (this.state.resource.silenceRemaining === -1) { + this.state.resource.silenceRemaining = this.state.resource.silencePaddingFrames; + } + 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 === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) + return false; + if (!state.resource.readable) { + this.state = { + status: AudioPlayerStatus.Idle + }; + return false; + } + 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 === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) + return; + 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 === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) + return; + const playable = this.playable; + if (state.status === AudioPlayerStatus.AutoPaused && playable.length > 0) { + this.state = { + ...state, + status: AudioPlayerStatus.Playing, + missedFrames: 0 + }; + } + if (state.status === AudioPlayerStatus.Paused || state.status === AudioPlayerStatus.AutoPaused) { + if (state.silencePacketsRemaining > 0) { + state.silencePacketsRemaining--; + this._preparePacket(SILENCE_FRAME, playable, state); + if (state.silencePacketsRemaining === 0) { + this._signalStopSpeaking(); + } + } + return; + } + if (playable.length === 0) { + if (this.behaviors.noSubscriber === NoSubscriberBehavior.Pause) { + this.state = { + ...state, + status: AudioPlayerStatus.AutoPaused, + silencePacketsRemaining: 5 + }; + return; + } else if (this.behaviors.noSubscriber === NoSubscriberBehavior.Stop) { + this.stop(true); + } + } + const packet = state.resource.read(); + if (state.status === AudioPlayerStatus.Playing) { + if (packet) { + this._preparePacket(packet, playable, state); + state.missedFrames = 0; + } else { + this._preparePacket(SILENCE_FRAME, playable, state); + state.missedFrames++; + if (state.missedFrames >= this.behaviors.maxMissedFrames) { + this.stop(); + } + } + } + } + /** + * 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() { + 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; + for (const connection of receivers) { + connection.prepareAudioPacket(packet); + } + } +}; +__name(AudioPlayer, "AudioPlayer"); +function createAudioPlayer(options) { + return new AudioPlayer(options); +} +__name(createAudioPlayer, "createAudioPlayer"); + +// src/receive/AudioReceiveStream.ts +var EndBehaviorType; +(function(EndBehaviorType2) { + EndBehaviorType2[EndBehaviorType2[ + /** + * The stream will only end when manually destroyed. + */ + "Manual" + ] = 0] = "Manual"; + EndBehaviorType2[EndBehaviorType2[ + /** + * The stream will end after a given time period of silence/no audio packets. + */ + "AfterSilence" + ] = 1] = "AfterSilence"; + EndBehaviorType2[EndBehaviorType2[ + /** + * The stream will end after a given time period of no audio packets. + */ + "AfterInactivity" + ] = 2] = "AfterInactivity"; +})(EndBehaviorType || (EndBehaviorType = {})); +function createDefaultAudioReceiveStreamOptions() { + return { + end: { + behavior: EndBehaviorType.Manual + } + }; +} +__name(createDefaultAudioReceiveStreamOptions, "createDefaultAudioReceiveStreamOptions"); +var AudioReceiveStream = class extends Readable { + constructor({ end, ...options }) { + super({ + ...options, + objectMode: true + }); + this.end = end; + } + push(buffer) { + if (buffer && (this.end.behavior === EndBehaviorType.AfterInactivity || this.end.behavior === EndBehaviorType.AfterSilence && (buffer.compare(SILENCE_FRAME) !== 0 || typeof this.endTimeout === "undefined"))) { + this.renewEndTimeout(this.end); + } + return super.push(buffer); + } + renewEndTimeout(end) { + if (this.endTimeout) { + clearTimeout(this.endTimeout); + } + this.endTimeout = setTimeout(() => this.push(null), end.duration); + } + _read() { + } +}; +__name(AudioReceiveStream, "AudioReceiveStream"); + +// src/receive/SSRCMap.ts +import { EventEmitter as EventEmitter5 } from "node:events"; +var SSRCMap = class extends EventEmitter5 { + constructor() { + super(); + 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 = { + ...this.map.get(data.audioSSRC), + ...data + }; + this.map.set(data.audioSSRC, newValue); + if (!existing) + 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); + } + for (const data of this.map.values()) { + if (data.userId === target) { + return data; + } + } + 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); + if (existing) { + this.map.delete(target); + this.emit("delete", existing); + } + return existing; + } + for (const [audioSSRC, data] of this.map.entries()) { + if (data.userId === target) { + this.map.delete(audioSSRC); + this.emit("delete", data); + return data; + } + } + return void 0; + } +}; +__name(SSRCMap, "SSRCMap"); + +// src/receive/SpeakingMap.ts +import { EventEmitter as EventEmitter6 } from "node:events"; +var _SpeakingMap = class extends EventEmitter6 { + constructor() { + super(); + this.users = /* @__PURE__ */ new Map(); + this.speakingTimeouts = /* @__PURE__ */ new Map(); + } + onPacket(userId) { + const timeout = this.speakingTimeouts.get(userId); + if (timeout) { + clearTimeout(timeout); + } else { + this.users.set(userId, Date.now()); + this.emit("start", userId); + } + this.startTimeout(userId); + } + startTimeout(userId) { + 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 { + constructor(voiceConnection) { + this.voiceConnection = voiceConnection; + this.ssrcMap = new SSRCMap(); + this.speaking = new SpeakingMap(); + this.subscriptions = /* @__PURE__ */ new Map(); + this.connectionData = {}; + 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); + } else if (packet.op === VoiceOpcodes3.Speaking && typeof packet.d?.user_id === "string" && typeof packet.d?.ssrc === "number") { + this.ssrcMap.update({ + userId: packet.d.user_id, + audioSSRC: packet.d.ssrc + }); + } else if (packet.op === VoiceOpcodes3.ClientConnect && typeof packet.d?.user_id === "string" && typeof packet.d?.audio_ssrc === "number") { + this.ssrcMap.update({ + userId: packet.d.user_id, + audioSSRC: packet.d.audio_ssrc, + videoSSRC: packet.d.video_ssrc === 0 ? void 0 : packet.d.video_ssrc + }); + } + } + decrypt(buffer, mode, nonce2, secretKey) { + let end; + if (mode === "xsalsa20_poly1305_lite") { + buffer.copy(nonce2, 0, buffer.length - 4); + end = buffer.length - 4; + } else if (mode === "xsalsa20_poly1305_suffix") { + buffer.copy(nonce2, 0, buffer.length - 24); + end = buffer.length - 24; + } else { + buffer.copy(nonce2, 0, 0, 12); + } + const decrypted = methods.open(buffer.slice(12, end), nonce2, secretKey); + if (!decrypted) + return; + 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) + return; + if (packet[0] === 190 && packet[1] === 222) { + const headerExtensionLength = packet.readUInt16BE(2); + packet = packet.subarray(4 + 4 * headerExtensionLength); + } + 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; + const ssrc = msg.readUInt32BE(8); + const userData = this.ssrcMap.get(ssrc); + if (!userData) + return; + this.speaking.onPacket(userData.userId); + const stream = this.subscriptions.get(userData.userId); + 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); + if (packet) { + stream.push(packet); + } else { + stream.destroy(new Error("Failed to parse packet")); + } + } + } + /** + * 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) + return existing; + const stream = new AudioReceiveStream({ + ...createDefaultAudioReceiveStreamOptions(), + ...options + }); + stream.once("close", () => this.subscriptions.delete(userId)); + this.subscriptions.set(userId, stream); + return stream; + } +}; +__name(VoiceReceiver, "VoiceReceiver"); + +// src/VoiceConnection.ts +var VoiceConnectionStatus; +(function(VoiceConnectionStatus2) { + VoiceConnectionStatus2[ + /** + * The `VOICE_SERVER_UPDATE` and `VOICE_STATE_UPDATE` packets have been received, now attempting to establish a voice connection. + */ + "Connecting" + ] = "connecting"; + VoiceConnectionStatus2[ + /** + * The voice connection has been destroyed and untracked, it cannot be reused. + */ + "Destroyed" + ] = "destroyed"; + VoiceConnectionStatus2[ + /** + * The voice connection has either been severed or not established. + */ + "Disconnected" + ] = "disconnected"; + VoiceConnectionStatus2[ + /** + * A voice connection has been established, and is ready to be used. + */ + "Ready" + ] = "ready"; + VoiceConnectionStatus2[ + /** + * Sending a packet to the main Discord gateway to indicate we want to change our voice state. + */ + "Signalling" + ] = "signalling"; +})(VoiceConnectionStatus || (VoiceConnectionStatus = {})); +var VoiceConnectionDisconnectReason; +(function(VoiceConnectionDisconnectReason2) { + VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2[ + /** + * When the WebSocket connection has been closed. + */ + "WebSocketClose" + ] = 0] = "WebSocketClose"; + VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2[ + /** + * When the adapter was unable to send a message requested by the VoiceConnection. + */ + "AdapterUnavailable" + ] = 1] = "AdapterUnavailable"; + VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2[ + /** + * When a VOICE_SERVER_UPDATE packet is received with a null endpoint, causing the connection to be severed. + */ + "EndpointRemoved" + ] = 2] = "EndpointRemoved"; + VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2[ + /** + * When a manual disconnect was requested. + */ + "Manual" + ] = 3] = "Manual"; +})(VoiceConnectionDisconnectReason || (VoiceConnectionDisconnectReason = {})); +var VoiceConnection = class extends EventEmitter7 { + /** + * 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(); + 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 = options.adapterCreator({ + onVoiceServerUpdate: (data) => this.addServerPacket(data), + onVoiceStateUpdate: (data) => this.addStatePacket(data), + destroy: () => this.destroy(false) + }); + this._state = { + status: VoiceConnectionStatus.Signalling, + adapter + }; + this.packets = { + server: void 0, + state: void 0 + }; + 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"); + const newNetworking = Reflect.get(newState, "networking"); + const oldSubscription = Reflect.get(oldState, "subscription"); + const newSubscription = Reflect.get(newState, "subscription"); + if (oldNetworking !== newNetworking) { + if (oldNetworking) { + oldNetworking.on("error", noop); + oldNetworking.off("debug", this.onNetworkingDebug); + oldNetworking.off("error", this.onNetworkingError); + oldNetworking.off("close", this.onNetworkingClose); + oldNetworking.off("stateChange", this.onNetworkingStateChange); + oldNetworking.destroy(); + } + if (newNetworking) + this.updateReceiveBindings(newNetworking.state, oldNetworking?.state); + } + if (newState.status === VoiceConnectionStatus.Ready) { + this.rejoinAttempts = 0; + } else if (newState.status === VoiceConnectionStatus.Destroyed) { + for (const stream of this.receiver.subscriptions.values()) { + if (!stream.destroyed) + stream.destroy(); + } + } + if (oldState.status !== VoiceConnectionStatus.Destroyed && newState.status === VoiceConnectionStatus.Destroyed) { + oldState.adapter.destroy(); + } + this._state = newState; + if (oldSubscription && oldSubscription !== newSubscription) { + oldSubscription.unsubscribe(); + } + this.emit("stateChange", oldState, newState); + if (oldState.status !== newState.status) { + 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) { + this.configureNetworking(); + } else if (this.state.status !== VoiceConnectionStatus.Destroyed) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.EndpointRemoved + }; + } + } + /** + * 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") + this.joinConfig.selfDeaf = packet.self_deaf; + if (typeof packet.self_mute !== "undefined") + 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"); + const oldUdp = Reflect.get(oldState ?? {}, "udp"); + const newUdp = Reflect.get(newState, "udp"); + if (oldWs !== newWs) { + oldWs?.off("packet", this.receiver.onWsPacket); + newWs?.on("packet", this.receiver.onWsPacket); + } + if (oldUdp !== newUdp) { + oldUdp?.off("message", this.receiver.onUdpMessage); + newUdp?.on("message", this.receiver.onUdpMessage); + } + 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 === VoiceConnectionStatus.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)); + networking.once("close", this.onNetworkingClose); + networking.on("stateChange", this.onNetworkingStateChange); + networking.on("error", this.onNetworkingError); + networking.on("debug", this.onNetworkingDebug); + this.state = { + ...this.state, + status: VoiceConnectionStatus.Connecting, + 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 === VoiceConnectionStatus.Destroyed) + return; + if (code === 4014) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.WebSocketClose, + closeCode: code + }; + } else { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Signalling + }; + this.rejoinAttempts++; + if (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + } + } + } + /** + * 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) + return; + if (this.state.status !== VoiceConnectionStatus.Connecting && this.state.status !== VoiceConnectionStatus.Ready) + return; + if (newState.code === NetworkingStatusCode.Ready) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Ready + }; + } else if (newState.code !== NetworkingStatusCode.Closed) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Connecting + }; + } + } + /** + * 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 !== VoiceConnectionStatus.Ready) + return; + return state.networking.prepareAudioPacket(buffer); + } + /** + * Dispatches the previously prepared audio packet (if any) + */ + dispatchAudio() { + const state = this.state; + if (state.status !== VoiceConnectionStatus.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 !== VoiceConnectionStatus.Ready) + return; + 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 === VoiceConnectionStatus.Destroyed) { + throw new Error("Cannot destroy VoiceConnection - it has already been destroyed"); + } + if (getVoiceConnection(this.joinConfig.guildId, this.joinConfig.group) === this) { + untrackVoiceConnection(this); + } + if (adapterAvailable) { + this.state.adapter.sendPayload(createJoinVoiceChannelPayload({ + ...this.joinConfig, + channelId: null + })); + } + this.state = { + status: VoiceConnectionStatus.Destroyed + }; + } + /** + * Disconnects the VoiceConnection, allowing the possibility of rejoining later on. + * + * @returns `true` if the connection was successfully disconnected + */ + disconnect() { + if (this.state.status === VoiceConnectionStatus.Destroyed || this.state.status === VoiceConnectionStatus.Signalling) { + return false; + } + this.joinConfig.channelId = null; + if (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) { + this.state = { + adapter: this.state.adapter, + subscription: this.state.subscription, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + return false; + } + this.state = { + adapter: this.state.adapter, + reason: VoiceConnectionDisconnectReason.Manual, + status: VoiceConnectionStatus.Disconnected + }; + 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 === VoiceConnectionStatus.Destroyed) { + return false; + } + const notReady = this.state.status !== VoiceConnectionStatus.Ready; + if (notReady) + this.rejoinAttempts++; + Object.assign(this.joinConfig, joinConfig); + if (this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) { + if (notReady) { + this.state = { + ...this.state, + status: VoiceConnectionStatus.Signalling + }; + } + return true; + } + this.state = { + adapter: this.state.adapter, + subscription: this.state.subscription, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + 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 !== VoiceConnectionStatus.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 === VoiceConnectionStatus.Destroyed) + return; + const subscription = player["subscribe"](this); + this.state = { + ...this.state, + subscription + }; + 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 === VoiceConnectionStatus.Ready && this.state.networking.state.code === NetworkingStatusCode.Ready) { + return { + ws: this.state.networking.state.ws.ping, + udp: this.state.networking.state.udp.ping + }; + } + return { + ws: void 0, + 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 !== VoiceConnectionStatus.Destroyed && this.state.subscription === subscription) { + this.state = { + ...this.state, + subscription: void 0 + }; + } + } +}; +__name(VoiceConnection, "VoiceConnection"); +function createVoiceConnection(joinConfig, options) { + const payload = createJoinVoiceChannelPayload(joinConfig); + const existing = getVoiceConnection(joinConfig.guildId, joinConfig.group); + if (existing && existing.state.status !== VoiceConnectionStatus.Destroyed) { + if (existing.state.status === VoiceConnectionStatus.Disconnected) { + existing.rejoin({ + channelId: joinConfig.channelId, + selfDeaf: joinConfig.selfDeaf, + selfMute: joinConfig.selfMute + }); + } else if (!existing.state.adapter.sendPayload(payload)) { + existing.state = { + ...existing.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + } + return existing; + } + const voiceConnection = new VoiceConnection(joinConfig, options); + trackVoiceConnection(voiceConnection); + if (voiceConnection.state.status !== VoiceConnectionStatus.Destroyed && !voiceConnection.state.adapter.sendPayload(payload)) { + voiceConnection.state = { + ...voiceConnection.state, + status: VoiceConnectionStatus.Disconnected, + reason: VoiceConnectionDisconnectReason.AdapterUnavailable + }; + } + return voiceConnection; +} +__name(createVoiceConnection, "createVoiceConnection"); + +// src/joinVoiceChannel.ts +function joinVoiceChannel(options) { + const joinConfig = { + selfDeaf: true, + selfMute: false, + group: "default", + ...options + }; + return createVoiceConnection(joinConfig, { + adapterCreator: options.adapterCreator, + debug: options.debug + }); +} +__name(joinVoiceChannel, "joinVoiceChannel"); + +// src/audio/AudioResource.ts +import { pipeline } from "node:stream"; +import prism2 from "prism-media"; + +// src/audio/TransformerGraph.ts +import prism from "prism-media"; +var FFMPEG_PCM_ARGUMENTS = [ + "-analyzeduration", + "0", + "-loglevel", + "0", + "-f", + "s16le", + "-ar", + "48000", + "-ac", + "2" +]; +var FFMPEG_OPUS_ARGUMENTS = [ + "-analyzeduration", + "0", + "-loglevel", + "0", + "-acodec", + "libopus", + "-f", + "opus", + "-ar", + "48000", + "-ac", + "2" +]; +var StreamType; +(function(StreamType2) { + StreamType2["Arbitrary"] = "arbitrary"; + StreamType2["OggOpus"] = "ogg/opus"; + StreamType2["Opus"] = "opus"; + StreamType2["Raw"] = "raw"; + StreamType2["WebmOpus"] = "webm/opus"; +})(StreamType || (StreamType = {})); +var TransformerType; +(function(TransformerType2) { + TransformerType2["FFmpegOgg"] = "ffmpeg ogg"; + TransformerType2["FFmpegPCM"] = "ffmpeg pcm"; + TransformerType2["InlineVolume"] = "volume transformer"; + TransformerType2["OggOpusDemuxer"] = "ogg/opus demuxer"; + TransformerType2["OpusDecoder"] = "opus decoder"; + TransformerType2["OpusEncoder"] = "opus encoder"; + TransformerType2["WebmOpusDemuxer"] = "webm/opus demuxer"; +})(TransformerType || (TransformerType = {})); +var Node = class { + /** + * The outbound edges from this node. + */ + edges = []; + constructor(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 + }); + } +}; +__name(Node, "Node"); +var NODES = /* @__PURE__ */ new Map(); +for (const streamType of Object.values(StreamType)) { + NODES.set(streamType, new Node(streamType)); +} +function getNode(type) { + const node = NODES.get(type); + if (!node) + throw new Error(`Node type '${type}' does not exist!`); + return node; +} +__name(getNode, "getNode"); +getNode(StreamType.Raw).addEdge({ + type: TransformerType.OpusEncoder, + to: getNode(StreamType.Opus), + cost: 1.5, + transformer: () => new prism.opus.Encoder({ + rate: 48e3, + channels: 2, + frameSize: 960 + }) +}); +getNode(StreamType.Opus).addEdge({ + type: TransformerType.OpusDecoder, + to: getNode(StreamType.Raw), + cost: 1.5, + transformer: () => new prism.opus.Decoder({ + rate: 48e3, + channels: 2, + frameSize: 960 + }) +}); +getNode(StreamType.OggOpus).addEdge({ + type: TransformerType.OggOpusDemuxer, + to: getNode(StreamType.Opus), + cost: 1, + transformer: () => new prism.opus.OggDemuxer() +}); +getNode(StreamType.WebmOpus).addEdge({ + type: TransformerType.WebmOpusDemuxer, + to: getNode(StreamType.Opus), + cost: 1, + transformer: () => new prism.opus.WebmDemuxer() +}); +var FFMPEG_PCM_EDGE = { + type: TransformerType.FFmpegPCM, + to: getNode(StreamType.Raw), + cost: 2, + transformer: (input) => new prism.FFmpeg({ + args: typeof input === "string" ? [ + "-i", + input, + ...FFMPEG_PCM_ARGUMENTS + ] : FFMPEG_PCM_ARGUMENTS + }) +}; +getNode(StreamType.Arbitrary).addEdge(FFMPEG_PCM_EDGE); +getNode(StreamType.OggOpus).addEdge(FFMPEG_PCM_EDGE); +getNode(StreamType.WebmOpus).addEdge(FFMPEG_PCM_EDGE); +getNode(StreamType.Raw).addEdge({ + type: TransformerType.InlineVolume, + to: getNode(StreamType.Raw), + cost: 0.5, + transformer: () => new prism.VolumeTransformer({ + type: "s16le" + }) +}); +function canEnableFFmpegOptimizations() { + try { + return prism.FFmpeg.getInfo().output.includes("--enable-libopus"); + } catch { + } + return false; +} +__name(canEnableFFmpegOptimizations, "canEnableFFmpegOptimizations"); +if (canEnableFFmpegOptimizations()) { + const FFMPEG_OGG_EDGE = { + type: TransformerType.FFmpegOgg, + to: getNode(StreamType.OggOpus), + cost: 2, + transformer: (input) => new prism.FFmpeg({ + args: typeof input === "string" ? [ + "-i", + input, + ...FFMPEG_OPUS_ARGUMENTS + ] : FFMPEG_OPUS_ARGUMENTS + }) + }; + getNode(StreamType.Arbitrary).addEdge(FFMPEG_OGG_EDGE); + getNode(StreamType.OggOpus).addEdge(FFMPEG_OGG_EDGE); + getNode(StreamType.WebmOpus).addEdge(FFMPEG_OGG_EDGE); +} +function findPath(from, constraints, goal = getNode(StreamType.Opus), path = [], depth = 5) { + if (from === goal && constraints(path)) { + return { + cost: 0 + }; + } else if (depth === 0) { + return { + cost: Number.POSITIVE_INFINITY + }; + } + let currentBest; + for (const edge of from.edges) { + if (currentBest && edge.cost > currentBest.cost) + continue; + const next = findPath(edge.to, constraints, goal, [ + ...path, + edge + ], depth - 1); + const cost = edge.cost + next.cost; + if (!currentBest || cost < currentBest.cost) { + currentBest = { + cost, + edge, + next + }; + } + } + return currentBest ?? { + cost: Number.POSITIVE_INFINITY + }; +} +__name(findPath, "findPath"); +function constructPipeline(step) { + const edges = []; + let current = step; + while (current?.edge) { + edges.push(current.edge); + current = current.next; + } + return edges; +} +__name(constructPipeline, "constructPipeline"); +function findPipeline(from, constraint) { + return constructPipeline(findPath(getNode(from), constraint)); +} +__name(findPipeline, "findPipeline"); + +// src/audio/AudioResource.ts +var AudioResource = class { + /** + * 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 remaining silence frames to play. If -1, the frames have not yet started playing. + */ + silenceRemaining = -1; + constructor(edges, streams, metadata, silencePaddingFrames) { + this.edges = edges; + this.playStream = streams.length > 1 ? pipeline(streams, noop) : streams[0]; + this.metadata = metadata; + this.silencePaddingFrames = silencePaddingFrames; + for (const stream of streams) { + if (stream instanceof prism2.VolumeTransformer) { + this.volume = stream; + } else if (stream instanceof prism2.opus.Encoder) { + this.encoder = stream; + } + } + 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; + const real = this.playStream.readable; + if (!real) { + if (this.silenceRemaining === -1) + this.silenceRemaining = this.silencePaddingFrames; + return this.silenceRemaining !== 0; + } + 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; + } else if (this.silenceRemaining > 0) { + this.silenceRemaining--; + return SILENCE_FRAME; + } + const packet = this.playStream.read(); + if (packet) { + this.playbackDuration += 20; + } + return packet; + } +}; +__name(AudioResource, "AudioResource"); +var VOLUME_CONSTRAINT = /* @__PURE__ */ __name((path) => path.some((edge) => edge.type === TransformerType.InlineVolume), "VOLUME_CONSTRAINT"); +var NO_CONSTRAINT = /* @__PURE__ */ __name(() => true, "NO_CONSTRAINT"); +function inferStreamType(stream) { + if (stream instanceof prism2.opus.Encoder) { + return { + streamType: StreamType.Opus, + hasVolume: false + }; + } else if (stream instanceof prism2.opus.Decoder) { + return { + streamType: StreamType.Raw, + hasVolume: false + }; + } else if (stream instanceof prism2.VolumeTransformer) { + return { + streamType: StreamType.Raw, + hasVolume: true + }; + } else if (stream instanceof prism2.opus.OggDemuxer) { + return { + streamType: StreamType.Opus, + hasVolume: false + }; + } else if (stream instanceof prism2.opus.WebmDemuxer) { + return { + streamType: StreamType.Opus, + hasVolume: false + }; + } + return { + streamType: StreamType.Arbitrary, + hasVolume: false + }; +} +__name(inferStreamType, "inferStreamType"); +function createAudioResource(input, options = {}) { + let inputType = options.inputType; + let needsInlineVolume = Boolean(options.inlineVolume); + if (typeof input === "string") { + inputType = StreamType.Arbitrary; + } else if (typeof inputType === "undefined") { + const analysis = inferStreamType(input); + inputType = analysis.streamType; + needsInlineVolume = needsInlineVolume && !analysis.hasVolume; + } + const transformerPipeline = findPipeline(inputType, needsInlineVolume ? VOLUME_CONSTRAINT : NO_CONSTRAINT); + if (transformerPipeline.length === 0) { + if (typeof input === "string") + throw new Error(`Invalid pipeline constructed for string resource '${input}'`); + return new AudioResource([], [ + input + ], options.metadata ?? null, options.silencePaddingFrames ?? 5); + } + 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); +} +__name(createAudioResource, "createAudioResource"); + +// src/util/generateDependencyReport.ts +import { resolve, dirname } from "node:path"; +import prism3 from "prism-media"; +function findPackageJSON(dir, packageName, depth) { + if (depth === 0) + return void 0; + const attemptedPath = resolve(dir, "./package.json"); + try { + const pkg = __require(attemptedPath); + if (pkg.name !== packageName) + throw new Error("package.json does not match"); + return pkg; + } catch { + return findPackageJSON(resolve(dir, ".."), packageName, depth - 1); + } +} +__name(findPackageJSON, "findPackageJSON"); +function version(name) { + try { + if (name === "@discordjs/voice") { + return "[VI]{{inject}}[/VI]"; + } + const pkg = findPackageJSON(dirname(__require.resolve(name)), name, 3); + return pkg?.version ?? "not found"; + } catch { + return "not found"; + } +} +__name(version, "version"); +function generateDependencyReport() { + const report = []; + const addVersion = /* @__PURE__ */ __name((name) => report.push(`- ${name}: ${version(name)}`), "addVersion"); + report.push("Core Dependencies"); + addVersion("@discordjs/voice"); + addVersion("prism-media"); + report.push(""); + report.push("Opus Libraries"); + addVersion("@discordjs/opus"); + addVersion("opusscript"); + report.push(""); + report.push("Encryption Libraries"); + addVersion("sodium-native"); + addVersion("sodium"); + addVersion("libsodium-wrappers"); + addVersion("tweetnacl"); + report.push(""); + report.push("FFmpeg"); + try { + const info = prism3.FFmpeg.getInfo(); + report.push(`- version: ${info.version}`); + report.push(`- libopus: ${info.output.includes("--enable-libopus") ? "yes" : "no"}`); + } catch { + report.push("- not found"); + } + return [ + "-".repeat(50), + ...report, + "-".repeat(50) + ].join("\n"); +} +__name(generateDependencyReport, "generateDependencyReport"); + +// src/util/entersState.ts +import { once } from "node:events"; + +// src/util/abortAfter.ts +function abortAfter(delay) { + const ac = new AbortController(); + const timeout = setTimeout(() => ac.abort(), delay); + ac.signal.addEventListener("abort", () => clearTimeout(timeout)); + return [ + ac, + ac.signal + ]; +} +__name(abortAfter, "abortAfter"); + +// src/util/entersState.ts +async function entersState(target, status, timeoutOrSignal) { + if (target.state.status !== status) { + const [ac, signal] = typeof timeoutOrSignal === "number" ? abortAfter(timeoutOrSignal) : [ + void 0, + timeoutOrSignal + ]; + try { + await once(target, status, { + signal + }); + } finally { + ac?.abort(); + } + } + return target; +} +__name(entersState, "entersState"); + +// src/util/demuxProbe.ts +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); + const sampleRate = opusHead.readUInt32LE(12); + return channels === 2 && sampleRate === 48e3; +} +__name(validateDiscordOpusHead, "validateDiscordOpusHead"); +async function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHead) { + return new Promise((resolve2, reject) => { + 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); + stream.off("end", onClose); + stream.pause(); + resolved = type; + if (stream.readableEnded) { + resolve2({ + stream: Readable2.from(readBuffer), + type + }); + } else { + if (readBuffer.length > 0) { + stream.push(readBuffer); + } + resolve2({ + stream, + type + }); + } + }, "finish"); + const foundHead = /* @__PURE__ */ __name((type) => (head) => { + if (validator(head)) { + finish(type); + } + }, "foundHead"); + const webm = new prism4.opus.WebmDemuxer(); + webm.once("error", noop); + webm.on("head", foundHead(StreamType.WebmOpus)); + const ogg = new prism4.opus.OggDemuxer(); + ogg.once("error", noop); + ogg.on("head", foundHead(StreamType.OggOpus)); + const onClose = /* @__PURE__ */ __name(() => { + if (!resolved) { + finish(StreamType.Arbitrary); + } + }, "onClose"); + const onData = /* @__PURE__ */ __name((buffer) => { + readBuffer = Buffer7.concat([ + readBuffer, + buffer + ]); + webm.write(buffer); + ogg.write(buffer); + if (readBuffer.length >= probeSize) { + stream.off("data", onData); + stream.pause(); + process.nextTick(onClose); + } + }, "onData"); + stream.once("error", reject); + stream.on("data", onData); + stream.once("close", onClose); + stream.once("end", onClose); + }); +} +__name(demuxProbe, "demuxProbe"); + +// src/index.ts +var version2 = "[VI]{{inject}}[/VI]"; +export { + AudioPlayer, + AudioPlayerError, + AudioPlayerStatus, + AudioReceiveStream, + AudioResource, + EndBehaviorType, + NoSubscriberBehavior, + PlayerSubscription, + SSRCMap, + SpeakingMap, + StreamType, + VoiceConnection, + VoiceConnectionDisconnectReason, + VoiceConnectionStatus, + VoiceReceiver, + createAudioPlayer, + createAudioResource, + createDefaultAudioReceiveStreamOptions, + demuxProbe, + entersState, + generateDependencyReport, + getGroups, + getVoiceConnection, + getVoiceConnections, + joinVoiceChannel, + 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 new file mode 100644 index 0000000..76d65bc --- /dev/null +++ b/node_modules/@discordjs/voice/dist/index.mjs.map @@ -0,0 +1 @@ +{"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 (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 *\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 (typeof 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 (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\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 (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\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 || typeof 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 (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\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 '[VI]{{inject}}[/VI]';\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 = '[VI]{{inject}}[/VI]' as string;\n"],"mappings":";;;;;;;;;;;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OAAAA;EACpB,CAAA;AACD;AArFsBlB;;;AChBf,IAAM4C,WAAU;","names":["EventEmitter","GatewayOpcodes","createJoinVoiceChannelPayload","config","op","GatewayOpcodes","VoiceStateUpdate","d","guild_id","guildId","channel_id","channelId","self_deaf","selfDeaf","self_mute","selfMute","groups","Map","set","getOrCreateGroup","group","existing","get","map","getGroups","getVoiceConnections","getVoiceConnection","untrackVoiceConnection","voiceConnection","joinConfig","delete","trackVoiceConnection","FRAME_LENGTH","audioCycleInterval","nextTime","audioPlayers","audioCycleStep","available","filter","player","checkPlayable","prepareNextAudioFrame","players","nextPlayer","shift","setTimeout","Date","now","setImmediate","hasAudioPlayer","target","includes","addAudioPlayer","push","length","deleteAudioPlayer","index","indexOf","splice","clearTimeout","Buffer","EventEmitter","VoiceOpcodes","Buffer","libs","sodium","open","buffer","nonce","secretKey","output","Buffer","allocUnsafe","length","crypto_box_MACBYTES","crypto_secretbox_open_easy","close","opusPacket","crypto_secretbox_easy","random","num","randombytes_buf","api","tweetnacl","secretbox","randomBytes","fallbackError","Error","methods","libName","Object","keys","lib","require","ready","assign","noop","Buffer","createSocket","EventEmitter","isIPv4","parseLocalPacket","message","packet","Buffer","from","ip","slice","indexOf","toString","isIPv4","Error","port","readUInt16BE","length","KEEP_ALIVE_INTERVAL","MAX_COUNTER_VALUE","VoiceUDPSocket","EventEmitter","keepAliveCounter","remote","socket","createSocket","on","error","emit","buffer","onMessage","keepAliveBuffer","alloc","keepAliveInterval","setInterval","keepAlive","setImmediate","writeUInt32LE","send","destroy","close","clearInterval","performIPDiscovery","ssrc","Promise","resolve","reject","listener","off","once","discoveryBuffer","writeUInt16BE","writeUInt32BE","EventEmitter","VoiceOpcodes","WebSocket","VoiceWebSocket","EventEmitter","missedHeartbeats","address","debug","ws","WebSocket","onmessage","err","onMessage","onopen","emit","onerror","Error","error","onclose","lastHeartbeatAck","lastHeartbeatSend","message","destroy","setHeartbeatInterval","close","event","data","packet","JSON","parse","op","VoiceOpcodes","HeartbeatAck","Date","now","ping","sendPacket","stringified","stringify","send","sendHeartbeat","nonce","Heartbeat","d","ms","heartbeatInterval","clearInterval","setInterval","CHANNELS","TIMESTAMP_INC","MAX_NONCE_SIZE","SUPPORTED_ENCRYPTION_MODES","NetworkingStatusCode","OpeningWs","Identifying","UdpHandshaking","SelectingProtocol","Ready","Resuming","Closed","nonce","Buffer","alloc","stringifyState","state","JSON","stringify","ws","Reflect","has","udp","chooseEncryptionMode","options","option","find","includes","Error","join","randomNBit","numberOfBits","Math","floor","random","Networking","EventEmitter","debug","onWsOpen","bind","onChildError","onWsPacket","onWsClose","onWsDebug","onUdpDebug","onUdpClose","message","emit","_state","code","createWebSocket","endpoint","connectionOptions","destroy","newState","oldWs","get","newWs","off","on","noop","oldUdp","newUdp","oldState","VoiceWebSocket","Boolean","once","error","packet","op","VoiceOpcodes","Identify","d","server_id","serverId","user_id","userId","session_id","sessionId","token","sendPacket","Resume","canResume","Hello","setHeartbeatInterval","heartbeat_interval","ip","port","ssrc","modes","VoiceUDPSocket","performIPDiscovery","then","localConfig","SelectProtocol","protocol","data","address","mode","catch","connectionData","SessionDescription","encryptionMode","secret_key","secretKey","Uint8Array","sequence","timestamp","nonceBuffer","speaking","packetsPlayed","Resumed","prepareAudioPacket","opusPacket","preparedPacket","createAudioPacket","dispatchAudio","playAudioPacket","undefined","audioPacket","setSpeaking","send","Speaking","delay","packetBuffer","writeUIntBE","copy","concat","encryptOpusPacket","writeUInt32BE","methods","close","slice","Buffer","VoiceOpcodes","Readable","Buffer","EventEmitter","AudioPlayerError","Error","error","resource","message","name","stack","PlayerSubscription","connection","player","unsubscribe","SILENCE_FRAME","Buffer","from","NoSubscriberBehavior","Pause","Play","Stop","AudioPlayerStatus","AutoPaused","Buffering","Idle","Paused","Playing","stringifyState","state","JSON","stringify","resource","Reflect","has","stepTimeout","AudioPlayer","EventEmitter","subscribers","options","_state","status","behaviors","noSubscriber","maxMissedFrames","debug","message","emit","playable","filter","connection","VoiceConnectionStatus","Ready","map","subscribe","existingSubscription","find","subscription","PlayerSubscription","push","setImmediate","unsubscribe","index","indexOf","exists","splice","setSpeaking","newState","oldState","newResource","get","playStream","on","noop","off","onStreamError","audioPlayer","undefined","destroy","read","onFailureCallback","onReadableCallback","_signalStopSpeaking","deleteAudioPlayer","addAudioPlayer","didChangeResources","play","ended","Error","error","AudioPlayerError","once","started","missedFrames","playbackDuration","pause","interpolateSilence","silencePacketsRemaining","unpause","stop","force","silencePaddingFrames","silenceRemaining","checkPlayable","readable","_stepDispatch","dispatchAudio","_stepPrepare","length","_preparePacket","packet","receivers","prepareAudioPacket","createAudioPlayer","EndBehaviorType","Manual","AfterSilence","AfterInactivity","createDefaultAudioReceiveStreamOptions","end","behavior","AudioReceiveStream","Readable","options","objectMode","push","buffer","compare","SILENCE_FRAME","endTimeout","renewEndTimeout","clearTimeout","setTimeout","duration","_read","EventEmitter","SSRCMap","EventEmitter","map","Map","update","data","existing","get","audioSSRC","newValue","set","emit","target","values","userId","undefined","delete","entries","EventEmitter","SpeakingMap","EventEmitter","users","Map","speakingTimeouts","onPacket","userId","timeout","get","clearTimeout","set","Date","now","emit","startTimeout","setTimeout","delete","DELAY","VoiceReceiver","voiceConnection","ssrcMap","SSRCMap","speaking","SpeakingMap","subscriptions","Map","connectionData","onWsPacket","bind","onUdpMessage","packet","op","VoiceOpcodes","ClientDisconnect","d","user_id","delete","Speaking","ssrc","update","userId","audioSSRC","ClientConnect","audio_ssrc","videoSSRC","video_ssrc","undefined","decrypt","buffer","mode","nonce","secretKey","end","copy","length","decrypted","methods","open","slice","Buffer","from","parsePacket","headerExtensionLength","readUInt16BE","subarray","msg","readUInt32BE","userData","get","onPacket","stream","encryptionMode","nonceBuffer","push","destroy","Error","subscribe","options","existing","AudioReceiveStream","createDefaultAudioReceiveStreamOptions","once","set","VoiceConnectionStatus","Connecting","Destroyed","Disconnected","Ready","Signalling","VoiceConnectionDisconnectReason","WebSocketClose","AdapterUnavailable","EndpointRemoved","Manual","VoiceConnection","EventEmitter","joinConfig","options","debug","message","emit","rejoinAttempts","receiver","VoiceReceiver","onNetworkingClose","bind","onNetworkingStateChange","onNetworkingError","onNetworkingDebug","adapter","adapterCreator","onVoiceServerUpdate","data","addServerPacket","onVoiceStateUpdate","addStatePacket","destroy","_state","status","packets","server","undefined","state","newState","oldState","oldNetworking","Reflect","get","newNetworking","oldSubscription","newSubscription","on","noop","off","updateReceiveBindings","stream","subscriptions","values","destroyed","unsubscribe","packet","endpoint","configureNetworking","reason","self_deaf","selfDeaf","self_mute","selfMute","channel_id","channelId","oldWs","newWs","oldUdp","newUdp","onWsPacket","onUdpMessage","connectionData","networking","Networking","serverId","guild_id","token","sessionId","session_id","userId","user_id","Boolean","once","code","closeCode","sendPayload","createJoinVoiceChannelPayload","NetworkingStatusCode","Closed","error","prepareAudioPacket","buffer","dispatchAudio","playOpusPacket","adapterAvailable","Error","getVoiceConnection","guildId","group","untrackVoiceConnection","disconnect","subscription","rejoin","notReady","Object","assign","setSpeaking","enabled","subscribe","player","ping","ws","udp","onSubscriptionRemoved","createVoiceConnection","payload","existing","voiceConnection","trackVoiceConnection","joinVoiceChannel","options","joinConfig","selfDeaf","selfMute","group","createVoiceConnection","adapterCreator","debug","pipeline","prism","prism","FFMPEG_PCM_ARGUMENTS","FFMPEG_OPUS_ARGUMENTS","StreamType","Arbitrary","OggOpus","Opus","Raw","WebmOpus","TransformerType","FFmpegOgg","FFmpegPCM","InlineVolume","OggOpusDemuxer","OpusDecoder","OpusEncoder","WebmOpusDemuxer","Node","edges","type","addEdge","edge","push","from","NODES","Map","streamType","Object","values","set","getNode","node","get","Error","to","cost","transformer","prism","opus","Encoder","rate","channels","frameSize","Decoder","OggDemuxer","WebmDemuxer","FFMPEG_PCM_EDGE","input","FFmpeg","args","VolumeTransformer","canEnableFFmpegOptimizations","getInfo","output","includes","FFMPEG_OGG_EDGE","findPath","constraints","goal","path","depth","Number","POSITIVE_INFINITY","currentBest","next","constructPipeline","step","current","findPipeline","constraint","AudioResource","playbackDuration","started","silenceRemaining","edges","streams","metadata","silencePaddingFrames","playStream","length","pipeline","noop","stream","prism","VolumeTransformer","volume","opus","Encoder","encoder","once","readable","real","ended","readableEnded","destroyed","read","SILENCE_FRAME","packet","VOLUME_CONSTRAINT","path","some","edge","type","TransformerType","InlineVolume","NO_CONSTRAINT","inferStreamType","streamType","StreamType","Opus","hasVolume","Decoder","Raw","OggDemuxer","WebmDemuxer","Arbitrary","createAudioResource","input","options","inputType","needsInlineVolume","Boolean","inlineVolume","analysis","transformerPipeline","findPipeline","Error","map","transformer","unshift","resolve","dirname","prism","findPackageJSON","dir","packageName","depth","undefined","attemptedPath","resolve","pkg","require","name","Error","version","dirname","generateDependencyReport","report","addVersion","push","info","prism","FFmpeg","getInfo","output","includes","repeat","join","once","abortAfter","delay","ac","AbortController","timeout","setTimeout","abort","signal","addEventListener","clearTimeout","entersState","target","status","timeoutOrSignal","state","ac","signal","abortAfter","undefined","once","abort","Buffer","process","Readable","prism","validateDiscordOpusHead","opusHead","channels","readUInt8","sampleRate","readUInt32LE","demuxProbe","stream","probeSize","validator","Promise","resolve","reject","readableObjectMode","Error","readableEnded","readBuffer","Buffer","alloc","resolved","finish","type","off","onData","onClose","pause","Readable","from","length","push","foundHead","head","webm","prism","opus","WebmDemuxer","once","noop","on","StreamType","WebmOpus","ogg","OggDemuxer","OggOpus","Arbitrary","buffer","concat","write","process","nextTick","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/package.json b/node_modules/@discordjs/voice/package.json new file mode 100644 index 0000000..14e5274 --- /dev/null +++ b/node_modules/@discordjs/voice/package.json @@ -0,0 +1,89 @@ +{ + "name": "@discordjs/voice", + "version": "0.15.0", + "description": "Implementation of the Discord Voice API for node.js", + "scripts": { + "build": "tsup && node scripts/postbuild.mjs", + "build:docs": "tsc -p tsconfig.docs.json", + "test": "jest --coverage", + "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", + "prepack": "yarn lint && yarn test && yarn build", + "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 ", + "Aura Román " + ], + "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.4", + "discord-api-types": "^0.37.35", + "prism-media": "^1.3.5", + "tslib": "^2.5.0", + "ws": "^8.12.1" + }, + "devDependencies": { + "@babel/core": "^7.21.0", + "@babel/preset-env": "^7.20.2", + "@babel/preset-typescript": "^7.21.0", + "@favware/cliff-jumper": "^1.10.0", + "@microsoft/api-extractor": "^7.34.4", + "@types/jest": "^29.4.0", + "@types/node": "16.18.13", + "cross-env": "^7.0.3", + "esbuild-plugin-version-injector": "^1.0.3", + "eslint": "^8.35.0", + "eslint-config-neon": "^0.1.40", + "eslint-formatter-pretty": "^4.1.0", + "jest": "^29.4.3", + "jest-websocket-mock": "^2.4.0", + "mock-socket": "^9.2.1", + "prettier": "^2.8.4", + "tsup": "^6.6.3", + "tweetnacl": "^1.0.3", + "typescript": "^4.9.5" + }, + "engines": { + "node": ">=16.9.0" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/node_modules/@sapphire/async-queue/CHANGELOG.md b/node_modules/@sapphire/async-queue/CHANGELOG.md new file mode 100644 index 0000000..f2d02e0 --- /dev/null +++ b/node_modules/@sapphire/async-queue/CHANGELOG.md @@ -0,0 +1,148 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@sapphire/async-queue@1.5.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.4.0...@sapphire/async-queue@1.5.0) - (2022-08-16) + +## 🐛 Bug Fixes + +- **deps:** Update all non-major dependencies ([2308bd7](https://github.com/sapphiredev/utilities/commit/2308bd74356b6b2e0c12995b25f4d8ade4803fe9)) + +## 🚀 Features + +- Add `AsyncQueue#abortAll` (#429) ([b351e70](https://github.com/sapphiredev/utilities/commit/b351e70ebef329009daaebba89729ee84bb5704c)) + +# [@sapphire/async-queue@1.4.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.3.1...@sapphire/async-queue@1.4.0) - (2022-08-07) + +## 🐛 Bug Fixes + +- **deps:** Update all non-major dependencies ([84af0db](https://github.com/sapphiredev/utilities/commit/84af0db2db749223b036aa99fe19a2e9af5681c6)) +- **deps:** Update all non-major dependencies ([50cd8de](https://github.com/sapphiredev/utilities/commit/50cd8dea593b6f5ae75571209456b3421e2ca59a)) + +## 📝 Documentation + +- Add @muchnameless as a contributor ([a1221fe](https://github.com/sapphiredev/utilities/commit/a1221fea68506e99591d5d00ec552a07c26833f9)) +- Add @enxg as a contributor ([d2382f0](https://github.com/sapphiredev/utilities/commit/d2382f04e3909cb4ad11798a0a10e683f6cf5383)) +- Add @EvolutionX-10 as a contributor ([efc3a32](https://github.com/sapphiredev/utilities/commit/efc3a320a72ae258996dd62866d206c33f8d4961)) +- Add @MajesticString as a contributor ([295b3e9](https://github.com/sapphiredev/utilities/commit/295b3e9849a4b0fe64074bae02f6426378a303c3)) +- Add @Mzato0001 as a contributor ([c790ef2](https://github.com/sapphiredev/utilities/commit/c790ef25df2d7e22888fa9f8169167aa555e9e19)) +- Add @NotKaskus as a contributor ([00da8f1](https://github.com/sapphiredev/utilities/commit/00da8f199137b9277119823f322d1f2d168d928a)) +- Add @imranbarbhuiya as a contributor ([fb674c2](https://github.com/sapphiredev/utilities/commit/fb674c2c5594d41e71662263553dcb4bac9e37f4)) +- Add @axisiscool as a contributor ([ce1aa31](https://github.com/sapphiredev/utilities/commit/ce1aa316871a88d3663efbdf2a42d3d8dfe6a27f)) +- Add @dhruv-kaushikk as a contributor ([ebbf43f](https://github.com/sapphiredev/utilities/commit/ebbf43f63617daba96e72c50a234bf8b64f6ddc4)) +- Add @Commandtechno as a contributor ([f1d69fa](https://github.com/sapphiredev/utilities/commit/f1d69fabe1ee0abe4be08b19e63dbec03102f7ce)) +- Fix typedoc causing OOM crashes ([63ba41c](https://github.com/sapphiredev/utilities/commit/63ba41c4b6678554b1c7043a22d3296db4f59360)) + +## 🚀 Features + +- **AsyncQueue:** Add AbortSignal support (#417) ([c0629e7](https://github.com/sapphiredev/utilities/commit/c0629e781ebc3f48e496a0851191b32e91f62fe9)) + +## 🧪 Testing + +- Migrate to vitest (#380) ([075ec73](https://github.com/sapphiredev/utilities/commit/075ec73c7a8e3374fad3ada612d37eb4ac36ec8d)) + +## [1.3.1](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.3.0...@sapphire/async-queue@1.3.1) (2022-04-01) + +**Note:** Version bump only for package @sapphire/async-queue + +# [1.3.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.2.0...@sapphire/async-queue@1.3.0) (2022-03-06) + +### Features + +- allow module: NodeNext ([#306](https://github.com/sapphiredev/utilities/issues/306)) ([9dc6dd6](https://github.com/sapphiredev/utilities/commit/9dc6dd619efab879bb2b0b3c9e64304e10a67ed6)) +- **ts-config:** add multi-config structure ([#281](https://github.com/sapphiredev/utilities/issues/281)) ([b5191d7](https://github.com/sapphiredev/utilities/commit/b5191d7f2416dc5838590c4ff221454925553e37)) + +# [1.2.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.9...@sapphire/async-queue@1.2.0) (2022-01-28) + +### Features + +- change build system to tsup ([#270](https://github.com/sapphiredev/utilities/issues/270)) ([365a53a](https://github.com/sapphiredev/utilities/commit/365a53a5517a01a0926cf28a83c96b63f32ed9f8)) + +## [1.1.9](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.8...@sapphire/async-queue@1.1.9) (2021-11-06) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.1.8](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.7...@sapphire/async-queue@1.1.8) (2021-10-26) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.1.7](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.6...@sapphire/async-queue@1.1.7) (2021-10-17) + +### Bug Fixes + +- allow more node & npm versions in engines field ([5977d2a](https://github.com/sapphiredev/utilities/commit/5977d2a30a4b2cfdf84aff3f33af03ffde1bbec5)) + +## [1.1.6](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.5...@sapphire/async-queue@1.1.6) (2021-10-11) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.1.5](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.4...@sapphire/async-queue@1.1.5) (2021-10-04) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.1.4](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.3...@sapphire/async-queue@1.1.4) (2021-06-27) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.1.3](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.2...@sapphire/async-queue@1.1.3) (2021-06-06) + +### Bug Fixes + +- remove peer deps, update dev deps, update READMEs ([#124](https://github.com/sapphiredev/utilities/issues/124)) ([67256ed](https://github.com/sapphiredev/utilities/commit/67256ed43b915b02a8b5c68230ba82d6210c5032)) + +## [1.1.2](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.1...@sapphire/async-queue@1.1.2) (2021-05-20) + +### Bug Fixes + +- **async-queue:** mark package as side effect free ([1c4b901](https://github.com/sapphiredev/utilities/commit/1c4b901cda3d14bd085c35cc74e160f844567ba7)) + +## [1.1.1](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.1.0...@sapphire/async-queue@1.1.1) (2021-05-02) + +### Bug Fixes + +- drop the `www.` from the SapphireJS URL ([494d89f](https://github.com/sapphiredev/utilities/commit/494d89ffa04f78c195b93d7905b3232884f7d7e2)) +- update all the SapphireJS URLs from `.com` to `.dev` ([f59b46d](https://github.com/sapphiredev/utilities/commit/f59b46d1a0ebd39cad17b17d71cd3b9da808d5fd)) + +# [1.1.0](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.7...@sapphire/async-queue@1.1.0) (2021-04-21) + +### Features + +- add @sapphire/embed-jsx ([#100](https://github.com/sapphiredev/utilities/issues/100)) ([7277a23](https://github.com/sapphiredev/utilities/commit/7277a236015236ed8e81b7882875410facc4ce17)) + +## [1.0.7](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.6...@sapphire/async-queue@1.0.7) (2021-04-19) + +### Bug Fixes + +- change all Sapphire URLs from "project"->"community" & use our domain where applicable 👨‍🌾🚜 ([#102](https://github.com/sapphiredev/utilities/issues/102)) ([835b408](https://github.com/sapphiredev/utilities/commit/835b408e8e57130c3787aca2e32613346ff23e4d)) + +## [1.0.6](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.5...@sapphire/async-queue@1.0.6) (2021-04-03) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.0.5](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.4...@sapphire/async-queue@1.0.5) (2021-03-16) + +### Bug Fixes + +- remove terser from all packages ([#79](https://github.com/sapphiredev/utilities/issues/79)) ([1cfe4e7](https://github.com/sapphiredev/utilities/commit/1cfe4e7c804e62c142495686d2b83b81d0026c02)) + +## [1.0.4](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.3...@sapphire/async-queue@1.0.4) (2021-02-16) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.0.3](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.2...@sapphire/async-queue@1.0.3) (2021-02-13) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.0.2](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.1...@sapphire/async-queue@1.0.2) (2021-01-25) + +**Note:** Version bump only for package @sapphire/async-queue + +## [1.0.1](https://github.com/sapphiredev/utilities/compare/@sapphire/async-queue@1.0.0...@sapphire/async-queue@1.0.1) (2021-01-16) + +**Note:** Version bump only for package @sapphire/async-queue + +# 1.0.0 (2021-01-13) + +### Features + +- **async-queue:** add async-queue package ([#56](https://github.com/sapphiredev/utilities/issues/56)) ([ba81832](https://github.com/sapphiredev/utilities/commit/ba8183287dbbc3f3d7d79af6d5a2d3dd8d62f63e)) diff --git a/node_modules/@sapphire/async-queue/README.md b/node_modules/@sapphire/async-queue/README.md new file mode 100644 index 0000000..40d1358 --- /dev/null +++ b/node_modules/@sapphire/async-queue/README.md @@ -0,0 +1,116 @@ +
+ +![Sapphire Logo](https://cdn.skyra.pw/gh-assets/sapphire-banner.png) + +# @sapphire/async-queue + +**Sequential asynchronous lock-based queue for promises.** + +[![GitHub](https://img.shields.io/github/license/sapphiredev/utilities)](https://github.com/sapphiredev/utilities/blob/main/LICENSE.md) +[![codecov](https://codecov.io/gh/sapphiredev/utilities/branch/main/graph/badge.svg?token=OEGIV6RFDO)](https://codecov.io/gh/sapphiredev/utilities) +[![npm bundle size](https://img.shields.io/bundlephobia/min/@sapphire/async-queue?logo=webpack&style=flat-square)](https://bundlephobia.com/result?p=@sapphire/async-queue) +[![npm](https://img.shields.io/npm/v/@sapphire/async-queue?color=crimson&logo=npm&style=flat-square)](https://www.npmjs.com/package/@sapphire/async-queue) + +
+ +## Description + +Ever needed a queue for a set of promises? This is the package for you. + +## Features + +- Written in TypeScript +- Bundled with esbuild so it can be used in NodeJS and browsers +- Offers CommonJS, ESM and UMD bundles +- Fully tested + +## Installation + +You can use the following command to install this package, or replace `npm install` with your package manager of choice. + +```sh +npm install @sapphire/async-queue +``` + +--- + +## Buy us some doughnuts + +Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are amazing people who may still want to donate just to show their appreciation. Thank you very much in advance! + +We accept donations through Open Collective, Ko-fi, PayPal, Patreon and GitHub Sponsorships. You can use the buttons below to donate through your method of choice. + +| Donate With | Address | +| :-------------: | :-------------------------------------------------: | +| Open Collective | [Click Here](https://sapphirejs.dev/opencollective) | +| Ko-fi | [Click Here](https://sapphirejs.dev/kofi) | +| Patreon | [Click Here](https://sapphirejs.dev/patreon) | +| PayPal | [Click Here](https://sapphirejs.dev/paypal) | + +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Jeroen Claassens

💻 🚇 📆 📖 ⚠️

Antonio Román

💻 📆 👀 ⚠️

Gryffon Bellish

💻 👀 ⚠️

Vlad Frangu

💻 🐛 👀 📓 ⚠️

Stitch07

💻 📆 ⚠️

depfu[bot]

🚧

allcontributors[bot]

📖

Tyler J Russell

📖

Ivan Lieder

💻 🐛

Hezekiah Hendry

💻

Vetlix

💻

Ethan Mitchell

📖

Elliot

💻

Jurien Hamaker

💻

Charalampos Fanoulis

📖

dependabot[bot]

🚧

Kaname

💻

nandhagk

🐛

megatank58

💻

UndiedGamer

💻

Lioness100

📖 💻

David

💻

renovate[bot]

🚧

WhiteSource Renovate

🚧

FC

💻

Jérémy de Saint Denis

💻

MrCube

💻

bitomic

💻

c43721

💻

Commandtechno

💻

Aura

💻

Jonathan

💻

Parbez

🚧

Paul Andrew

📖

Mzato

💻 🐛

Harry Allen

📖

Evo

💻

Enes Genç

💻

muchnameless

💻
+ + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! diff --git a/node_modules/@sapphire/async-queue/dist/index.d.ts b/node_modules/@sapphire/async-queue/dist/index.d.ts new file mode 100644 index 0000000..0ea062c --- /dev/null +++ b/node_modules/@sapphire/async-queue/dist/index.d.ts @@ -0,0 +1,55 @@ +/** + * The AsyncQueue class used to sequentialize burst requests + */ +declare class AsyncQueue { + /** + * The amount of entries in the queue, including the head. + * @seealso {@link queued} for the queued count. + */ + get remaining(): number; + /** + * The amount of queued entries. + * @seealso {@link remaining} for the count with the head. + */ + get queued(): number; + /** + * The promises array + */ + private promises; + /** + * Waits for last promise and queues a new one + * @example + * ```typescript + * const queue = new AsyncQueue(); + * async function request(url, options) { + * await queue.wait({ signal: options.signal }); + * try { + * const result = await fetch(url, options); + * // Do some operations with 'result' + * } finally { + * // Remove first entry from the queue and resolve for the next entry + * queue.shift(); + * } + * } + * + * request(someUrl1, someOptions1); // Will call fetch() immediately + * request(someUrl2, someOptions2); // Will call fetch() after the first finished + * request(someUrl3, someOptions3); // Will call fetch() after the second finished + * ``` + */ + wait(options?: Readonly): Promise; + /** + * Unlocks the head lock and transfers the next lock (if any) to the head. + */ + shift(): void; + /** + * Aborts all the pending promises. + * @note To avoid race conditions, this does **not** unlock the head lock. + */ + abortAll(): void; +} +interface AsyncQueueWaitOptions { + signal?: AbortSignal | undefined | null; +} + +export { AsyncQueue, AsyncQueueWaitOptions }; diff --git a/node_modules/@sapphire/async-queue/dist/index.global.js b/node_modules/@sapphire/async-queue/dist/index.global.js new file mode 100644 index 0000000..8a8dadf --- /dev/null +++ b/node_modules/@sapphire/async-queue/dist/index.global.js @@ -0,0 +1,125 @@ +"use strict"; +var SapphireAsyncQueue = (() => { + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + 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 __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); + var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; + }; + + // src/index.ts + var src_exports = {}; + __export(src_exports, { + AsyncQueue: () => AsyncQueue + }); + + // src/lib/AsyncQueueEntry.ts + var AsyncQueueEntry = class { + constructor(queue) { + __publicField(this, "promise"); + __publicField(this, "resolve"); + __publicField(this, "reject"); + __publicField(this, "queue"); + __publicField(this, "signal", null); + __publicField(this, "signalListener", null); + this.queue = queue; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + setSignal(signal) { + if (signal.aborted) + return this; + this.signal = signal; + this.signalListener = () => { + const index = this.queue["promises"].indexOf(this); + if (index !== -1) + this.queue["promises"].splice(index, 1); + this.reject(new Error("Request aborted manually")); + }; + this.signal.addEventListener("abort", this.signalListener); + return this; + } + use() { + this.dispose(); + this.resolve(); + return this; + } + abort() { + this.dispose(); + this.reject(new Error("Request aborted manually")); + return this; + } + dispose() { + if (this.signal) { + this.signal.removeEventListener("abort", this.signalListener); + this.signal = null; + this.signalListener = null; + } + } + }; + __name(AsyncQueueEntry, "AsyncQueueEntry"); + + // src/lib/AsyncQueue.ts + var AsyncQueue = class { + constructor() { + __publicField(this, "promises", []); + } + get remaining() { + return this.promises.length; + } + get queued() { + return this.remaining === 0 ? 0 : this.remaining - 1; + } + wait(options) { + const entry = new AsyncQueueEntry(this); + if (this.promises.length === 0) { + this.promises.push(entry); + return Promise.resolve(); + } + this.promises.push(entry); + if (options?.signal) + entry.setSignal(options.signal); + return entry.promise; + } + shift() { + if (this.promises.length === 0) + return; + if (this.promises.length === 1) { + this.promises.shift(); + return; + } + this.promises.shift(); + this.promises[0].use(); + } + abortAll() { + if (this.queued === 0) + return; + for (let i = 1; i < this.promises.length; ++i) { + this.promises[i].abort(); + } + this.promises.length = 1; + } + }; + __name(AsyncQueue, "AsyncQueue"); + return __toCommonJS(src_exports); +})(); +//# sourceMappingURL=index.global.js.map \ No newline at end of file diff --git a/node_modules/@sapphire/async-queue/dist/index.global.js.map b/node_modules/@sapphire/async-queue/dist/index.global.js.map new file mode 100644 index 0000000..54b6787 --- /dev/null +++ b/node_modules/@sapphire/async-queue/dist/index.global.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/lib/AsyncQueueEntry.ts","../src/lib/AsyncQueue.ts"],"sourcesContent":["export * from './lib/AsyncQueue';\n","import type { AsyncQueue } from './AsyncQueue';\n\n/**\n * @internal\n */\nexport class AsyncQueueEntry {\n\tpublic readonly promise: Promise;\n\tprivate resolve!: () => void;\n\tprivate reject!: (error: Error) => void;\n\tprivate readonly queue: AsyncQueue;\n\tprivate signal: PolyFillAbortSignal | null = null;\n\tprivate signalListener: (() => void) | null = null;\n\n\tpublic constructor(queue: AsyncQueue) {\n\t\tthis.queue = queue;\n\t\tthis.promise = new Promise((resolve, reject) => {\n\t\t\tthis.resolve = resolve;\n\t\t\tthis.reject = reject;\n\t\t});\n\t}\n\n\tpublic setSignal(signal: AbortSignal) {\n\t\tif (signal.aborted) return this;\n\n\t\tthis.signal = signal as PolyFillAbortSignal;\n\t\tthis.signalListener = () => {\n\t\t\tconst index = this.queue['promises'].indexOf(this);\n\t\t\tif (index !== -1) this.queue['promises'].splice(index, 1);\n\n\t\t\tthis.reject(new Error('Request aborted manually'));\n\t\t};\n\t\tthis.signal.addEventListener('abort', this.signalListener);\n\t\treturn this;\n\t}\n\n\tpublic use() {\n\t\tthis.dispose();\n\t\tthis.resolve();\n\t\treturn this;\n\t}\n\n\tpublic abort() {\n\t\tthis.dispose();\n\t\tthis.reject(new Error('Request aborted manually'));\n\t\treturn this;\n\t}\n\n\tprivate dispose() {\n\t\tif (this.signal) {\n\t\t\tthis.signal.removeEventListener('abort', this.signalListener!);\n\t\t\tthis.signal = null;\n\t\t\tthis.signalListener = null;\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 { AsyncQueueEntry } from './AsyncQueueEntry';\n\n/**\n * The AsyncQueue class used to sequentialize burst requests\n */\nexport class AsyncQueue {\n\t/**\n\t * The amount of entries in the queue, including the head.\n\t * @seealso {@link queued} for the queued count.\n\t */\n\tpublic get remaining(): number {\n\t\treturn this.promises.length;\n\t}\n\n\t/**\n\t * The amount of queued entries.\n\t * @seealso {@link remaining} for the count with the head.\n\t */\n\tpublic get queued(): number {\n\t\treturn this.remaining === 0 ? 0 : this.remaining - 1;\n\t}\n\n\t/**\n\t * The promises array\n\t */\n\tprivate promises: AsyncQueueEntry[] = [];\n\n\t/**\n\t * Waits for last promise and queues a new one\n\t * @example\n\t * ```typescript\n\t * const queue = new AsyncQueue();\n\t * async function request(url, options) {\n\t * await queue.wait({ signal: options.signal });\n\t * try {\n\t * const result = await fetch(url, options);\n\t * // Do some operations with 'result'\n\t * } finally {\n\t * // Remove first entry from the queue and resolve for the next entry\n\t * queue.shift();\n\t * }\n\t * }\n\t *\n\t * request(someUrl1, someOptions1); // Will call fetch() immediately\n\t * request(someUrl2, someOptions2); // Will call fetch() after the first finished\n\t * request(someUrl3, someOptions3); // Will call fetch() after the second finished\n\t * ```\n\t */\n\tpublic wait(options?: Readonly): Promise {\n\t\tconst entry = new AsyncQueueEntry(this);\n\n\t\tif (this.promises.length === 0) {\n\t\t\tthis.promises.push(entry);\n\t\t\treturn Promise.resolve();\n\t\t}\n\n\t\tthis.promises.push(entry);\n\t\tif (options?.signal) entry.setSignal(options.signal);\n\t\treturn entry.promise;\n\t}\n\n\t/**\n\t * Unlocks the head lock and transfers the next lock (if any) to the head.\n\t */\n\tpublic shift(): void {\n\t\tif (this.promises.length === 0) return;\n\t\tif (this.promises.length === 1) {\n\t\t\t// Remove the head entry.\n\t\t\tthis.promises.shift();\n\t\t\treturn;\n\t\t}\n\n\t\t// Remove the head entry, making the 2nd entry the new one.\n\t\t// Then use the head entry, which will unlock the promise.\n\t\tthis.promises.shift();\n\t\tthis.promises[0].use();\n\t}\n\n\t/**\n\t * Aborts all the pending promises.\n\t * @note To avoid race conditions, this does **not** unlock the head lock.\n\t */\n\tpublic abortAll(): void {\n\t\t// If there are no queued entries, skip early.\n\t\tif (this.queued === 0) return;\n\n\t\t// Abort all the entries except the head, that is why the loop starts at\n\t\t// 1 and not at 0.\n\t\tfor (let i = 1; i < this.promises.length; ++i) {\n\t\t\tthis.promises[i].abort();\n\t\t}\n\n\t\tthis.promises.length = 1;\n\t}\n}\n\nexport interface AsyncQueueWaitOptions {\n\tsignal?: AbortSignal | undefined | null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;;;ACKO,MAAM,kBAAN,MAAsB;AAAA,IAQrB,YAAY,OAAmB;AAPtC,0BAAgB;AAChB,0BAAQ;AACR,0BAAQ;AACR,0BAAiB;AACjB,0BAAQ,UAAqC;AAC7C,0BAAQ,kBAAsC;AAG7C,WAAK,QAAQ;AACb,WAAK,UAAU,IAAI,QAAQ,CAAC,SAAS,WAAW;AAC/C,aAAK,UAAU;AACf,aAAK,SAAS;AAAA,MACf,CAAC;AAAA,IACF;AAAA,IAEO,UAAU,QAAqB;AACrC,UAAI,OAAO;AAAS,eAAO;AAE3B,WAAK,SAAS;AACd,WAAK,iBAAiB,MAAM;AAC3B,cAAM,QAAQ,KAAK,MAAM,YAAY,QAAQ,IAAI;AACjD,YAAI,UAAU;AAAI,eAAK,MAAM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AAI,KAAK,WAAW;AAAG;AAIvB,eAAS,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,EAAE,GAAG;AAC9C,aAAK,SAAS,GAAG,MAAM;AAAA,MACxB;AAEA,WAAK,SAAS,SAAS;AAAA,IACxB;AAAA,EACD;AAzFa;","names":[]} \ No newline at end of file diff --git a/node_modules/@sapphire/async-queue/dist/index.js b/node_modules/@sapphire/async-queue/dist/index.js new file mode 100644 index 0000000..8cab616 --- /dev/null +++ b/node_modules/@sapphire/async-queue/dist/index.js @@ -0,0 +1,128 @@ +"use strict"; +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +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 __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); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + AsyncQueue: () => AsyncQueue +}); +module.exports = __toCommonJS(src_exports); + +// src/lib/AsyncQueueEntry.ts +var AsyncQueueEntry = class { + constructor(queue) { + __publicField(this, "promise"); + __publicField(this, "resolve"); + __publicField(this, "reject"); + __publicField(this, "queue"); + __publicField(this, "signal", null); + __publicField(this, "signalListener", null); + this.queue = queue; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + setSignal(signal) { + if (signal.aborted) + return this; + this.signal = signal; + this.signalListener = () => { + const index = this.queue["promises"].indexOf(this); + if (index !== -1) + this.queue["promises"].splice(index, 1); + this.reject(new Error("Request aborted manually")); + }; + this.signal.addEventListener("abort", this.signalListener); + return this; + } + use() { + this.dispose(); + this.resolve(); + return this; + } + abort() { + this.dispose(); + this.reject(new Error("Request aborted manually")); + return this; + } + dispose() { + if (this.signal) { + this.signal.removeEventListener("abort", this.signalListener); + this.signal = null; + this.signalListener = null; + } + } +}; +__name(AsyncQueueEntry, "AsyncQueueEntry"); + +// src/lib/AsyncQueue.ts +var AsyncQueue = class { + constructor() { + __publicField(this, "promises", []); + } + get remaining() { + return this.promises.length; + } + get queued() { + return this.remaining === 0 ? 0 : this.remaining - 1; + } + wait(options) { + const entry = new AsyncQueueEntry(this); + if (this.promises.length === 0) { + this.promises.push(entry); + return Promise.resolve(); + } + this.promises.push(entry); + if (options?.signal) + entry.setSignal(options.signal); + return entry.promise; + } + shift() { + if (this.promises.length === 0) + return; + if (this.promises.length === 1) { + this.promises.shift(); + return; + } + this.promises.shift(); + this.promises[0].use(); + } + abortAll() { + if (this.queued === 0) + return; + for (let i = 1; i < this.promises.length; ++i) { + this.promises[i].abort(); + } + this.promises.length = 1; + } +}; +__name(AsyncQueue, "AsyncQueue"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AsyncQueue +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@sapphire/async-queue/dist/index.js.map b/node_modules/@sapphire/async-queue/dist/index.js.map new file mode 100644 index 0000000..fc20d2d --- /dev/null +++ b/node_modules/@sapphire/async-queue/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/lib/AsyncQueueEntry.ts","../src/lib/AsyncQueue.ts"],"sourcesContent":["export * from './lib/AsyncQueue';\n","import type { AsyncQueue } from './AsyncQueue';\n\n/**\n * @internal\n */\nexport class AsyncQueueEntry {\n\tpublic readonly promise: Promise;\n\tprivate resolve!: () => void;\n\tprivate reject!: (error: Error) => void;\n\tprivate readonly queue: AsyncQueue;\n\tprivate signal: PolyFillAbortSignal | null = null;\n\tprivate signalListener: (() => void) | null = null;\n\n\tpublic constructor(queue: AsyncQueue) {\n\t\tthis.queue = queue;\n\t\tthis.promise = new Promise((resolve, reject) => {\n\t\t\tthis.resolve = resolve;\n\t\t\tthis.reject = reject;\n\t\t});\n\t}\n\n\tpublic setSignal(signal: AbortSignal) {\n\t\tif (signal.aborted) return this;\n\n\t\tthis.signal = signal as PolyFillAbortSignal;\n\t\tthis.signalListener = () => {\n\t\t\tconst index = this.queue['promises'].indexOf(this);\n\t\t\tif (index !== -1) this.queue['promises'].splice(index, 1);\n\n\t\t\tthis.reject(new Error('Request aborted manually'));\n\t\t};\n\t\tthis.signal.addEventListener('abort', this.signalListener);\n\t\treturn this;\n\t}\n\n\tpublic use() {\n\t\tthis.dispose();\n\t\tthis.resolve();\n\t\treturn this;\n\t}\n\n\tpublic abort() {\n\t\tthis.dispose();\n\t\tthis.reject(new Error('Request aborted manually'));\n\t\treturn this;\n\t}\n\n\tprivate dispose() {\n\t\tif (this.signal) {\n\t\t\tthis.signal.removeEventListener('abort', this.signalListener!);\n\t\t\tthis.signal = null;\n\t\t\tthis.signalListener = null;\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 { AsyncQueueEntry } from './AsyncQueueEntry';\n\n/**\n * The AsyncQueue class used to sequentialize burst requests\n */\nexport class AsyncQueue {\n\t/**\n\t * The amount of entries in the queue, including the head.\n\t * @seealso {@link queued} for the queued count.\n\t */\n\tpublic get remaining(): number {\n\t\treturn this.promises.length;\n\t}\n\n\t/**\n\t * The amount of queued entries.\n\t * @seealso {@link remaining} for the count with the head.\n\t */\n\tpublic get queued(): number {\n\t\treturn this.remaining === 0 ? 0 : this.remaining - 1;\n\t}\n\n\t/**\n\t * The promises array\n\t */\n\tprivate promises: AsyncQueueEntry[] = [];\n\n\t/**\n\t * Waits for last promise and queues a new one\n\t * @example\n\t * ```typescript\n\t * const queue = new AsyncQueue();\n\t * async function request(url, options) {\n\t * await queue.wait({ signal: options.signal });\n\t * try {\n\t * const result = await fetch(url, options);\n\t * // Do some operations with 'result'\n\t * } finally {\n\t * // Remove first entry from the queue and resolve for the next entry\n\t * queue.shift();\n\t * }\n\t * }\n\t *\n\t * request(someUrl1, someOptions1); // Will call fetch() immediately\n\t * request(someUrl2, someOptions2); // Will call fetch() after the first finished\n\t * request(someUrl3, someOptions3); // Will call fetch() after the second finished\n\t * ```\n\t */\n\tpublic wait(options?: Readonly): Promise {\n\t\tconst entry = new AsyncQueueEntry(this);\n\n\t\tif (this.promises.length === 0) {\n\t\t\tthis.promises.push(entry);\n\t\t\treturn Promise.resolve();\n\t\t}\n\n\t\tthis.promises.push(entry);\n\t\tif (options?.signal) entry.setSignal(options.signal);\n\t\treturn entry.promise;\n\t}\n\n\t/**\n\t * Unlocks the head lock and transfers the next lock (if any) to the head.\n\t */\n\tpublic shift(): void {\n\t\tif (this.promises.length === 0) return;\n\t\tif (this.promises.length === 1) {\n\t\t\t// Remove the head entry.\n\t\t\tthis.promises.shift();\n\t\t\treturn;\n\t\t}\n\n\t\t// Remove the head entry, making the 2nd entry the new one.\n\t\t// Then use the head entry, which will unlock the promise.\n\t\tthis.promises.shift();\n\t\tthis.promises[0].use();\n\t}\n\n\t/**\n\t * Aborts all the pending promises.\n\t * @note To avoid race conditions, this does **not** unlock the head lock.\n\t */\n\tpublic abortAll(): void {\n\t\t// If there are no queued entries, skip early.\n\t\tif (this.queued === 0) return;\n\n\t\t// Abort all the entries except the head, that is why the loop starts at\n\t\t// 1 and not at 0.\n\t\tfor (let i = 1; i < this.promises.length; ++i) {\n\t\t\tthis.promises[i].abort();\n\t\t}\n\n\t\tthis.promises.length =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SAAS;AAAA,EACtB;AAAA,EAMA,IAAW,SAAiB;AAC3B,WAAO,KAAK,cAAc,IAAI,IAAI,KAAK,YAAY;AAAA,EACpD;AAAA,EA4BO,KAAK,SAA0D;AACrE,UAAM,QAAQ,IAAI,gBAAgB,IAAI;AAEtC,QAAI,KAAK,SAAS,WAAW,GAAG;AAC/B,WAAK,SAAS,KAAK,KAAK;AACxB,aAAO,QAAQ,QAAQ;AAAA,IACxB;AAEA,SAAK,SAAS,KAAK,KAAK;AACxB,QAAI,SAAS;AAAQ,YAAM,UAAU,QAAQ,MAAM;AACnD,WAAO,MAAM;AAAA,EACd;AAAA,EAKO,QAAc;AACpB,QAAI,KAAK,SAAS,WAAW;AAAG;AAChC,QAAI,KAAK,SAAS,WAAW,GAAG;AAE/B,WAAK,SAAS,MAAM;AACpB;AAAA,IACD;AAIA,SAAK,SAAS,MAAM;AACpB,SAAK,SAAS,GAAG,IAAI;AAAA,EACtB;AAAA,EAMO,WAAiB;AAEvB,QAAI,KAAK,WAAW;AAAG;AAIvB,aAAS,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,EAAE,GAAG;AAC9C,WAAK,SAAS,GAAG,MAAM;AAAA,IACxB;AAEA,SAAK,SAAS,SAAS;AAAA,EACxB;AACD;AAzFa;","names":[]} \ No newline at end of file diff --git a/node_modules/@sapphire/async-queue/dist/index.mjs b/node_modules/@sapphire/async-queue/dist/index.mjs new file mode 100644 index 0000000..b1ca52d --- /dev/null +++ b/node_modules/@sapphire/async-queue/dist/index.mjs @@ -0,0 +1,102 @@ +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 __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/lib/AsyncQueueEntry.ts +var AsyncQueueEntry = class { + constructor(queue) { + __publicField(this, "promise"); + __publicField(this, "resolve"); + __publicField(this, "reject"); + __publicField(this, "queue"); + __publicField(this, "signal", null); + __publicField(this, "signalListener", null); + this.queue = queue; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } + setSignal(signal) { + if (signal.aborted) + return this; + this.signal = signal; + this.signalListener = () => { + const index = this.queue["promises"].indexOf(this); + if (index !== -1) + this.queue["promises"].splice(index, 1); + this.reject(new Error("Request aborted manually")); + }; + this.signal.addEventListener("abort", this.signalListener); + return this; + } + use() { + this.dispose(); + this.resolve(); + return this; + } + abort() { + this.dispose(); + this.reject(new Error("Request aborted manually")); + return this; + } + dispose() { + if (this.signal) { + this.signal.removeEventListener("abort", this.signalListener); + this.signal = null; + this.signalListener = null; + } + } +}; +__name(AsyncQueueEntry, "AsyncQueueEntry"); + +// src/lib/AsyncQueue.ts +var AsyncQueue = class { + constructor() { + __publicField(this, "promises", []); + } + get remaining() { + return this.promises.length; + } + get queued() { + return this.remaining === 0 ? 0 : this.remaining - 1; + } + wait(options) { + const entry = new AsyncQueueEntry(this); + if (this.promises.length === 0) { + this.promises.push(entry); + return Promise.resolve(); + } + this.promises.push(entry); + if (options?.signal) + entry.setSignal(options.signal); + return entry.promise; + } + shift() { + if (this.promises.length === 0) + return; + if (this.promises.length === 1) { + this.promises.shift(); + return; + } + this.promises.shift(); + this.promises[0].use(); + } + abortAll() { + if (this.queued === 0) + return; + for (let i = 1; i < this.promises.length; ++i) { + this.promises[i].abort(); + } + this.promises.length = 1; + } +}; +__name(AsyncQueue, "AsyncQueue"); +export { + AsyncQueue +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@sapphire/async-queue/dist/index.mjs.map b/node_modules/@sapphire/async-queue/dist/index.mjs.map new file mode 100644 index 0000000..26dfb53 --- /dev/null +++ b/node_modules/@sapphire/async-queue/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/lib/AsyncQueueEntry.ts","../src/lib/AsyncQueue.ts"],"sourcesContent":["import type { AsyncQueue } from './AsyncQueue';\n\n/**\n * @internal\n */\nexport class AsyncQueueEntry {\n\tpublic readonly promise: Promise;\n\tprivate resolve!: () => void;\n\tprivate reject!: (error: Error) => void;\n\tprivate readonly queue: AsyncQueue;\n\tprivate signal: PolyFillAbortSignal | null = null;\n\tprivate signalListener: (() => void) | null = null;\n\n\tpublic constructor(queue: AsyncQueue) {\n\t\tthis.queue = queue;\n\t\tthis.promise = new Promise((resolve, reject) => {\n\t\t\tthis.resolve = resolve;\n\t\t\tthis.reject = reject;\n\t\t});\n\t}\n\n\tpublic setSignal(signal: AbortSignal) {\n\t\tif (signal.aborted) return this;\n\n\t\tthis.signal = signal as PolyFillAbortSignal;\n\t\tthis.signalListener = () => {\n\t\t\tconst index = this.queue['promises'].indexOf(this);\n\t\t\tif (index !== -1) this.queue['promises'].splice(index, 1);\n\n\t\t\tthis.reject(new Error('Request aborted manually'));\n\t\t};\n\t\tthis.signal.addEventListener('abort', this.signalListener);\n\t\treturn this;\n\t}\n\n\tpublic use() {\n\t\tthis.dispose();\n\t\tthis.resolve();\n\t\treturn this;\n\t}\n\n\tpublic abort() {\n\t\tthis.dispose();\n\t\tthis.reject(new Error('Request aborted manually'));\n\t\treturn this;\n\t}\n\n\tprivate dispose() {\n\t\tif (this.signal) {\n\t\t\tthis.signal.removeEventListener('abort', this.signalListener!);\n\t\t\tthis.signal = null;\n\t\t\tthis.signalListener = null;\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 { AsyncQueueEntry } from './AsyncQueueEntry';\n\n/**\n * The AsyncQueue class used to sequentialize burst requests\n */\nexport class AsyncQueue {\n\t/**\n\t * The amount of entries in the queue, including the head.\n\t * @seealso {@link queued} for the queued count.\n\t */\n\tpublic get remaining(): number {\n\t\treturn this.promises.length;\n\t}\n\n\t/**\n\t * The amount of queued entries.\n\t * @seealso {@link remaining} for the count with the head.\n\t */\n\tpublic get queued(): number {\n\t\treturn this.remaining === 0 ? 0 : this.remaining - 1;\n\t}\n\n\t/**\n\t * The promises array\n\t */\n\tprivate promises: AsyncQueueEntry[] = [];\n\n\t/**\n\t * Waits for last promise and queues a new one\n\t * @example\n\t * ```typescript\n\t * const queue = new AsyncQueue();\n\t * async function request(url, options) {\n\t * await queue.wait({ signal: options.signal });\n\t * try {\n\t * const result = await fetch(url, options);\n\t * // Do some operations with 'result'\n\t * } finally {\n\t * // Remove first entry from the queue and resolve for the next entry\n\t * queue.shift();\n\t * }\n\t * }\n\t *\n\t * request(someUrl1, someOptions1); // Will call fetch() immediately\n\t * request(someUrl2, someOptions2); // Will call fetch() after the first finished\n\t * request(someUrl3, someOptions3); // Will call fetch() after the second finished\n\t * ```\n\t */\n\tpublic wait(options?: Readonly): Promise {\n\t\tconst entry = new AsyncQueueEntry(this);\n\n\t\tif (this.promises.length === 0) {\n\t\t\tthis.promises.push(entry);\n\t\t\treturn Promise.resolve();\n\t\t}\n\n\t\tthis.promises.push(entry);\n\t\tif (options?.signal) entry.setSignal(options.signal);\n\t\treturn entry.promise;\n\t}\n\n\t/**\n\t * Unlocks the head lock and transfers the next lock (if any) to the head.\n\t */\n\tpublic shift(): void {\n\t\tif (this.promises.length === 0) return;\n\t\tif (this.promises.length === 1) {\n\t\t\t// Remove the head entry.\n\t\t\tthis.promises.shift();\n\t\t\treturn;\n\t\t}\n\n\t\t// Remove the head entry, making the 2nd entry the new one.\n\t\t// Then use the head entry, which will unlock the promise.\n\t\tthis.promises.shift();\n\t\tthis.promises[0].use();\n\t}\n\n\t/**\n\t * Aborts all the pending promises.\n\t * @note To avoid race conditions, this does **not** unlock the head lock.\n\t */\n\tpublic abortAll(): void {\n\t\t// If there are no queued entries, skip early.\n\t\tif (this.queued === 0) return;\n\n\t\t// Abort all the entries except the head, that is why the loop starts at\n\t\t// 1 and not at 0.\n\t\tfor (let i = 1; i < this.promises.length; ++i) {\n\t\t\tthis.promises[i].abort();\n\t\t}\n\n\t\tthis.promises.length = 1;\n\t}\n}\n\nexport interface AsyncQueueWaitOptions {\n\tsignal?: AbortSignal | undefined | null;\n}\n"],"mappings":";;;;;;;;;AAKO,IAAM,kBAAN,MAAsB;AAAA,EAQrB,YAAY,OAAmB;AAPtC,wBAAgB;AAChB,wBAAQ;AACR,wBAAQ;AACR,wBAAiB;AACjB,wBAAQ,UAAqC;AAC7C,wBAAQ,kBAAsC;AAG7C,SAAK,QAAQ;AACb,SAAK,UAAU,IAAI,QAAQ,CAAC,SAAS,WAAW;AAC/C,WAAK,UAAU;AACf,WAAK,SAAS;AAAA,IACf,CAAC;AAAA,EACF;AAAA,EAEO,UAAU,QAAqB;AACrC,QAAI,OAAO;AAAS,aAAO;AAE3B,SAAK,SAAS;AACd,SAAK,iBAAiB,MAAM;AAC3B,YAAM,QAAQ,KAAK,MAAM,YAAY,QAAQ,IAAI;AACjD,UAAI,UAAU;AAAI,aAAK,MAAM,YAAY,OAAO,OAAO,CAAC;AAExD,WAAK,OAAO,IAAI,MAAM,0BAA0B,CAAC;AAAA,IAClD;AACA,SAAK,OAAO,iBAAiB,SAAS,KAAK,cAAc;AACzD,WAAO;AAAA,EACR;AAAA,EAEO,MAAM;AACZ,SAAK,QAAQ;AACb,SAAK,QAAQ;AACb,WAAO;AAAA,EACR;AAAA,EAEO,QAAQ;AACd,SAAK,QAAQ;AACb,SAAK,OAAO,IAAI,MAAM,0BAA0B,CAAC;AACjD,WAAO;AAAA,EACR;AAAA,EAEQ,UAAU;AACjB,QAAI,KAAK,QAAQ;AAChB,WAAK,OAAO,oBAAoB,SAAS,KAAK,cAAe;AAC7D,WAAK,SAAS;AACd,WAAK,iBAAiB;AAAA,IACvB;AAAA,EACD;AACD;AAjDa;;;ACAN,IAAM,aAAN,MAAiB;AAAA,EAAjB;AAoBN,wBAAQ,YAA8B,CAAC;AAAA;AAAA,EAfvC,IAAW,YAAoB;AAC9B,WAAO,KAAK,SAAS;AAAA,EACtB;AAAA,EAMA,IAAW,SAAiB;AAC3B,WAAO,KAAK,cAAc,IAAI,IAAI,KAAK,YAAY;AAAA,EACpD;AAAA,EA4BO,KAAK,SAA0D;AACrE,UAAM,QAAQ,IAAI,gBAAgB,IAAI;AAEtC,QAAI,KAAK,SAAS,WAAW,GAAG;AAC/B,WAAK,SAAS,KAAK,KAAK;AACxB,aAAO,QAAQ,QAAQ;AAAA,IACxB;AAEA,SAAK,SAAS,KAAK,KAAK;AACxB,QAAI,SAAS;AAAQ,YAAM,UAAU,QAAQ,MAAM;AACnD,WAAO,MAAM;AAAA,EACd;AAAA,EAKO,QAAc;AACpB,QAAI,KAAK,SAAS,WAAW;AAAG;AAChC,QAAI,KAAK,SAAS,WAAW,GAAG;AAE/B,WAAK,SAAS,MAAM;AACpB;AAAA,IACD;AAIA,SAAK,SAAS,MAAM;AACpB,SAAK,SAAS,GAAG,IAAI;AAAA,EACtB;AAAA,EAMO,WAAiB;AAEvB,QAAI,KAAK,WAAW;AAAG;AAIvB,aAAS,IAAI,GAAG,IAAI,KAAK,SAAS,QAAQ,EAAE,GAAG;AAC9C,WAAK,SAAS,GAAG,MAAM;AAAA,IACxB;AAEA,SAAK,SAAS,SAAS;AAAA,EACxB;AACD;AAzFa;","names":[]} \ No newline at end of file diff --git a/node_modules/@sapphire/async-queue/package.json b/node_modules/@sapphire/async-queue/package.json new file mode 100644 index 0000000..b1917fd --- /dev/null +++ b/node_modules/@sapphire/async-queue/package.json @@ -0,0 +1,65 @@ +{ + "name": "@sapphire/async-queue", + "version": "1.5.0", + "description": "Sequential asynchronous lock-based queue for promises", + "author": "@sapphire", + "license": "MIT", + "main": "dist/index.js", + "module": "dist/index.mjs", + "browser": "dist/index.global.js", + "unpkg": "dist/index.global.js", + "types": "dist/index.d.ts", + "exports": { + "import": "./dist/index.mjs", + "require": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "sideEffects": false, + "homepage": "https://github.com/sapphiredev/utilities/tree/main/packages/async-queue", + "scripts": { + "test": "vitest run", + "lint": "eslint src tests --ext ts --fix -c ../../.eslintrc", + "build": "tsup", + "prepack": "yarn build", + "bump": "cliff-jumper", + "check-update": "cliff-jumper --dry-run" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sapphiredev/utilities.git", + "directory": "packages/async-queue" + }, + "files": [ + "dist/**/*.js*", + "dist/**/*.mjs*", + "dist/**/*.d*" + ], + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + }, + "keywords": [ + "@sapphire/async-queue", + "bot", + "typescript", + "ts", + "yarn", + "discord", + "sapphire", + "standalone" + ], + "bugs": { + "url": "https://github.com/sapphiredev/utilities/issues" + }, + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@favware/cliff-jumper": "^1.8.6", + "@vitest/coverage-c8": "^0.22.0", + "c8": "^7.12.0", + "tsup": "^6.2.2", + "typescript": "^4.7.4", + "vitest": "^0.22.0" + } +} \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/CHANGELOG.md b/node_modules/@sapphire/shapeshift/CHANGELOG.md new file mode 100644 index 0000000..d048520 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/CHANGELOG.md @@ -0,0 +1,263 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [3.8.1](https://github.com/sapphiredev/shapeshift/compare/v3.8.0...v3.8.1) - (2022-12-15) + +## 🐛 Bug Fixes + +- Fixed lodash esm import (#230) ([63def7b](https://github.com/sapphiredev/shapeshift/commit/63def7bcec6319b3792093945ba7ba9f871ced6f)) + +# [3.8.0](https://github.com/sapphiredev/shapeshift/compare/v3.7.1...v3.8.0) - (2022-12-11) + +## 🏠 Refactor + +- Remove `NonNullObject` (#227) ([04d3934](https://github.com/sapphiredev/shapeshift/commit/04d39343f55a4e1571f54870a84d8b95447bd682)) + +## 🚀 Features + +- Add `when` constraint (#223) ([8eade90](https://github.com/sapphiredev/shapeshift/commit/8eade90cd4c02b80746ecdcdc612829d7f765178)) + +# [3.7.1](https://github.com/sapphiredev/shapeshift/compare/v3.7.0...v3.7.1) - (2022-11-27) + +## 🐛 Bug Fixes + +- Fixed "jump to definition" for `undefinedToOptional` going to wrong symbol (#226) ([6aab6d0](https://github.com/sapphiredev/shapeshift/commit/6aab6d01450fd7abbeaa95e91fb58568240e02ff)) + +## 📝 Documentation + +- Add @legendhimslef as a contributor ([499522a](https://github.com/sapphiredev/shapeshift/commit/499522a782c3ecd4df80978d0811df1a75d08212)) + +# [3.7.0](https://github.com/sapphiredev/shapeshift/compare/v3.6.0...v3.7.0) - (2022-10-02) + +## 📝 Documentation + +- Add phone in readme (#203) ([4ec9b7a](https://github.com/sapphiredev/shapeshift/commit/4ec9b7ab85124d84b3404cb548b17b9221a716c5)) +- Add RealShadowNova as a contributor for tool (#185) ([6dfc442](https://github.com/sapphiredev/shapeshift/commit/6dfc442af6ef26d6bbca39078eca5727257b6dab)) + +## 🚀 Features + +- Add `s.string.phone` (#202) ([7d122d5](https://github.com/sapphiredev/shapeshift/commit/7d122d5dc0eaa63c639b9cde1514e63566a681bd)) + +# [3.6.0](https://github.com/sapphiredev/shapeshift/compare/v3.5.1...v3.6.0) - (2022-08-29) + +## 🐛 Bug Fixes + +- Typescript 4.8 compatibility (#179) ([2281535](https://github.com/sapphiredev/shapeshift/commit/2281535f7589a987510828e46bf66accc8393c34)) + +## 🚀 Features + +- Add `Validator#is` (#183) ([5114f95](https://github.com/sapphiredev/shapeshift/commit/5114f9516e5406cd1ca4a7ceb5ea5761158af1c6)) + +# [3.5.1](https://github.com/sapphiredev/shapeshift/compare/v3.5.0...v3.5.1) - (2022-07-17) + +## 🐛 Bug Fixes + +- Fast deep equal import (#155) ([5ce8ff6](https://github.com/sapphiredev/shapeshift/commit/5ce8ff6803b70624af07c3e406bc1cdc9e3cdafe)) + +# [3.5.0](https://github.com/sapphiredev/shapeshift/compare/v3.4.1...v3.5.0) - (2022-07-10) + +## 🏠 Refactor + +- Port net module (#149) ([5f26e32](https://github.com/sapphiredev/shapeshift/commit/5f26e32b0f87d2b100ca13471d5835c0067ddee8)) + +## 🐛 Bug Fixes + +- Ensure browser compatibility (#150) ([92d05d8](https://github.com/sapphiredev/shapeshift/commit/92d05d83c1fbab53f98f61219fb01d49fc031bae)) +- Fixed `s.array` type inference (#153) ([a5948dc](https://github.com/sapphiredev/shapeshift/commit/a5948dc67ce6a0ea73986d32084898a4ce0b9c3a)) +- Fixed `shape#array` types (#146) ([43016a0](https://github.com/sapphiredev/shapeshift/commit/43016a025b04a676d906758ed065d26a17231888)) + +## 🚀 Features + +- Lazy validator (#147) ([807666e](https://github.com/sapphiredev/shapeshift/commit/807666ef537c84d2e0f8bd9f4ce1a8060bfb3fb5)) +- Reshape finally (#148) ([d3751f6](https://github.com/sapphiredev/shapeshift/commit/d3751f6d3d99f415d797369f98158f932371e02c)) +- **arrays:** Add unique (#141) ([ad7af34](https://github.com/sapphiredev/shapeshift/commit/ad7af34eb811541253150b7ff0b58a6bd7200796)) + +# [3.4.1](https://github.com/sapphiredev/shapeshift/compare/v3.4.0...v3.4.1) - (2022-07-03) + +## 🏠 Refactor + +- Move all type utilities to one file (#139) ([61cab3d](https://github.com/sapphiredev/shapeshift/commit/61cab3d0e486d9dc74c8f6160ff8c75c91b595b2)) + +## 🐛 Bug Fixes + +- Return array-validator from length* methods (#140) ([75b1f9a](https://github.com/sapphiredev/shapeshift/commit/75b1f9a6efffb6c27dcfd48eb4ec6269a3614633)) + +## 🧪 Testing + +- Typechecking for tests (#145) ([273cdc8](https://github.com/sapphiredev/shapeshift/commit/273cdc82c1cf65ba4111ca6e70b050e02cbdf485)) + +# [3.4.0](https://github.com/sapphiredev/shapeshift/compare/v3.3.2...v3.4.0) - (2022-06-29) + +## 🚀 Features + +- Add `required` in object validation (#137) ([928f7be](https://github.com/sapphiredev/shapeshift/commit/928f7beb5e727b47868e9e46f2191f2def228080)) + +# [3.3.2](https://github.com/sapphiredev/shapeshift/compare/v3.3.1...v3.3.2) - (2022-06-26) + +## 🐛 Bug Fixes + +- Make keys optional in object parsing (#134) ([57a3719](https://github.com/sapphiredev/shapeshift/commit/57a37193d64399aae1431b041012d582e8defecf)) + +# [3.3.1](https://github.com/sapphiredev/shapeshift/compare/v3.3.0...v3.3.1) - (2022-06-22) + +## 🐛 Bug Fixes + +- Add generic type to parse (#133) ([90c91aa](https://github.com/sapphiredev/shapeshift/commit/90c91aad572d51a2bfbd1ed32a51e1d4201c5d4a)) + +# [3.3.0](https://github.com/sapphiredev/shapeshift/compare/v3.2.0...v3.3.0) - (2022-06-19) + +## 🐛 Bug Fixes + +- Compile for es2020 instead of es2021 (#128) ([051344d](https://github.com/sapphiredev/shapeshift/commit/051344debe1cf423713d7fc64b8908353348f301)) + +## 🚀 Features + +- Allow passing functions in `setValidationEnabled` (#131) ([e1991cf](https://github.com/sapphiredev/shapeshift/commit/e1991cfef1ffe92f9167d11d7f2ded65379df8d2)) + +## 🧪 Testing + +- Migrate to vitest (#126) ([4d80969](https://github.com/sapphiredev/shapeshift/commit/4d80969b714c39768499569456405a73c1444da8)) + +# [3.2.0](https://github.com/sapphiredev/shapeshift/compare/v3.1.0...v3.2.0) - (2022-06-11) + +## 🚀 Features + +- Add disabling of validators (#125) ([e17af95](https://github.com/sapphiredev/shapeshift/commit/e17af95d697be62796c57d03385b0c74b9d2d580)) + +# [3.1.0](https://github.com/sapphiredev/shapeshift/compare/v3.0.0...v3.1.0) - (2022-06-04) + +## 🐛 Bug Fixes + +- **ObjectValidator:** Fix #121 (#122) ([ecfad7e](https://github.com/sapphiredev/shapeshift/commit/ecfad7ec2cdd9e0cee0b3e227e55a91b28c29c30)) + +## 📝 Documentation + +- **readme:** Clarify the difference between validations and schemas and add table of contents (#108) ([dc492a3](https://github.com/sapphiredev/shapeshift/commit/dc492a395349cc5bc680f313146127ea510b4ada)) + +## 🚀 Features + +- **StringValidator:** Add date string checks (#106) ([1b72907](https://github.com/sapphiredev/shapeshift/commit/1b729078be32a88aeddf574c9cff3098990d4f94)) + +# [3.0.0](https://github.com/sapphiredev/shapeshift/compare/v2.2.0...v3.0.0) - (2022-05-06) + +## 🏃 Performance + +- Speed up object validation a LOT (#101) ([817278e](https://github.com/sapphiredev/shapeshift/commit/817278e6a3ac128ca342e5ae1737f40b98788c37)) + +## 🐛 Bug Fixes + +- Expand method names (#100) ([741490f](https://github.com/sapphiredev/shapeshift/commit/741490fb6907f618fa25fe53808f7dcb5a59a96c))} + + ### 💥 Breaking Changes: + - `date.eq` has been renamed to `date.equal` + - `string.lengthLt` has been renamed to `string.lengthLessThan` + - `string.lengthLe` has been renamed to `string.lengthLessThanOrEqual` + - `string.lengthGt` has been renamed to `string.lengthGreaterThan` + - `string.lengthGe` has been renamed to `string.lengthGreaterThanOrEqual` + - `string.lengthEq` has been renamed to `string.lengthEqual` + - `string.lengthNe` has been renamed to `string.lengthNotEqual` + - `number.gt` has been renamed to `number.greaterThan` + - `number.ge` has been renamed to `number.greaterThanOrEqual` + - `number.lt` has been renamed to `number.lessThan` + - `number.le` has been renamed to `number.lessThanOrEqual` + - `number.eq` has been renamed to `number.equal` + - `number.ne` has been renamed to `number.notEqual` + - `bigint.gt` has been renamed to `bigint.greaterThan` + - `bigint.ge` has been renamed to `bigint.greaterThanOrEqual` + - `bigint.lt` has been renamed to `bigint.lessThan` + - `bigint.le` has been renamed to `bigint.lessThanOrEqual` + - `bigint.eq` has been renamed to `bigint.equal` + - `bigint.ne` has been renamed to `bigint.notEqual` + - `boolean.eq` has been renamed to `boolean.equal` + - `boolean.ne` has been renamed to `boolean.notEqual` + - `array.lengthLt` has been renamed to `array.lengthLessThan` + - `array.lengthLe` has been renamed to `array.lengthLessThanOrEqual` + - `array.lengthGt` has been renamed to `array.lengthGreaterThan` + - `array.lengthGe` has been renamed to `array.lengthGreaterThanOrEqual` + - `array.lengthEq` has been renamed to `array.lengthEqual` + - `array.lengthNe` has been renamed to `array.lengthNotEqual` + - `typedArray.lengthLt` has been renamed to `typedArray.lengthLessThan` + - `typedArray.lengthLe` has been renamed to `typedArray.lengthLessThanOrEqual` + - `typedArray.lengthGt` has been renamed to `typedArray.lengthGreaterThan` + - `typedArray.lengthGe` has been renamed to `typedArray.lengthGreaterThanOrEqual` + - `typedArray.lengthEq` has been renamed to `typedArray.lengthEqual` + - `typedArray.lengthNe` has been renamed to `typedArray.lengthNotEqual` + - `typedArray.byteLengthLt` has been renamed to `typedArray.byteLengthLessThan` + - `typedArray.byteLengthLe` has been renamed to `typedArray.byteLengthLessThanOrEqual` + - `typedArray.byteLengthGt` has been renamed to `typedArray.byteLengthGreaterThan` + - `typedArray.byteLengthGe` has been renamed to `typedArray.byteLengthGreaterThanOrEqual` + - `typedArray.byteLengthEq` has been renamed to `typedArray.byteLengthEqual` + - `typedArray.byteLengthNe` has been renamed to `typedArray.byteLengthNotEqual` + +- **ObjectValidator:** Don't run validation on arrays (#99) ([c83b3d0](https://github.com/sapphiredev/shapeshift/commit/c83b3d03a201d38cc230d9c831ca1d9b66ca533b)) + +## 🚀 Features + +- Add 2 utility types inspired by yup and co (#102) ([2fef902](https://github.com/sapphiredev/shapeshift/commit/2fef9026c30f2f1825aa55511d0ab088a3dd13ab)) + +# [2.2.0](https://github.com/sapphiredev/shapeshift/compare/v2.0.0...v2.2.0) - (2022-04-29) + +## Bug Fixes + +- Ensure `BaseError` is exported as value (#95) ([335d799](https://github.com/sapphiredev/shapeshift/commit/335d799ef7a8c1a19a12e3eeec07e6d210db113d)) + +## Documentation + +- **readme:** Add todo notice for `reshape` and `function` validations (#75) ([d5f16f6](https://github.com/sapphiredev/shapeshift/commit/d5f16f615de83503187dc834c6245fafbf138f5e)) + +## Features + +- Add Typed Array (#78) ([ca5ea5f](https://github.com/sapphiredev/shapeshift/commit/ca5ea5f568084bd5d3aa004911d4ea64329e1a89)) + +## Performance + +- Optimize `NativeEnum` (#79) ([e9ae280](https://github.com/sapphiredev/shapeshift/commit/e9ae280f73e9ea08239bd8bd22165fe0b2178f82)) + +# [@sapphire/shapeshift@2.1.0](https://github.com/sapphiredev/shapeshift/compare/v2.0.0...@sapphire/shapeshift@2.1.0) - (2022-04-24) + +## Documentation + +- **readme:** Add todo notice for `reshape` and `function` validations (#75) ([d5f16f6](https://github.com/sapphiredev/shapeshift/commit/d5f16f615de83503187dc834c6245fafbf138f5e)) + +## Performance + +- Optimize `NativeEnum` (#79) ([e9ae280](https://github.com/sapphiredev/shapeshift/commit/e9ae280f73e9ea08239bd8bd22165fe0b2178f82)) + +## [2.0.0](https://github.com/sapphiredev/shapeshift/compare/v1.0.0...v2.0.0) (2022-03-13) + +### Features + +- add `default` ([#25](https://github.com/sapphiredev/shapeshift/issues/25)) ([378c51f](https://github.com/sapphiredev/shapeshift/commit/378c51fb4ba2c501fd782387169db888d6bfe662)) +- add bigint methods ([#32](https://github.com/sapphiredev/shapeshift/issues/32)) ([4c444c1](https://github.com/sapphiredev/shapeshift/commit/4c444c15657c4610b99481b6dec9812bd136d72b)) +- add MapValidator ([#21](https://github.com/sapphiredev/shapeshift/issues/21)) ([c4d1258](https://github.com/sapphiredev/shapeshift/commit/c4d12586762d446b858454077b66635d9d11e2d6)) +- add NativeEnum validator ([#54](https://github.com/sapphiredev/shapeshift/issues/54)) ([7359042](https://github.com/sapphiredev/shapeshift/commit/7359042843d1119f396ac2c038aaff89dbd90c8e)) +- add RecordValidator ([#20](https://github.com/sapphiredev/shapeshift/issues/20)) ([8727427](https://github.com/sapphiredev/shapeshift/commit/8727427be4656792eebcdc5bddf6bcd61bc7e846)) +- add remaining string validations ([#38](https://github.com/sapphiredev/shapeshift/issues/38)) ([1c2fd7b](https://github.com/sapphiredev/shapeshift/commit/1c2fd7bbb20463f09ac461b697c312bec6ae9195)) +- add tuple ([#39](https://github.com/sapphiredev/shapeshift/issues/39)) ([b7704bf](https://github.com/sapphiredev/shapeshift/commit/b7704bf87cf5225021408cf4a6b9ceff8cba25b3)) +- added number transformers ([#17](https://github.com/sapphiredev/shapeshift/issues/17)) ([89a8ddd](https://github.com/sapphiredev/shapeshift/commit/89a8ddd8583774e68c43260c28ee1589ef44516c)) +- allow the use of module: NodeNext ([#55](https://github.com/sapphiredev/shapeshift/issues/55)) ([e6827c5](https://github.com/sapphiredev/shapeshift/commit/e6827c5a12b6a2803a137b71fe4c21bd1c35034b)) +- **array:** add array length Comparators ([#40](https://github.com/sapphiredev/shapeshift/issues/40)) ([1e564c2](https://github.com/sapphiredev/shapeshift/commit/1e564c204b6c9b0a798b3121d31dd4cc99165f60)) +- **Array:** generate tuple types with given length ([#52](https://github.com/sapphiredev/shapeshift/issues/52)) ([793648b](https://github.com/sapphiredev/shapeshift/commit/793648b4cde1f72c5b735ceebb0c48272179be06)) +- **ArrayValidator:** add length ranges ([#53](https://github.com/sapphiredev/shapeshift/issues/53)) ([e431d62](https://github.com/sapphiredev/shapeshift/commit/e431d6218b86fc1480fce14c4466cb36567cad2f)) +- display the property that errored ([#35](https://github.com/sapphiredev/shapeshift/issues/35)) ([fe188b0](https://github.com/sapphiredev/shapeshift/commit/fe188b0d17eeaa5f73b08085562903e23e91717c)) +- improve how errors are returned ([#29](https://github.com/sapphiredev/shapeshift/issues/29)) ([8bc7669](https://github.com/sapphiredev/shapeshift/commit/8bc7669a1a66a10449b321cc4447e411383977d9)) +- **s.object:** add passthrough ([#66](https://github.com/sapphiredev/shapeshift/issues/66)) ([ee9f6f3](https://github.com/sapphiredev/shapeshift/commit/ee9f6f367e513c0120a04cfafe05057c7907c327)) + +### Bug Fixes + +- copy/paste error and `ge` ([#22](https://github.com/sapphiredev/shapeshift/issues/22)) ([fe6505f](https://github.com/sapphiredev/shapeshift/commit/fe6505f8e698bcaf9f8024b2d8f012559827cbb0)) +- fix union type and add test ([#41](https://github.com/sapphiredev/shapeshift/issues/41)) ([fbcf8a9](https://github.com/sapphiredev/shapeshift/commit/fbcf8a9c617c16b33fdddb0a44aa0fe506164fd3)) +- **s.union:** fix union overrides ([#62](https://github.com/sapphiredev/shapeshift/issues/62)) ([56e9b19](https://github.com/sapphiredev/shapeshift/commit/56e9b1947d9b2b129dbed374671114b2242e6d35)) + +## 1.0.0 (2022-01-16) + +### Features + +- added more primitives ([#2](https://github.com/sapphiredev/shapeshift/issues/2)) ([16af17b](https://github.com/sapphiredev/shapeshift/commit/16af17b5d9ee40dce284ee120e0b099f7b2cc0b8)) +- added more things ([7c73d82](https://github.com/sapphiredev/shapeshift/commit/7c73d82cf3740d5b2d4eebcac7767da9d3562437)) +- added ObjectValidator ([#3](https://github.com/sapphiredev/shapeshift/issues/3)) ([abe7ead](https://github.com/sapphiredev/shapeshift/commit/abe7eaddee981ef485713ff5e7b7f32ff97c645b)) + +### Bug Fixes + +- resolved install error ([a5abe13](https://github.com/sapphiredev/shapeshift/commit/a5abe1362bb6d9ce6d6471bffa47fe8983b0d1a4)) diff --git a/node_modules/@sapphire/shapeshift/LICENSE.md b/node_modules/@sapphire/shapeshift/LICENSE.md new file mode 100644 index 0000000..95a4396 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/LICENSE.md @@ -0,0 +1,24 @@ +# The MIT License (MIT) + +Copyright © `2021` `The Sapphire Community and its contributors` + +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/@sapphire/shapeshift/README.md b/node_modules/@sapphire/shapeshift/README.md new file mode 100644 index 0000000..f970cb1 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/README.md @@ -0,0 +1,955 @@ +
+ +![Sapphire Logo](https://cdn.skyra.pw/gh-assets/sapphire-banner.png) + +# @sapphire/shapeshift + +**Shapeshift** + +Blazing fast input validation and transformation ⚡ + +[![GitHub](https://img.shields.io/github/license/sapphiredev/shapeshift)](https://github.com/sapphiredev/shapeshift/blob/main/LICENSE.md) +[![codecov](https://codecov.io/gh/sapphiredev/shapeshift/branch/main/graph/badge.svg?token=RF4mMKx6lL)](https://codecov.io/gh/sapphiredev/shapeshift) +[![npm](https://img.shields.io/npm/v/@sapphire/shapeshift?color=crimson&logo=npm&style=flat-square)](https://www.npmjs.com/package/@sapphire/shapeshift) + +
+ +## Table of Contents + +- [@sapphire/shapeshift](#sapphireshapeshift) + - [Table of Contents](#table-of-contents) + - [Description](#description) + - [Features](#features) + - [Usage](#usage) + - [Basic usage](#basic-usage) + - [Defining validations](#defining-validations) + - [Primitives](#primitives) + - [Literals](#literals) + - [Strings](#strings) + - [Numbers](#numbers) + - [BigInts](#bigints) + - [Booleans](#booleans) + - [Arrays](#arrays) + - [Tuples](#tuples) + - [Unions](#unions) + - [Enums](#enums) + - [Maps](#maps) + - [Sets](#sets) + - [Instances](#instances) + - [Records](#records) + - [Functions // TODO](#functions--todo) + - [TypedArray](#typedarray) + - [Defining schemas (objects)](#defining-schemas-objects) + - [Utility types for TypeScript](#utility-types-for-typescript) + - [Extracting an interface from a schema](#extracting-an-interface-from-a-schema) + - [Defining the structure of a schema through an interface](#defining-the-structure-of-a-schema-through-an-interface) + - [`.extend`:](#extend) + - [`.pick` / `.omit`:](#pick--omit) + - [`.partial`](#partial) + - [`.required`](#required) + - [Handling unrecognized keys](#handling-unrecognized-keys) + - [`.strict`](#strict) + - [`.ignore`](#ignore) + - [`.passthrough`](#passthrough) + - [BaseValidator: methods and properties](#basevalidator-methods-and-properties) + - [`.run`](#rundata-unknown-resultt-error-given-a-validation-you-can-call-this-method-to-check-whether-or-not-the) + - [`.parse`](#parsedata-unknown-t-given-a-validations-you-can-call-this-method-to-check-whether-or-not-the-input-is-valid) + - [`.transform`](#transformrvalue-t--r-nopvalidatorr-adds-a-constraint-that-modifies-the-input) + - [`.reshape`](#reshapervalue-t--resultr-error--iconstraint-nopvalidatorr-adds-a-constraint-able-to-both-validate) + - [`.default`](#defaultvalue-t----t-transform-undefined-into-the-given-value-or-the-callbacks-returned-value) + - [`.optional`](#optional-a-convenience-method-that-returns-a-union-of-the-type-with-sundefined) + - [`.nullable`](#nullable-a-convenience-method-that-returns-a-union-of-the-type-with-snullable) + - [`.nullish`](#nullish-a-convenience-method-that-returns-a-union-of-the-type-with-snullish) + - [`.array`](#array-a-convenience-method-that-returns-an-arrayvalidator-with-the-type) + - [`.or`](#or-a-convenience-method-that-returns-an-unionvalidator-with-the-type-this-method-is-also-overridden-in) + - [`.when`](#when-adjust-the-schema-based-on-a-sibling-or-sinbling-children-fields) + - [Available options for providing `is`](#available-options-for-providing-is) + - [Resolving of the `key` (first) parameter](#resolving-of-the-key-first-parameter) + - [Examples](#examples) + - [Enabling and disabling validation](#enabling-and-disabling-validation) + - [Buy us some doughnuts](#buy-us-some-doughnuts) + - [Contributors](#contributors) + +## Description + +[Back to top][toc] + +A very fast and lightweight input validation and transformation library for JavaScript. + +> **Note**: Shapeshift requires Node.js v14.0.0 or higher to work. + +## Features + +[Back to top][toc] + +- TypeScript friendly +- Offers CJS, ESM and UMD builds +- API similar to [`zod`] +- Faster than ⚡ + +## Usage + +[Back to top][toc] + +**_For complete usages, please dive into our [documentation]_** + +### Basic usage + +[Back to top][toc] + +Creating a simple string validation + +```typescript +import { s } from '@sapphire/shapeshift'; + +const myStringValidation = s.string; + +// Parse +myStringValidation.parse('sapphire'); // => returns 'sapphire' +myStringValidation.parse(12); // throws ValidationError +``` + +Creating an object schema + +```typescript +import { s } from '@sapphire/shapeshift'; + +const user = s.object({ + username: s.string +}); + +user.parse({ username: 'Sapphire' }); +``` + +### Defining validations + +[Back to top][toc] + +#### Primitives + +[Back to top][toc] + +```typescript +import { s } from '@sapphire/shapeshift'; + +// Primitives +s.string; +s.number; +s.bigint; +s.boolean; +s.date; + +// Empty Types +s.undefined; +s.null; +s.nullish; // Accepts undefined | null + +// Catch-all Types +s.any; +s.unknown; + +// Never Type +s.never; +``` + +#### Literals + +[Back to top][toc] + +```typescript +s.literal('sapphire'); +s.literal(12); +s.literal(420n); +s.literal(true); +s.literal(new Date(1639278160000)); // s.date.equal(1639278160000); +``` + +#### Strings + +[Back to top][toc] + +Shapeshift includes a handful of string-specific validations: + +```typescript +s.string.lengthLessThan(5); +s.string.lengthLessThanOrEqual(5); +s.string.lengthGreaterThan(5); +s.string.lengthGreaterThanOrEqual(5); +s.string.lengthEqual(5); +s.string.lengthNotEqual(5); +s.string.email; +s.string.url(); +s.string.uuid(); +s.string.regex(regex); +s.string.ip(); +s.string.ipv4; +s.string.ipv6; +s.string.phone(); +``` + +#### Numbers + +[Back to top][toc] + +Shapeshift includes a handful of number-specific validations: + +```typescript +s.number.greaterThan(5); // > 5 +s.number.greaterThanOrEqual(5); // >= 5 +s.number.lessThan(5); // < 5 +s.number.lessThanOrEqual(5); // <= 5 +s.number.equal(5); // === 5 +s.number.notEqual(5); // !== 5 + +s.number.equal(NaN); // special case: Number.isNaN +s.number.notEqual(NaN); // special case: !Number.isNaN + +s.number.int; // value must be an integer +s.number.safeInt; // value must be a safe integer +s.number.finite; // value must be finite + +s.number.positive; // .greaterThanOrEqual(0) +s.number.negative; // .lessThan(0) + +s.number.divisibleBy(5); // Divisible by 5 +``` + +And transformations: + +```typescript +s.number.abs; // Transforms the number to an absolute number +s.number.sign; // Gets the number's sign + +s.number.trunc; // Transforms the number to the result of `Math.trunc` +s.number.floor; // Transforms the number to the result of `Math.floor` +s.number.fround; // Transforms the number to the result of `Math.fround` +s.number.round; // Transforms the number to the result of `Math.round` +s.number.ceil; // Transforms the number to the result of `Math.ceil` +``` + +#### BigInts + +[Back to top][toc] + +Shapeshift includes a handful of number-specific validations: + +```typescript +s.bigint.greaterThan(5n); // > 5n +s.bigint.greaterThanOrEqual(5n); // >= 5n +s.bigint.lessThan(5n); // < 5n +s.bigint.lessThanOrEqual(5n); // <= 5n +s.bigint.equal(5n); // === 5n +s.bigint.notEqual(5n); // !== 5n + +s.bigint.positive; // .greaterThanOrEqual(0n) +s.bigint.negative; // .lessThan(0n) + +s.bigint.divisibleBy(5n); // Divisible by 5n +``` + +And transformations: + +```typescript +s.bigint.abs; // Transforms the bigint to an absolute bigint + +s.bigint.intN(5); // Clamps to a bigint to a signed bigint with 5 digits, see BigInt.asIntN +s.bigint.uintN(5); // Clamps to a bigint to an unsigned bigint with 5 digits, see BigInt.asUintN +``` + +#### Booleans + +[Back to top][toc] + +Shapeshift includes a few boolean-specific validations: + +```typescript +s.boolean.true; // value must be true +s.boolean.false; // value must be false + +s.boolean.equal(true); // s.boolean.true +s.boolean.equal(false); // s.boolean.false + +s.boolean.notEqual(true); // s.boolean.false +s.boolean.notEqual(false); // s.boolean.true +``` + +#### Arrays + +[Back to top][toc] + +```typescript +const stringArray = s.array(s.string); +const stringArray = s.string.array; +``` + +Shapeshift includes a handful of array-specific validations: + +```typescript +s.string.array.lengthLessThan(5); // Must have less than 5 elements +s.string.array.lengthLessThanOrEqual(5); // Must have 5 or less elements +s.string.array.lengthGreaterThan(5); // Must have more than 5 elements +s.string.array.lengthGreaterThanOrEqual(5); // Must have 5 or more elements +s.string.array.lengthEqual(5); // Must have exactly 5 elements +s.string.array.lengthNotEqual(5); // Must not have exactly 5 elements +s.string.array.lengthRange(0, 4); // Must have at least 0 elements and less than 4 elements (in math, that is [0, 4)) +s.string.array.lengthRangeInclusive(0, 4); // Must have at least 0 elements and at most 4 elements (in math, that is [0, 4]) +s.string.array.lengthRangeExclusive(0, 4); // Must have more than 0 element and less than 4 elements (in math, that is (0, 4)) +s.string.array.unique; // All elements must be unique. Deep equality is used to check for uniqueness. +``` + +> **Note**: All `.length` methods define tuple types with the given amount of elements. For example, +> `s.string.array.lengthGreaterThanOrEqual(2)`'s inferred type is `[string, string, ...string[]]` + +#### Tuples + +[Back to top][toc] + +Unlike arrays, tuples have a fixed number of elements and each element can have a different type: + +```typescript +const dish = s.tuple([ + s.string, // Dish's name + s.number.int, // Table's number + s.date // Date the dish was ready for delivery +]); + +dish.parse(['Iberian ham', 10, new Date()]); +``` + +#### Unions + +[Back to top][toc] + +Shapeshift includes a built-in method for composing OR types: + +```typescript +const stringOrNumber = s.union(s.string, s.number); + +stringOrNumber.parse('Sapphire'); // => 'Sapphire' +stringOrNumber.parse(42); // => 42 +stringOrNumber.parse({}); // => throws CombinedError +``` + +#### Enums + +[Back to top][toc] + +Enums are a convenience method that aliases `s.union(s.literal(a), s.literal(b), ...)`: + +```typescript +s.enum('Red', 'Green', 'Blue'); +// s.union(s.literal('Red'), s.literal('Green'), s.literal('Blue')); +``` + +#### Maps + +[Back to top][toc] + +```typescript +const map = s.map(s.string, s.number); +// Map +``` + +#### Sets + +[Back to top][toc] + +```typescript +const set = s.set(s.number); +// Set +``` + +#### Instances + +[Back to top][toc] + +You can use `s.instance(Class)` to check that the input is an instance of a class. This is useful to validate inputs +against classes: + +```typescript +class User { + public constructor(public name: string) {} +} + +const userInstanceValidation = s.instance(User); +userInstanceValidation.parse(new User('Sapphire')); // => User { name: 'Sapphire' } +userInstanceValidation.parse('oops'); // => throws ValidatorError +``` + +#### Records + +[Back to top][toc] + +Record validations are similar to objects, but validate `Record` types. Keep in mind this does not check for +the keys, and cannot support validation for specific ones: + +```typescript +const tags = s.record(s.string); + +tags.parse({ foo: 'bar', hello: 'world' }); // => { foo: 'bar', hello: 'world' } +tags.parse({ foo: 42 }); // => throws CombinedError +tags.parse('Hello'); // => throws ValidateError +``` + +--- + +_**Function validation is not yet implemented and will be made available starting v2.1.0**_ + +#### Functions // TODO + +[Back to top][toc] + +You can define function validations. This checks for whether or not an input is a function: + +```typescript +s.function; // () => unknown +``` + +You can define arguments by passing an array as the first argument, as well as the return type as the second: + +```typescript +s.function([s.string]); // (arg0: string) => unknown +s.function([s.string, s.number], s.string); // (arg0: string, arg1: number) => string +``` + +> **Note**: Shapeshift will transform the given function into one with validation on arguments and output. You can +> access the `.raw` property of the function to get the unchecked function. + +--- + +#### TypedArray + +[Back to top][toc] + +```ts +const typedArray = s.typedArray(); +const int16Array = s.int16Array; +const uint16Array = s.uint16Array; +const uint8ClampedArray = s.uint8ClampedArray; +const int16Array = s.int16Array; +const uint16Array = s.uint16Array; +const int32Array = s.int32Array; +const uint32Array = s.uint32Array; +const float32Array = s.float32Array; +const float64Array = s.float64Array; +const bigInt64Array = s.bigInt64Array; +const bigUint64Array = s.bigUint64Array; +``` + +Shapeshift includes a handful of validations specific to typed arrays. + +```typescript +s.typedArray().lengthLessThan(5); // Length must be less than 5 +s.typedArray().lengthLessThanOrEqual(5); // Length must be 5 or less +s.typedArray().lengthGreaterThan(5); // Length must be more than 5 +s.typedArray().lengthGreaterThanOrEqual(5); // Length must be 5 or more +s.typedArray().lengthEqual(5); // Length must be exactly 5 +s.typedArray().lengthNotEqual(5); // Length must not be 5 +s.typedArray().lengthRange(0, 4); // Length L must satisfy 0 <= L < 4 +s.typedArray().lengthRangeInclusive(0, 4); // Length L must satisfy 0 <= L <= 4 +s.typedArray().lengthRangeExclusive(0, 4); // Length L must satisfy 0 < L < 4 +``` + +Note that all of these methods have analogous methods for working with the typed array's byte length, +`s.typedArray().byteLengthX()` - for instance, `s.typedArray().byteLengthLessThan(5)` is the same as +`s.typedArray().lengthLessThan(5)` but for the array's byte length. + +--- + +### Defining schemas (objects) + +[Back to top][toc] + +```typescript +// Properties are required by default: +const animal = s.object({ + name: s.string, + age: s.number +}); +``` + +#### Utility types for TypeScript + +[Back to top][toc] + +For object validation Shapeshift exports 2 utility types that can be used to extract interfaces from schemas and define +the structure of a schema as an interface beforehand respectively. + +##### Extracting an interface from a schema + +[Back to top][toc] + +You can use the `InferType` type to extract the interface from a schema, for example: + +```typescript +import { InferType, s } from '@sapphire/shapeshift'; + +const schema = s.object({ + foo: s.string, + bar: s.number, + baz: s.boolean, + qux: s.bigint, + quux: s.date +}); + +type Inferredtype = InferType; + +// Expected type: +type Inferredtype = { + foo: string; + bar: number; + baz: boolean; + qux: bigint; + quux: Date; +}; +``` + +##### Defining the structure of a schema through an interface + +[Back to top][toc] + +You can use the `SchemaOf` type to define the structure of a schema before defining the actual schema, for example: + +```typescript +import { s, SchemaOf } from '@sapphire/shapeshift'; + +interface IIngredient { + ingredientId: string | undefined; + name: string | undefined; +} + +interface IInstruction { + instructionId: string | undefined; + message: string | undefined; +} + +interface IRecipe { + recipeId: string | undefined; + title: string; + description: string; + instructions: IInstruction[]; + ingredients: IIngredient[]; +} + +type InstructionSchemaType = SchemaOf; +// Expected Type: ObjectValidator + +type IngredientSchemaType = SchemaOf; +// Expected Type: ObjectValidator + +type RecipeSchemaType = SchemaOf; +// Expected Type: ObjectValidator + +const instructionSchema: InstructionSchemaType = s.object({ + instructionId: s.string.optional, + message: s.string +}); + +const ingredientSchema: IngredientSchemaType = s.object({ + ingredientId: s.string.optional, + name: s.string +}); + +const recipeSchema: RecipeSchemaType = s.object({ + recipeId: s.string.optional, + title: s.string, + description: s.string, + instructions: s.array(instructionSchema), + ingredients: s.array(ingredientSchema) +}); +``` + +#### `.extend`: + +[Back to top][toc] + +You can add additional fields using either an object or an ObjectValidator, in this case, you will get a new object +validator with the merged properties: + +```typescript +const animal = s.object({ + name: s.string.optional, + age: s.number +}); + +const pet = animal.extend({ + owner: s.string.nullish +}); + +const pet = animal.extend( + s.object({ + owner: s.string.nullish + }) +); +``` + +> If both schemas share keys, an error will be thrown. Please use `.omit` on the first object if you desire this +> behaviour. + +#### `.pick` / `.omit`: + +[Back to top][toc] + +Inspired by TypeScript's built-in `Pick` and `Omit` utility types, all object schemas have the aforementioned methods +that return a modifier version: + +```typescript +const pkg = s.object({ + name: s.string, + description: s.string, + dependencies: s.string.array +}); + +const justTheName = pkg.pick(['name']); +// s.object({ name: s.string }); + +const noDependencies = pkg.omit(['dependencies']); +// s.object({ name: s.string, description: s.string }); +``` + +#### `.partial` + +[Back to top][toc] + +Inspired by TypeScript's built-in `Partial` utility type, all object schemas have the aforementioned method that makes +all properties optional: + +```typescript +const user = s.object({ + username: s.string, + password: s.string +}).partial; +``` + +Which is the same as doing: + +```typescript +const user = s.object({ + username: s.string.optional, + password: s.string.optional +}); +``` + +--- + +#### `.required` + +[Back to top][toc] + +Inspired by TypeScript's built-in `Required` utility type, all object schemas have the aforementioned method that makes +all properties required: + +```typescript +const user = s.object({ + username: s.string.optional, + password: s.string.optional +}).required; +``` + +Which is the same as doing: + +```typescript +const user = s.object({ + username: s.string, + password: s.string +}); +``` + +--- + +### Handling unrecognized keys + +[Back to top][toc] + +By default, Shapeshift will not include keys that are not defined by the schema during parsing: + +```typescript +const person = s.object({ + framework: s.string +}); + +person.parse({ + framework: 'Sapphire', + awesome: true +}); +// => { name: 'Sapphire' } +``` + +#### `.strict` + +[Back to top][toc] + +You can disallow unknown keys with `.strict`. If the input includes any unknown keys, an error will be thrown. + +```typescript +const person = s.object({ + framework: s.string +}).strict; + +person.parse({ + framework: 'Sapphire', + awesome: true +}); +// => throws ValidationError +``` + +#### `.ignore` + +[Back to top][toc] + +You can use the `.ignore` getter to reset an object schema to the default behaviour (ignoring unrecognized keys). + +#### `.passthrough` + +[Back to top][toc] + +You can use the `.passthrough` getter to make the validator add the unrecognized properties the shape does not have, +from the input. + +--- + +### BaseValidator: methods and properties + +[Back to top][toc] + +All validations in Shapeshift contain certain methods. + +- #### `.run(data: unknown): Result`: given a validation, you can call this method to check whether or not the + + input is valid. If it is, a `Result` with `success: true` and a deep-cloned value will be returned with the given + constraints and transformations. Otherwise, a `Result` with `success: false` and an error is returned. + +- #### `.parse(data: unknown): T`: given a validations, you can call this method to check whether or not the input is valid. + + If it is, a deep-cloned value will be returned with the given constraints and transformations. Otherwise, an error is + thrown. + +- #### `.transform((value: T) => R): NopValidator`: adds a constraint that modifies the input: + +```typescript +import { s } from '@sapphire/shapeshift'; + +const getLength = s.string.transform((value) => value.length); +getLength.parse('Hello There'); // => 11 +``` + +> :warning: `.transform`'s functions **must not throw**. If a validation error is desired to be thrown, `.reshape` +> instead. + +- #### `.reshape((value: T) => Result | IConstraint): NopValidator`: adds a constraint able to both validate + and modify the input: + +```typescript +import { s, Result } from '@sapphire/shapeshift'; + +const getLength = s.string.reshape((value) => Result.ok(value.length)); +getLength.parse('Hello There'); // => 11 +``` + +> :warning: `.reshape`'s functions **must not throw**. If a validation error is desired to be thrown, use +> `Result.err(error)` instead. + +- #### `.default(value: T | (() => T))`: transform `undefined` into the given value or the callback's returned value: + +```typescript +const name = s.string.default('Sapphire'); +name.parse('Hello'); // => 'Hello' +name.parse(undefined); // => 'Sapphire' +``` + +```typescript +const number = s.number.default(Math.random); +number.parse(12); // => 12 +number.parse(undefined); // => 0.989911985608602 +number.parse(undefined); // => 0.3224350185068794 +``` + +> :warning: The default values are not validated. + +- #### `.optional`: a convenience method that returns a union of the type with `s.undefined`. + +```typescript +s.string.optional; // s.union(s.string, s.undefined) +``` + +- #### `.nullable`: a convenience method that returns a union of the type with `s.nullable`. + +```typescript +s.string.nullable; // s.union(s.string, s.nullable) +``` + +- #### `.nullish`: a convenience method that returns a union of the type with `s.nullish`. + +```typescript +s.string.nullish; // s.union(s.string, s.nullish) +``` + +- #### `.array`: a convenience method that returns an ArrayValidator with the type. + +```typescript +s.string.array; // s.array(s.string) +``` + +- #### `.or`: a convenience method that returns an UnionValidator with the type. This method is also overridden in + UnionValidator to just append one more entry. + +```typescript +s.string.or(s.number); +// => s.union(s.string, s.number) + +s.object({ name: s.string }).or(s.string, s.number); +// => s.union(s.object({ name: s.string }), s.string, s.number) +``` + +- #### `.when`: Adjust the schema based on a sibling or sinbling children fields. + +For using when you provide an object literal where the key `is` is undefined, a value, or a matcher function; `then` +provides the schema when `is` resolves truthy, and `otherwise` provides the schema when `is` resolves falsey. + +##### Available options for providing `is` + +When `is` is not provided (`=== undefined`) it is strictly resolved as `Boolean(value)` wherein `value` is the current +value of the referenced sibling. Note that if multiple siblings are referenced then all the values of the array need to +resolve truthy for the `is` to resolve truthy. + +When `is` is a primitive literal it is strictly compared (`===`) to the current value. + +If you want to use a different form of equality you can provide a function like: `is: (value) => value === true`. + +##### Resolving of the `key` (first) parameter + +For resolving the `key` parameter to its respective value we use [lodash/get](https://lodash.com/docs#get). This means +that every way that Lodash supports resolving a key to its respective value is also supported by Shapeshift. This +includes: + +- Simply providing a string or number like `'name'` or `1`. +- Providing a string or number with a dot notation like `'name.first'` (representative of a nested object structure of + `{ 'name': { 'first': 'Sapphire' } }` => resolves to `Sapphire`). +- Providing a string or number with a bracket notation like `'name[0]'` (representative of an array structure of + `{ 'name': ['Sapphire', 'Framework'] }` => resolves to `Sapphire`). +- Providing a string or number with a dot and bracket notation like `'name[1].first'` (representative of a nested object + structure of `{ 'name': [{ 'first': 'Sapphire' }, { 'first': 'Framework' }] }` => resolves to `Framework`). + +##### Examples + +Let's start with a basic example: + +```typescript +const whenPredicate = s.object({ + booleanLike: s.boolean, + numberLike: s.number.when('booleanLike', { + then: (schema) => schema.greaterThanOrEqual(5), + otherwise: (schema) => schema.lessThanOrEqual(5) + }) +}); + +whenPredicate.parse({ booleanLike: true, numberLike: 6 }); +// => { booleanLike: true, numberLike: 6 } + +whenPredicate.parse({ booleanLike: true, numberLike: 4 }); +// => ExpectedConstraintError('s.number.greaterThanOrEqual', 'Invalid number value', 4, 'expected >= 5') + +whenPredicate.parse({ booleanLike: false, numberLike: 4 }); +// => { booleanLike: false, numberLike: 4 } +``` + +The provided key can also be an array of sibling children: + +```typescript +const whenPredicate = s.object({ + booleanLike: s.boolean, + stringLike: s.string, + numberLike: s.number.when(['booleanLike', 'stringLike'], { + is: ([booleanLikeValue, stringLikeValue]) => booleanLikeValue === true && stringLikeValue === 'foobar', + then: (schema) => schema.greaterThanOrEqual(5), + otherwise: (schema) => schema.lessThanOrEqual(5) + }) +}); + +whenPredicate.parse({ booleanLike: true, stringLike: 'foobar', numberLike: 6 }); +// => { booleanLike: true, numberLike: 6 } + +whenPredicate.parse({ booleanLike: true, stringLike: 'barfoo', numberLike: 4 }); +// => ExpectedConstraintError('s.number.greaterThanOrEqual', 'Invalid number value', 4, 'expected >= 5') + +whenPredicate.parse({ booleanLike: false, stringLike: 'foobar' numberLike: 4 }); +// => ExpectedConstraintError('s.number.greaterThanOrEqual', 'Invalid number value', 4, 'expected >= 5') +``` + +### Enabling and disabling validation + +[Back to top][toc] + +At times, you might want to have a consistent code base with validation, but would like to keep validation to the strict +necessities instead of the in-depth constraints available in shapeshift. By calling `setGlobalValidationEnabled` you can +disable validation at a global level, and by calling `setValidationEnabled` you can disable validation on a +per-validator level. + +> When setting the validation enabled status per-validator, you can also set it to `null` to use the global setting. + +```typescript +import { setGlobalValidationEnabled } from '@sapphire/shapeshift'; + +setGlobalValidationEnabled(false); +``` + +```typescript +import { s } from '@sapphire/shapeshift'; + +const predicate = s.string.lengthGreaterThan(5).setValidationEnabled(false); +``` + +## Buy us some doughnuts + +[Back to top][toc] + +Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are +amazing people who may still want to donate just to show their appreciation. Thank you very much in advance! + +We accept donations through Open Collective, Ko-fi, Paypal, Patreon and GitHub Sponsorships. You can use the buttons +below to donate through your method of choice. + +| Donate With | Address | +| :-------------: | :-------------------------------------------------: | +| Open Collective | [Click Here](https://sapphirejs.dev/opencollective) | +| Ko-fi | [Click Here](https://sapphirejs.dev/kofi) | +| Patreon | [Click Here](https://sapphirejs.dev/patreon) | +| PayPal | [Click Here](https://sapphirejs.dev/paypal) | + +## Contributors + +[Back to top][toc] + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + + + + + + + + + + + +

Antonio Román

💻 📖 🤔

Vlad Frangu

💻 📖 🤔

Jeroen Claassens

📖 🚧 🚇

renovate[bot]

🚧

WhiteSource Renovate

🚧

John

💻

Parbez

💻 ⚠️ 🐛 📖

allcontributors[bot]

📖

Hezekiah Hendry

🔧

Voxelli

📖
+ + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. +Contributions of any kind welcome! + +[`zod`]: https://github.com/colinhacks/zod +[documentation]: https://www.sapphirejs.dev/docs/Documentation/api-shapeshift/ +[toc]: #table-of-contents diff --git a/node_modules/@sapphire/shapeshift/dist/index.d.ts b/node_modules/@sapphire/shapeshift/dist/index.d.ts new file mode 100644 index 0000000..586de82 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/dist/index.d.ts @@ -0,0 +1,713 @@ +import { InspectOptionsStylized } from 'node:util'; + +declare class Result { + readonly success: boolean; + readonly value?: T; + readonly error?: E; + private constructor(); + isOk(): this is { + success: true; + value: T; + }; + isErr(): this is { + success: false; + error: E; + }; + unwrap(): T; + static ok(value: T): Result; + static err(error: E): Result; +} + +type ArrayConstraintName = `s.array(T).${'unique' | `length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual' | 'Range' | 'RangeInclusive' | 'RangeExclusive'}`}`; +declare function arrayLengthLessThan(value: number): IConstraint; +declare function arrayLengthLessThanOrEqual(value: number): IConstraint; +declare function arrayLengthGreaterThan(value: number): IConstraint; +declare function arrayLengthGreaterThanOrEqual(value: number): IConstraint; +declare function arrayLengthEqual(value: number): IConstraint; +declare function arrayLengthNotEqual(value: number): IConstraint; +declare function arrayLengthRange(start: number, endBefore: number): IConstraint; +declare function arrayLengthRangeInclusive(start: number, end: number): IConstraint; +declare function arrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint; + +type BigIntConstraintName = `s.bigint.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'notEqual' | 'divisibleBy'}`; +declare function bigintLessThan(value: bigint): IConstraint; +declare function bigintLessThanOrEqual(value: bigint): IConstraint; +declare function bigintGreaterThan(value: bigint): IConstraint; +declare function bigintGreaterThanOrEqual(value: bigint): IConstraint; +declare function bigintEqual(value: bigint): IConstraint; +declare function bigintNotEqual(value: bigint): IConstraint; +declare function bigintDivisibleBy(divider: bigint): IConstraint; + +type BooleanConstraintName = `s.boolean.${boolean}`; +declare const booleanTrue: IConstraint; +declare const booleanFalse: IConstraint; + +type DateConstraintName = `s.date.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'notEqual' | 'valid' | 'invalid'}`; +declare function dateLessThan(value: Date): IConstraint; +declare function dateLessThanOrEqual(value: Date): IConstraint; +declare function dateGreaterThan(value: Date): IConstraint; +declare function dateGreaterThanOrEqual(value: Date): IConstraint; +declare function dateEqual(value: Date): IConstraint; +declare function dateNotEqual(value: Date): IConstraint; +declare const dateInvalid: IConstraint; +declare const dateValid: IConstraint; + +type NumberConstraintName = `s.number.${'lessThan' | 'lessThanOrEqual' | 'greaterThan' | 'greaterThanOrEqual' | 'equal' | 'equal(NaN)' | 'notEqual' | 'notEqual(NaN)' | 'int' | 'safeInt' | 'finite' | 'divisibleBy'}`; +declare function numberLessThan(value: number): IConstraint; +declare function numberLessThanOrEqual(value: number): IConstraint; +declare function numberGreaterThan(value: number): IConstraint; +declare function numberGreaterThanOrEqual(value: number): IConstraint; +declare function numberEqual(value: number): IConstraint; +declare function numberNotEqual(value: number): IConstraint; +declare const numberInt: IConstraint; +declare const numberSafeInt: IConstraint; +declare const numberFinite: IConstraint; +declare const numberNaN: IConstraint; +declare const numberNotNaN: IConstraint; +declare function numberDivisibleBy(divider: number): IConstraint; + +declare const customInspectSymbol: unique symbol; +declare const customInspectSymbolStackLess: unique symbol; +declare abstract class BaseError extends Error { + protected [customInspectSymbol](depth: number, options: InspectOptionsStylized): string; + protected abstract [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +declare class CombinedError extends BaseError { + readonly errors: readonly BaseError[]; + constructor(errors: readonly BaseError[]); + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +declare class ValidationError extends BaseError { + readonly validator: string; + readonly given: unknown; + constructor(validator: string, message: string, given: unknown); + toJSON(): { + name: string; + validator: string; + given: unknown; + }; + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +declare class ExpectedValidationError extends ValidationError { + readonly expected: T; + constructor(validator: string, message: string, given: unknown, expected: T); + toJSON(): { + name: string; + validator: string; + given: unknown; + expected: T; + }; + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +declare class MissingPropertyError extends BaseError { + readonly property: PropertyKey; + constructor(property: PropertyKey); + toJSON(): { + name: string; + property: PropertyKey; + }; + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +declare class MultiplePossibilitiesConstraintError extends BaseConstraintError { + readonly expected: readonly string[]; + constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: readonly string[]); + toJSON(): { + name: string; + constraint: ConstraintErrorNames; + given: T; + expected: readonly string[]; + }; + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +declare class UnknownEnumValueError extends BaseError { + readonly value: string | number; + readonly enumKeys: string[]; + readonly enumMappings: Map; + constructor(value: string | number, keys: string[], enumMappings: Map); + toJSON(): { + name: string; + value: string | number; + enumKeys: string[]; + enumMappings: [string | number, string | number][]; + }; + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +declare class UnknownPropertyError extends BaseError { + readonly property: PropertyKey; + readonly value: unknown; + constructor(property: PropertyKey, value: unknown); + toJSON(): { + name: string; + property: PropertyKey; + value: unknown; + }; + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +declare class BigIntValidator extends BaseValidator { + lessThan(number: bigint): this; + lessThanOrEqual(number: bigint): this; + greaterThan(number: bigint): this; + greaterThanOrEqual(number: bigint): this; + equal(number: N): BigIntValidator; + notEqual(number: bigint): this; + get positive(): this; + get negative(): this; + divisibleBy(number: bigint): this; + get abs(): this; + intN(bits: number): this; + uintN(bits: number): this; + protected handle(value: unknown): Result; +} + +declare class BooleanValidator extends BaseValidator { + get true(): BooleanValidator; + get false(): BooleanValidator; + equal(value: R): BooleanValidator; + notEqual(value: R): BooleanValidator; + protected handle(value: unknown): Result; +} + +declare class DateValidator extends BaseValidator { + lessThan(date: Date | number | string): this; + lessThanOrEqual(date: Date | number | string): this; + greaterThan(date: Date | number | string): this; + greaterThanOrEqual(date: Date | number | string): this; + equal(date: Date | number | string): this; + notEqual(date: Date | number | string): this; + get valid(): this; + get invalid(): this; + protected handle(value: unknown): Result; +} + +declare class DefaultValidator extends BaseValidator { + private readonly validator; + private defaultValue; + constructor(validator: BaseValidator, value: T | (() => T), constraints?: readonly IConstraint[]); + default(value: Exclude | (() => Exclude)): DefaultValidator>; + protected handle(value: unknown): Result; + protected clone(): this; +} + +declare class InstanceValidator extends BaseValidator { + readonly expected: Constructor; + constructor(expected: Constructor, constraints?: readonly IConstraint[]); + protected handle(value: unknown): Result>>; + protected clone(): this; +} + +declare class LiteralValidator extends BaseValidator { + readonly expected: T; + constructor(literal: T, constraints?: readonly IConstraint[]); + protected handle(value: unknown): Result>; + protected clone(): this; +} + +declare class CombinedPropertyError extends BaseError { + readonly errors: [PropertyKey, BaseError][]; + constructor(errors: [PropertyKey, BaseError][]); + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; + private static formatProperty; +} + +declare class MapValidator extends BaseValidator> { + private readonly keyValidator; + private readonly valueValidator; + constructor(keyValidator: BaseValidator, valueValidator: BaseValidator, constraints?: readonly IConstraint>[]); + protected clone(): this; + protected handle(value: unknown): Result, ValidationError | CombinedPropertyError>; +} + +declare class NativeEnumValidator extends BaseValidator { + readonly enumShape: T; + readonly hasNumericElements: boolean; + private readonly enumKeys; + private readonly enumMapping; + constructor(enumShape: T); + protected handle(value: unknown): Result; + protected clone(): this; +} +interface NativeEnumLike { + [key: string]: string | number; + [key: number]: string; +} + +declare class NeverValidator extends BaseValidator { + protected handle(value: unknown): Result; +} + +declare class NullishValidator extends BaseValidator { + protected handle(value: unknown): Result; +} + +declare class NumberValidator extends BaseValidator { + lessThan(number: number): this; + lessThanOrEqual(number: number): this; + greaterThan(number: number): this; + greaterThanOrEqual(number: number): this; + equal(number: N): NumberValidator; + notEqual(number: number): this; + get int(): this; + get safeInt(): this; + get finite(): this; + get positive(): this; + get negative(): this; + divisibleBy(divider: number): this; + get abs(): this; + get sign(): this; + get trunc(): this; + get floor(): this; + get fround(): this; + get round(): this; + get ceil(): this; + protected handle(value: unknown): Result; +} + +declare class ObjectValidator> extends BaseValidator { + readonly shape: MappedObjectValidator; + readonly strategy: ObjectValidatorStrategy; + private readonly keys; + private readonly handleStrategy; + private readonly requiredKeys; + private readonly possiblyUndefinedKeys; + private readonly possiblyUndefinedKeysWithDefaults; + constructor(shape: MappedObjectValidator, strategy?: ObjectValidatorStrategy, constraints?: readonly IConstraint[]); + get strict(): this; + get ignore(): this; + get passthrough(): this; + get partial(): ObjectValidator<{ + [Key in keyof I]?: I[Key]; + }>; + get required(): ObjectValidator<{ + [Key in keyof I]-?: I[Key]; + }>; + extend(schema: ObjectValidator | MappedObjectValidator): ObjectValidator; + pick(keys: readonly K[]): ObjectValidator<{ + [Key in keyof Pick]: I[Key]; + }>; + omit(keys: readonly K[]): ObjectValidator<{ + [Key in keyof Omit]: I[Key]; + }>; + protected handle(value: unknown): Result; + protected clone(): this; + private handleIgnoreStrategy; + private handleStrictStrategy; + private handlePassthroughStrategy; +} +declare const enum ObjectValidatorStrategy { + Ignore = 0, + Strict = 1, + Passthrough = 2 +} + +declare class PassthroughValidator extends BaseValidator { + protected handle(value: unknown): Result; +} + +declare class RecordValidator extends BaseValidator> { + private readonly validator; + constructor(validator: BaseValidator, constraints?: readonly IConstraint>[]); + protected clone(): this; + protected handle(value: unknown): Result, ValidationError | CombinedPropertyError>; +} + +declare class SetValidator extends BaseValidator> { + private readonly validator; + constructor(validator: BaseValidator, constraints?: readonly IConstraint>[]); + protected clone(): this; + protected handle(values: unknown): Result, ValidationError | CombinedError>; +} + +type StringConstraintName = `s.string.${`length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual'}` | 'regex' | 'url' | 'uuid' | 'email' | `ip${'v4' | 'v6' | ''}` | 'date' | 'phone'}`; +type StringProtocol = `${string}:`; +type StringDomain = `${string}.${string}`; +interface UrlOptions { + allowedProtocols?: StringProtocol[]; + allowedDomains?: StringDomain[]; +} +type UUIDVersion = 1 | 3 | 4 | 5; +interface StringUuidOptions { + version?: UUIDVersion | `${UUIDVersion}-${UUIDVersion}` | null; + nullable?: boolean; +} +declare function stringLengthLessThan(length: number): IConstraint; +declare function stringLengthLessThanOrEqual(length: number): IConstraint; +declare function stringLengthGreaterThan(length: number): IConstraint; +declare function stringLengthGreaterThanOrEqual(length: number): IConstraint; +declare function stringLengthEqual(length: number): IConstraint; +declare function stringLengthNotEqual(length: number): IConstraint; +declare function stringEmail(): IConstraint; +declare function stringUrl(options?: UrlOptions): IConstraint; +declare function stringIp(version?: 4 | 6): IConstraint; +declare function stringRegex(regex: RegExp): IConstraint; +declare function stringUuid({ version, nullable }?: StringUuidOptions): IConstraint; + +declare class StringValidator extends BaseValidator { + lengthLessThan(length: number): this; + lengthLessThanOrEqual(length: number): this; + lengthGreaterThan(length: number): this; + lengthGreaterThanOrEqual(length: number): this; + lengthEqual(length: number): this; + lengthNotEqual(length: number): this; + get email(): this; + url(options?: UrlOptions): this; + uuid(options?: StringUuidOptions): this; + regex(regex: RegExp): this; + get date(): this; + get ipv4(): this; + get ipv6(): this; + ip(version?: 4 | 6): this; + phone(): this; + protected handle(value: unknown): Result; +} + +declare class TupleValidator extends BaseValidator<[...T]> { + private readonly validators; + constructor(validators: BaseValidator<[...T]>[], constraints?: readonly IConstraint<[...T]>[]); + protected clone(): this; + protected handle(values: unknown): Result<[...T], ValidationError | CombinedPropertyError>; +} + +type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; +declare const TypedArrays: { + readonly Int8Array: (x: unknown) => x is Int8Array; + readonly Uint8Array: (x: unknown) => x is Uint8Array; + readonly Uint8ClampedArray: (x: unknown) => x is Uint8ClampedArray; + readonly Int16Array: (x: unknown) => x is Int16Array; + readonly Uint16Array: (x: unknown) => x is Uint16Array; + readonly Int32Array: (x: unknown) => x is Int32Array; + readonly Uint32Array: (x: unknown) => x is Uint32Array; + readonly Float32Array: (x: unknown) => x is Float32Array; + readonly Float64Array: (x: unknown) => x is Float64Array; + readonly BigInt64Array: (x: unknown) => x is BigInt64Array; + readonly BigUint64Array: (x: unknown) => x is BigUint64Array; + readonly TypedArray: (x: unknown) => x is TypedArray; +}; +type TypedArrayName = keyof typeof TypedArrays; + +declare class TypedArrayValidator extends BaseValidator { + private readonly type; + constructor(type: TypedArrayName, constraints?: readonly IConstraint[]); + byteLengthLessThan(length: number): this; + byteLengthLessThanOrEqual(length: number): this; + byteLengthGreaterThan(length: number): this; + byteLengthGreaterThanOrEqual(length: number): this; + byteLengthEqual(length: number): this; + byteLengthNotEqual(length: number): this; + byteLengthRange(start: number, endBefore: number): this; + byteLengthRangeInclusive(startAt: number, endAt: number): this; + byteLengthRangeExclusive(startAfter: number, endBefore: number): this; + lengthLessThan(length: number): this; + lengthLessThanOrEqual(length: number): this; + lengthGreaterThan(length: number): this; + lengthGreaterThanOrEqual(length: number): this; + lengthEqual(length: number): this; + lengthNotEqual(length: number): this; + lengthRange(start: number, endBefore: number): this; + lengthRangeInclusive(startAt: number, endAt: number): this; + lengthRangeExclusive(startAfter: number, endBefore: number): this; + protected clone(): this; + protected handle(value: unknown): Result; +} + +declare class UnionValidator extends BaseValidator { + private validators; + constructor(validators: readonly BaseValidator[], constraints?: readonly IConstraint[]); + get optional(): UnionValidator; + get required(): UnionValidator>; + get nullable(): UnionValidator; + get nullish(): UnionValidator; + or(...predicates: readonly BaseValidator[]): UnionValidator; + protected clone(): this; + protected handle(value: unknown): Result; +} + +type ObjectConstraintName = `s.object(T.when)`; +type WhenKey = PropertyKey | PropertyKey[]; +interface WhenOptions, Key extends WhenKey> { + is?: boolean | ((value: Key extends Array ? any[] : any) => boolean); + then: (predicate: T) => T; + otherwise?: (predicate: T) => T; +} + +declare class ExpectedConstraintError extends BaseConstraintError { + readonly expected: string; + constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: string); + toJSON(): { + name: string; + constraint: ConstraintErrorNames; + given: T; + expected: string; + }; + protected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string; +} + +type TypedArrayConstraintName = `s.typedArray(T).${'byteLength' | 'length'}${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual' | 'Range' | 'RangeInclusive' | 'RangeExclusive'}`; +declare function typedArrayByteLengthLessThan(value: number): IConstraint; +declare function typedArrayByteLengthLessThanOrEqual(value: number): IConstraint; +declare function typedArrayByteLengthGreaterThan(value: number): IConstraint; +declare function typedArrayByteLengthGreaterThanOrEqual(value: number): IConstraint; +declare function typedArrayByteLengthEqual(value: number): IConstraint; +declare function typedArrayByteLengthNotEqual(value: number): IConstraint; +declare function typedArrayByteLengthRange(start: number, endBefore: number): IConstraint; +declare function typedArrayByteLengthRangeInclusive(start: number, end: number): { + run(input: T): Result | Result>; +}; +declare function typedArrayByteLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint; +declare function typedArrayLengthLessThan(value: number): IConstraint; +declare function typedArrayLengthLessThanOrEqual(value: number): IConstraint; +declare function typedArrayLengthGreaterThan(value: number): IConstraint; +declare function typedArrayLengthGreaterThanOrEqual(value: number): IConstraint; +declare function typedArrayLengthEqual(value: number): IConstraint; +declare function typedArrayLengthNotEqual(value: number): IConstraint; +declare function typedArrayLengthRange(start: number, endBefore: number): IConstraint; +declare function typedArrayLengthRangeInclusive(start: number, end: number): IConstraint; +declare function typedArrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint; + +type ConstraintErrorNames = TypedArrayConstraintName | ArrayConstraintName | BigIntConstraintName | BooleanConstraintName | DateConstraintName | NumberConstraintName | ObjectConstraintName | StringConstraintName; +declare abstract class BaseConstraintError extends BaseError { + readonly constraint: ConstraintErrorNames; + readonly given: T; + constructor(constraint: ConstraintErrorNames, message: string, given: T); +} + +interface IConstraint { + run(input: Input, parent?: any): Result>; +} + +declare class ArrayValidator extends BaseValidator { + private readonly validator; + constructor(validator: BaseValidator, constraints?: readonly IConstraint[]); + lengthLessThan(length: N): ArrayValidator]>>>; + lengthLessThanOrEqual(length: N): ArrayValidator]>>; + lengthGreaterThan(length: N): ArrayValidator<[...Tuple, I, ...T]>; + lengthGreaterThanOrEqual(length: N): ArrayValidator<[...Tuple, ...T]>; + lengthEqual(length: N): ArrayValidator<[...Tuple]>; + lengthNotEqual(length: number): ArrayValidator<[...T]>; + lengthRange(start: S, endBefore: E): ArrayValidator]>>, ExpandSmallerTuples]>>>>; + lengthRangeInclusive(startAt: S, endAt: E): ArrayValidator]>, ExpandSmallerTuples]>>>>; + lengthRangeExclusive(startAfter: S, endBefore: E): ArrayValidator]>>, ExpandSmallerTuples<[...Tuple]>>>; + get unique(): this; + protected clone(): this; + protected handle(values: unknown): Result; +} + +declare abstract class BaseValidator { + protected parent?: object; + protected constraints: readonly IConstraint[]; + protected isValidationEnabled: boolean | (() => boolean) | null; + constructor(constraints?: readonly IConstraint[]); + setParent(parent: object): this; + get optional(): UnionValidator; + get nullable(): UnionValidator; + get nullish(): UnionValidator; + get array(): ArrayValidator; + get set(): SetValidator; + or(...predicates: readonly BaseValidator[]): UnionValidator; + transform(cb: (value: T) => T): this; + transform(cb: (value: T) => O): BaseValidator; + reshape(cb: (input: T) => Result): this; + reshape, O = InferResultType>(cb: (input: T) => R): BaseValidator; + default(value: Exclude | (() => Exclude)): DefaultValidator>; + when = this>(key: Key, options: WhenOptions): this; + run(value: unknown): Result; + parse(value: unknown): R; + is(value: unknown): value is R; + /** + * Sets if the validator should also run constraints or just do basic checks. + * @param isValidationEnabled Whether this validator should be enabled or disabled. You can pass boolean or a function returning boolean which will be called just before parsing. + * Set to `null` to go off of the global configuration. + */ + setValidationEnabled(isValidationEnabled: boolean | (() => boolean) | null): this; + getValidationEnabled(): boolean | null; + protected get shouldRunConstraints(): boolean; + protected clone(): this; + protected abstract handle(value: unknown): Result; + protected addConstraint(constraint: IConstraint): this; +} +type ValidatorError = ValidationError | CombinedError | CombinedPropertyError | UnknownEnumValueError; + +type Constructor = (new (...args: readonly any[]) => T) | (abstract new (...args: readonly any[]) => T); +type Type = V extends BaseValidator ? T : never; +/** + * @deprecated Use `object` instead. + */ +type NonNullObject = {} & object; +/** + * @deprecated This type is no longer used and will be removed in the next major version. + */ +type PickDefined = { + [K in keyof T as undefined extends T[K] ? never : K]: T[K]; +}; +/** + * @deprecated This type is no longer used and will be removed in the next major version. + */ +type PickUndefinedMakeOptional = { + [K in keyof T as undefined extends T[K] ? K : never]+?: Exclude; +}; +type FilterDefinedKeys = Exclude<{ + [TKey in keyof TObj]: undefined extends TObj[TKey] ? never : TKey; +}[keyof TObj], undefined>; +type UndefinedToOptional = Pick> & { + [k in keyof Omit>]?: Exclude; +}; +type MappedObjectValidator = { + [key in keyof T]: BaseValidator; +}; +/** + * An alias of {@link ObjectValidator} with a name more common among object validation libraries. + * This is the type of a schema after using `s.object({ ... })` + * @example + * ```typescript + * import { s, SchemaOf } from '@sapphire/shapeshift'; + * + * interface IIngredient { + * ingredientId: string | undefined; + * name: string | undefined; + * } + * + * interface IInstruction { + * instructionId: string | undefined; + * message: string | undefined; + * } + * + * interface IRecipe { + * recipeId: string | undefined; + * title: string; + * description: string; + * instructions: IInstruction[]; + * ingredients: IIngredient[]; + * } + * + * type InstructionSchemaType = SchemaOf; + * // Expected Type: ObjectValidator + * + * type IngredientSchemaType = SchemaOf; + * // Expected Type: ObjectValidator + * + * type RecipeSchemaType = SchemaOf; + * // Expected Type: ObjectValidator + * + * const instructionSchema: InstructionSchemaType = s.object({ + * instructionId: s.string.optional, + * message: s.string + * }); + * + * const ingredientSchema: IngredientSchemaType = s.object({ + * ingredientId: s.string.optional, + * name: s.string + * }); + * + * const recipeSchema: RecipeSchemaType = s.object({ + * recipeId: s.string.optional, + * title: s.string, + * description: s.string, + * instructions: s.array(instructionSchema), + * ingredients: s.array(ingredientSchema) + * }); + * ``` + */ +type SchemaOf = ObjectValidator; +/** + * Infers the type of a schema object given `typeof schema`. + * The schema has to extend {@link ObjectValidator}. + * @example + * ```typescript + * import { InferType, s } from '@sapphire/shapeshift'; + * + * const schema = s.object({ + * foo: s.string, + * bar: s.number, + * baz: s.boolean, + * qux: s.bigint, + * quux: s.date + * }); + * + * type Inferredtype = InferType; + * // Expected type: + * // type Inferredtype = { + * // foo: string; + * // bar: number; + * // baz: boolean; + * // qux: bigint; + * // quux: Date; + * // }; + * ``` + */ +type InferType> = T extends ObjectValidator ? U : never; +type InferResultType> = T extends Result ? U : never; +type UnwrapTuple = T extends [infer Head, ...infer Tail] ? [Unwrap, ...UnwrapTuple] : []; +type Unwrap = T extends BaseValidator ? V : never; +type UnshiftTuple = T extends [T[0], ...infer Tail] ? Tail : never; +type ExpandSmallerTuples = T extends [T[0], ...infer Tail] ? T | ExpandSmallerTuples : []; +type Shift> = ((...args: A) => void) extends (...args: [A[0], ...infer R]) => void ? R : never; +type GrowExpRev, N extends number, P extends Array>> = A['length'] extends N ? A : GrowExpRev<[...A, ...P[0]][N] extends undefined ? [...A, ...P[0]] : A, N, Shift

>; +type GrowExp, N extends number, P extends Array>> = [...A, ...A][N] extends undefined ? GrowExp<[...A, ...A], N, [A, ...P]> : GrowExpRev; +type Tuple = number extends N ? Array : N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T], N, [[]]>; + +declare class LazyValidator, R = Unwrap> extends BaseValidator { + private readonly validator; + constructor(validator: (value: unknown) => T, constraints?: readonly IConstraint[]); + protected clone(): this; + protected handle(values: unknown): Result; +} + +declare class Shapes { + get string(): StringValidator; + get number(): NumberValidator; + get bigint(): BigIntValidator; + get boolean(): BooleanValidator; + get date(): DateValidator; + object(shape: MappedObjectValidator): ObjectValidator>; + get undefined(): BaseValidator; + get null(): BaseValidator; + get nullish(): NullishValidator; + get any(): PassthroughValidator; + get unknown(): PassthroughValidator; + get never(): NeverValidator; + enum(...values: readonly T[]): UnionValidator; + nativeEnum(enumShape: T): NativeEnumValidator; + literal(value: T): BaseValidator; + instance(expected: Constructor): InstanceValidator; + union[]]>(...validators: [...T]): UnionValidator>; + array(validator: BaseValidator): ArrayValidator; + array(validator: BaseValidator): ArrayValidator; + typedArray(type?: TypedArrayName): TypedArrayValidator; + get int8Array(): TypedArrayValidator; + get uint8Array(): TypedArrayValidator; + get uint8ClampedArray(): TypedArrayValidator; + get int16Array(): TypedArrayValidator; + get uint16Array(): TypedArrayValidator; + get int32Array(): TypedArrayValidator; + get uint32Array(): TypedArrayValidator; + get float32Array(): TypedArrayValidator; + get float64Array(): TypedArrayValidator; + get bigInt64Array(): TypedArrayValidator; + get bigUint64Array(): TypedArrayValidator; + tuple[]]>(validators: [...T]): TupleValidator>; + set(validator: BaseValidator): SetValidator; + record(validator: BaseValidator): RecordValidator; + map(keyValidator: BaseValidator, valueValidator: BaseValidator): MapValidator; + lazy>(validator: (value: unknown) => T): LazyValidator>; +} + +/** + * Sets whether validators should run on the input, or if the input should be passed through. + * @param enabled Whether validation should be done on inputs + */ +declare function setGlobalValidationEnabled(enabled: boolean): void; +/** + * @returns Whether validation is enabled + */ +declare function getGlobalValidationEnabled(): boolean; + +declare const s: Shapes; + +export { ArrayConstraintName, ArrayValidator, BaseConstraintError, BaseError, BaseValidator, BigIntConstraintName, BigIntValidator, BooleanConstraintName, BooleanValidator, CombinedError, CombinedPropertyError, ConstraintErrorNames, Constructor, DateConstraintName, DateValidator, DefaultValidator, ExpandSmallerTuples, ExpectedConstraintError, ExpectedValidationError, GrowExp, GrowExpRev, IConstraint, InferResultType, InferType, InstanceValidator, LiteralValidator, MapValidator, MappedObjectValidator, MissingPropertyError, MultiplePossibilitiesConstraintError, NativeEnumLike, NativeEnumValidator, NeverValidator, NonNullObject, NullishValidator, NumberConstraintName, NumberValidator, ObjectValidator, ObjectValidatorStrategy, PassthroughValidator, PickDefined, PickUndefinedMakeOptional, RecordValidator, Result, SchemaOf, SetValidator, Shapes, Shift, StringConstraintName, StringDomain, StringProtocol, StringUuidOptions, StringValidator, Tuple, TupleValidator, Type, TypedArrayConstraintName, TypedArrayValidator, UUIDVersion, UndefinedToOptional, UnionValidator, UnknownEnumValueError, UnknownPropertyError, UnshiftTuple, Unwrap, UnwrapTuple, UrlOptions, ValidationError, ValidatorError, arrayLengthEqual, arrayLengthGreaterThan, arrayLengthGreaterThanOrEqual, arrayLengthLessThan, arrayLengthLessThanOrEqual, arrayLengthNotEqual, arrayLengthRange, arrayLengthRangeExclusive, arrayLengthRangeInclusive, bigintDivisibleBy, bigintEqual, bigintGreaterThan, bigintGreaterThanOrEqual, bigintLessThan, bigintLessThanOrEqual, bigintNotEqual, booleanFalse, booleanTrue, customInspectSymbol, customInspectSymbolStackLess, dateEqual, dateGreaterThan, dateGreaterThanOrEqual, dateInvalid, dateLessThan, dateLessThanOrEqual, dateNotEqual, dateValid, getGlobalValidationEnabled, numberDivisibleBy, numberEqual, numberFinite, numberGreaterThan, numberGreaterThanOrEqual, numberInt, numberLessThan, numberLessThanOrEqual, numberNaN, numberNotEqual, numberNotNaN, numberSafeInt, s, setGlobalValidationEnabled, stringEmail, stringIp, stringLengthEqual, stringLengthGreaterThan, stringLengthGreaterThanOrEqual, stringLengthLessThan, stringLengthLessThanOrEqual, stringLengthNotEqual, stringRegex, stringUrl, stringUuid, typedArrayByteLengthEqual, typedArrayByteLengthGreaterThan, typedArrayByteLengthGreaterThanOrEqual, typedArrayByteLengthLessThan, typedArrayByteLengthLessThanOrEqual, typedArrayByteLengthNotEqual, typedArrayByteLengthRange, typedArrayByteLengthRangeExclusive, typedArrayByteLengthRangeInclusive, typedArrayLengthEqual, typedArrayLengthGreaterThan, typedArrayLengthGreaterThanOrEqual, typedArrayLengthLessThan, typedArrayLengthLessThanOrEqual, typedArrayLengthNotEqual, typedArrayLengthRange, typedArrayLengthRangeExclusive, typedArrayLengthRangeInclusive }; diff --git a/node_modules/@sapphire/shapeshift/dist/index.global.js b/node_modules/@sapphire/shapeshift/dist/index.global.js new file mode 100644 index 0000000..1ede3cd --- /dev/null +++ b/node_modules/@sapphire/shapeshift/dist/index.global.js @@ -0,0 +1,4166 @@ +var SapphireShapeshift = (function (exports) { + 'use strict'; + + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + 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 __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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + + // node_modules/lodash/isArray.js + var require_isArray = __commonJS({ + "node_modules/lodash/isArray.js"(exports, module) { + var isArray3 = Array.isArray; + module.exports = isArray3; + } + }); + + // node_modules/lodash/_freeGlobal.js + var require_freeGlobal = __commonJS({ + "node_modules/lodash/_freeGlobal.js"(exports, module) { + var freeGlobal = typeof globalThis == "object" && globalThis && globalThis.Object === Object && globalThis; + module.exports = freeGlobal; + } + }); + + // node_modules/lodash/_root.js + var require_root = __commonJS({ + "node_modules/lodash/_root.js"(exports, module) { + var freeGlobal = require_freeGlobal(); + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + module.exports = root; + } + }); + + // node_modules/lodash/_Symbol.js + var require_Symbol = __commonJS({ + "node_modules/lodash/_Symbol.js"(exports, module) { + var root = require_root(); + var Symbol2 = root.Symbol; + module.exports = Symbol2; + } + }); + + // node_modules/lodash/_getRawTag.js + var require_getRawTag = __commonJS({ + "node_modules/lodash/_getRawTag.js"(exports, module) { + var Symbol2 = require_Symbol(); + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + var nativeObjectToString = objectProto.toString; + var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + try { + value[symToStringTag] = void 0; + var unmasked = true; + } catch (e3) { + } + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + __name(getRawTag, "getRawTag"); + module.exports = getRawTag; + } + }); + + // node_modules/lodash/_objectToString.js + var require_objectToString = __commonJS({ + "node_modules/lodash/_objectToString.js"(exports, module) { + var objectProto = Object.prototype; + var nativeObjectToString = objectProto.toString; + function objectToString(value) { + return nativeObjectToString.call(value); + } + __name(objectToString, "objectToString"); + module.exports = objectToString; + } + }); + + // node_modules/lodash/_baseGetTag.js + var require_baseGetTag = __commonJS({ + "node_modules/lodash/_baseGetTag.js"(exports, module) { + var Symbol2 = require_Symbol(); + var getRawTag = require_getRawTag(); + var objectToString = require_objectToString(); + var nullTag = "[object Null]"; + var undefinedTag = "[object Undefined]"; + var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; + function baseGetTag(value) { + if (value == null) { + return value === void 0 ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); + } + __name(baseGetTag, "baseGetTag"); + module.exports = baseGetTag; + } + }); + + // node_modules/lodash/isObjectLike.js + var require_isObjectLike = __commonJS({ + "node_modules/lodash/isObjectLike.js"(exports, module) { + function isObjectLike(value) { + return value != null && typeof value == "object"; + } + __name(isObjectLike, "isObjectLike"); + module.exports = isObjectLike; + } + }); + + // node_modules/lodash/isSymbol.js + var require_isSymbol = __commonJS({ + "node_modules/lodash/isSymbol.js"(exports, module) { + var baseGetTag = require_baseGetTag(); + var isObjectLike = require_isObjectLike(); + var symbolTag = "[object Symbol]"; + function isSymbol3(value) { + return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag; + } + __name(isSymbol3, "isSymbol"); + module.exports = isSymbol3; + } + }); + + // node_modules/lodash/_isKey.js + var require_isKey = __commonJS({ + "node_modules/lodash/_isKey.js"(exports, module) { + var isArray3 = require_isArray(); + var isSymbol3 = require_isSymbol(); + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + var reIsPlainProp = /^\w*$/; + function isKey(value, object) { + if (isArray3(value)) { + return false; + } + var type = typeof value; + if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol3(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); + } + __name(isKey, "isKey"); + module.exports = isKey; + } + }); + + // node_modules/lodash/isObject.js + var require_isObject = __commonJS({ + "node_modules/lodash/isObject.js"(exports, module) { + function isObject3(value) { + var type = typeof value; + return value != null && (type == "object" || type == "function"); + } + __name(isObject3, "isObject"); + module.exports = isObject3; + } + }); + + // node_modules/lodash/isFunction.js + var require_isFunction = __commonJS({ + "node_modules/lodash/isFunction.js"(exports, module) { + var baseGetTag = require_baseGetTag(); + var isObject3 = require_isObject(); + var asyncTag = "[object AsyncFunction]"; + var funcTag = "[object Function]"; + var genTag = "[object GeneratorFunction]"; + var proxyTag = "[object Proxy]"; + function isFunction3(value) { + if (!isObject3(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + __name(isFunction3, "isFunction"); + module.exports = isFunction3; + } + }); + + // node_modules/lodash/_coreJsData.js + var require_coreJsData = __commonJS({ + "node_modules/lodash/_coreJsData.js"(exports, module) { + var root = require_root(); + var coreJsData = root["__core-js_shared__"]; + module.exports = coreJsData; + } + }); + + // node_modules/lodash/_isMasked.js + var require_isMasked = __commonJS({ + "node_modules/lodash/_isMasked.js"(exports, module) { + var coreJsData = require_coreJsData(); + var maskSrcKey = function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); + return uid ? "Symbol(src)_1." + uid : ""; + }(); + function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func; + } + __name(isMasked, "isMasked"); + module.exports = isMasked; + } + }); + + // node_modules/lodash/_toSource.js + var require_toSource = __commonJS({ + "node_modules/lodash/_toSource.js"(exports, module) { + var funcProto = Function.prototype; + var funcToString = funcProto.toString; + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e3) { + } + try { + return func + ""; + } catch (e3) { + } + } + return ""; + } + __name(toSource, "toSource"); + module.exports = toSource; + } + }); + + // node_modules/lodash/_baseIsNative.js + var require_baseIsNative = __commonJS({ + "node_modules/lodash/_baseIsNative.js"(exports, module) { + var isFunction3 = require_isFunction(); + var isMasked = require_isMasked(); + var isObject3 = require_isObject(); + var toSource = require_toSource(); + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + var reIsHostCtor = /^\[object .+?Constructor\]$/; + var funcProto = Function.prototype; + var objectProto = Object.prototype; + var funcToString = funcProto.toString; + var hasOwnProperty = objectProto.hasOwnProperty; + var reIsNative = RegExp( + "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" + ); + function baseIsNative(value) { + if (!isObject3(value) || isMasked(value)) { + return false; + } + var pattern = isFunction3(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + __name(baseIsNative, "baseIsNative"); + module.exports = baseIsNative; + } + }); + + // node_modules/lodash/_getValue.js + var require_getValue = __commonJS({ + "node_modules/lodash/_getValue.js"(exports, module) { + function getValue2(object, key) { + return object == null ? void 0 : object[key]; + } + __name(getValue2, "getValue"); + module.exports = getValue2; + } + }); + + // node_modules/lodash/_getNative.js + var require_getNative = __commonJS({ + "node_modules/lodash/_getNative.js"(exports, module) { + var baseIsNative = require_baseIsNative(); + var getValue2 = require_getValue(); + function getNative(object, key) { + var value = getValue2(object, key); + return baseIsNative(value) ? value : void 0; + } + __name(getNative, "getNative"); + module.exports = getNative; + } + }); + + // node_modules/lodash/_nativeCreate.js + var require_nativeCreate = __commonJS({ + "node_modules/lodash/_nativeCreate.js"(exports, module) { + var getNative = require_getNative(); + var nativeCreate = getNative(Object, "create"); + module.exports = nativeCreate; + } + }); + + // node_modules/lodash/_hashClear.js + var require_hashClear = __commonJS({ + "node_modules/lodash/_hashClear.js"(exports, module) { + var nativeCreate = require_nativeCreate(); + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + __name(hashClear, "hashClear"); + module.exports = hashClear; + } + }); + + // node_modules/lodash/_hashDelete.js + var require_hashDelete = __commonJS({ + "node_modules/lodash/_hashDelete.js"(exports, module) { + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + __name(hashDelete, "hashDelete"); + module.exports = hashDelete; + } + }); + + // node_modules/lodash/_hashGet.js + var require_hashGet = __commonJS({ + "node_modules/lodash/_hashGet.js"(exports, module) { + var nativeCreate = require_nativeCreate(); + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? void 0 : result; + } + return hasOwnProperty.call(data, key) ? data[key] : void 0; + } + __name(hashGet, "hashGet"); + module.exports = hashGet; + } + }); + + // node_modules/lodash/_hashHas.js + var require_hashHas = __commonJS({ + "node_modules/lodash/_hashHas.js"(exports, module) { + var nativeCreate = require_nativeCreate(); + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key); + } + __name(hashHas, "hashHas"); + module.exports = hashHas; + } + }); + + // node_modules/lodash/_hashSet.js + var require_hashSet = __commonJS({ + "node_modules/lodash/_hashSet.js"(exports, module) { + var nativeCreate = require_nativeCreate(); + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; + return this; + } + __name(hashSet, "hashSet"); + module.exports = hashSet; + } + }); + + // node_modules/lodash/_Hash.js + var require_Hash = __commonJS({ + "node_modules/lodash/_Hash.js"(exports, module) { + var hashClear = require_hashClear(); + var hashDelete = require_hashDelete(); + var hashGet = require_hashGet(); + var hashHas = require_hashHas(); + var hashSet = require_hashSet(); + function Hash(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + __name(Hash, "Hash"); + Hash.prototype.clear = hashClear; + Hash.prototype["delete"] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + module.exports = Hash; + } + }); + + // node_modules/lodash/_listCacheClear.js + var require_listCacheClear = __commonJS({ + "node_modules/lodash/_listCacheClear.js"(exports, module) { + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + __name(listCacheClear, "listCacheClear"); + module.exports = listCacheClear; + } + }); + + // node_modules/lodash/eq.js + var require_eq = __commonJS({ + "node_modules/lodash/eq.js"(exports, module) { + function eq(value, other) { + return value === other || value !== value && other !== other; + } + __name(eq, "eq"); + module.exports = eq; + } + }); + + // node_modules/lodash/_assocIndexOf.js + var require_assocIndexOf = __commonJS({ + "node_modules/lodash/_assocIndexOf.js"(exports, module) { + var eq = require_eq(); + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + __name(assocIndexOf, "assocIndexOf"); + module.exports = assocIndexOf; + } + }); + + // node_modules/lodash/_listCacheDelete.js + var require_listCacheDelete = __commonJS({ + "node_modules/lodash/_listCacheDelete.js"(exports, module) { + var assocIndexOf = require_assocIndexOf(); + var arrayProto = Array.prototype; + var splice = arrayProto.splice; + function listCacheDelete(key) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + __name(listCacheDelete, "listCacheDelete"); + module.exports = listCacheDelete; + } + }); + + // node_modules/lodash/_listCacheGet.js + var require_listCacheGet = __commonJS({ + "node_modules/lodash/_listCacheGet.js"(exports, module) { + var assocIndexOf = require_assocIndexOf(); + function listCacheGet(key) { + var data = this.__data__, index = assocIndexOf(data, key); + return index < 0 ? void 0 : data[index][1]; + } + __name(listCacheGet, "listCacheGet"); + module.exports = listCacheGet; + } + }); + + // node_modules/lodash/_listCacheHas.js + var require_listCacheHas = __commonJS({ + "node_modules/lodash/_listCacheHas.js"(exports, module) { + var assocIndexOf = require_assocIndexOf(); + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + __name(listCacheHas, "listCacheHas"); + module.exports = listCacheHas; + } + }); + + // node_modules/lodash/_listCacheSet.js + var require_listCacheSet = __commonJS({ + "node_modules/lodash/_listCacheSet.js"(exports, module) { + var assocIndexOf = require_assocIndexOf(); + function listCacheSet(key, value) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + __name(listCacheSet, "listCacheSet"); + module.exports = listCacheSet; + } + }); + + // node_modules/lodash/_ListCache.js + var require_ListCache = __commonJS({ + "node_modules/lodash/_ListCache.js"(exports, module) { + var listCacheClear = require_listCacheClear(); + var listCacheDelete = require_listCacheDelete(); + var listCacheGet = require_listCacheGet(); + var listCacheHas = require_listCacheHas(); + var listCacheSet = require_listCacheSet(); + function ListCache(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + __name(ListCache, "ListCache"); + ListCache.prototype.clear = listCacheClear; + ListCache.prototype["delete"] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + module.exports = ListCache; + } + }); + + // node_modules/lodash/_Map.js + var require_Map = __commonJS({ + "node_modules/lodash/_Map.js"(exports, module) { + var getNative = require_getNative(); + var root = require_root(); + var Map2 = getNative(root, "Map"); + module.exports = Map2; + } + }); + + // node_modules/lodash/_mapCacheClear.js + var require_mapCacheClear = __commonJS({ + "node_modules/lodash/_mapCacheClear.js"(exports, module) { + var Hash = require_Hash(); + var ListCache = require_ListCache(); + var Map2 = require_Map(); + function mapCacheClear() { + this.size = 0; + this.__data__ = { + "hash": new Hash(), + "map": new (Map2 || ListCache)(), + "string": new Hash() + }; + } + __name(mapCacheClear, "mapCacheClear"); + module.exports = mapCacheClear; + } + }); + + // node_modules/lodash/_isKeyable.js + var require_isKeyable = __commonJS({ + "node_modules/lodash/_isKeyable.js"(exports, module) { + function isKeyable(value) { + var type = typeof value; + return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; + } + __name(isKeyable, "isKeyable"); + module.exports = isKeyable; + } + }); + + // node_modules/lodash/_getMapData.js + var require_getMapData = __commonJS({ + "node_modules/lodash/_getMapData.js"(exports, module) { + var isKeyable = require_isKeyable(); + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; + } + __name(getMapData, "getMapData"); + module.exports = getMapData; + } + }); + + // node_modules/lodash/_mapCacheDelete.js + var require_mapCacheDelete = __commonJS({ + "node_modules/lodash/_mapCacheDelete.js"(exports, module) { + var getMapData = require_getMapData(); + function mapCacheDelete(key) { + var result = getMapData(this, key)["delete"](key); + this.size -= result ? 1 : 0; + return result; + } + __name(mapCacheDelete, "mapCacheDelete"); + module.exports = mapCacheDelete; + } + }); + + // node_modules/lodash/_mapCacheGet.js + var require_mapCacheGet = __commonJS({ + "node_modules/lodash/_mapCacheGet.js"(exports, module) { + var getMapData = require_getMapData(); + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + __name(mapCacheGet, "mapCacheGet"); + module.exports = mapCacheGet; + } + }); + + // node_modules/lodash/_mapCacheHas.js + var require_mapCacheHas = __commonJS({ + "node_modules/lodash/_mapCacheHas.js"(exports, module) { + var getMapData = require_getMapData(); + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + __name(mapCacheHas, "mapCacheHas"); + module.exports = mapCacheHas; + } + }); + + // node_modules/lodash/_mapCacheSet.js + var require_mapCacheSet = __commonJS({ + "node_modules/lodash/_mapCacheSet.js"(exports, module) { + var getMapData = require_getMapData(); + function mapCacheSet(key, value) { + var data = getMapData(this, key), size = data.size; + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + __name(mapCacheSet, "mapCacheSet"); + module.exports = mapCacheSet; + } + }); + + // node_modules/lodash/_MapCache.js + var require_MapCache = __commonJS({ + "node_modules/lodash/_MapCache.js"(exports, module) { + var mapCacheClear = require_mapCacheClear(); + var mapCacheDelete = require_mapCacheDelete(); + var mapCacheGet = require_mapCacheGet(); + var mapCacheHas = require_mapCacheHas(); + var mapCacheSet = require_mapCacheSet(); + function MapCache(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + __name(MapCache, "MapCache"); + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype["delete"] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + module.exports = MapCache; + } + }); + + // node_modules/lodash/memoize.js + var require_memoize = __commonJS({ + "node_modules/lodash/memoize.js"(exports, module) { + var MapCache = require_MapCache(); + var FUNC_ERROR_TEXT = "Expected a function"; + function memoize(func, resolver) { + if (typeof func != "function" || resolver != null && typeof resolver != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = /* @__PURE__ */ __name(function() { + var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }, "memoized"); + memoized.cache = new (memoize.Cache || MapCache)(); + return memoized; + } + __name(memoize, "memoize"); + memoize.Cache = MapCache; + module.exports = memoize; + } + }); + + // node_modules/lodash/_memoizeCapped.js + var require_memoizeCapped = __commonJS({ + "node_modules/lodash/_memoizeCapped.js"(exports, module) { + var memoize = require_memoize(); + var MAX_MEMOIZE_SIZE = 500; + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + var cache = result.cache; + return result; + } + __name(memoizeCapped, "memoizeCapped"); + module.exports = memoizeCapped; + } + }); + + // node_modules/lodash/_stringToPath.js + var require_stringToPath = __commonJS({ + "node_modules/lodash/_stringToPath.js"(exports, module) { + var memoizeCapped = require_memoizeCapped(); + var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + var reEscapeChar = /\\(\\)?/g; + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46) { + result.push(""); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match); + }); + return result; + }); + module.exports = stringToPath; + } + }); + + // node_modules/lodash/_arrayMap.js + var require_arrayMap = __commonJS({ + "node_modules/lodash/_arrayMap.js"(exports, module) { + function arrayMap(array, iteratee) { + var index = -1, length = array == null ? 0 : array.length, result = Array(length); + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + __name(arrayMap, "arrayMap"); + module.exports = arrayMap; + } + }); + + // node_modules/lodash/_baseToString.js + var require_baseToString = __commonJS({ + "node_modules/lodash/_baseToString.js"(exports, module) { + var Symbol2 = require_Symbol(); + var arrayMap = require_arrayMap(); + var isArray3 = require_isArray(); + var isSymbol3 = require_isSymbol(); + var INFINITY = 1 / 0; + var symbolProto = Symbol2 ? Symbol2.prototype : void 0; + var symbolToString = symbolProto ? symbolProto.toString : void 0; + function baseToString(value) { + if (typeof value == "string") { + return value; + } + if (isArray3(value)) { + return arrayMap(value, baseToString) + ""; + } + if (isSymbol3(value)) { + return symbolToString ? symbolToString.call(value) : ""; + } + var result = value + ""; + return result == "0" && 1 / value == -INFINITY ? "-0" : result; + } + __name(baseToString, "baseToString"); + module.exports = baseToString; + } + }); + + // node_modules/lodash/toString.js + var require_toString = __commonJS({ + "node_modules/lodash/toString.js"(exports, module) { + var baseToString = require_baseToString(); + function toString(value) { + return value == null ? "" : baseToString(value); + } + __name(toString, "toString"); + module.exports = toString; + } + }); + + // node_modules/lodash/_castPath.js + var require_castPath = __commonJS({ + "node_modules/lodash/_castPath.js"(exports, module) { + var isArray3 = require_isArray(); + var isKey = require_isKey(); + var stringToPath = require_stringToPath(); + var toString = require_toString(); + function castPath(value, object) { + if (isArray3(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + __name(castPath, "castPath"); + module.exports = castPath; + } + }); + + // node_modules/lodash/_toKey.js + var require_toKey = __commonJS({ + "node_modules/lodash/_toKey.js"(exports, module) { + var isSymbol3 = require_isSymbol(); + var INFINITY = 1 / 0; + function toKey(value) { + if (typeof value == "string" || isSymbol3(value)) { + return value; + } + var result = value + ""; + return result == "0" && 1 / value == -INFINITY ? "-0" : result; + } + __name(toKey, "toKey"); + module.exports = toKey; + } + }); + + // node_modules/lodash/_baseGet.js + var require_baseGet = __commonJS({ + "node_modules/lodash/_baseGet.js"(exports, module) { + var castPath = require_castPath(); + var toKey = require_toKey(); + function baseGet(object, path) { + path = castPath(path, object); + var index = 0, length = path.length; + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return index && index == length ? object : void 0; + } + __name(baseGet, "baseGet"); + module.exports = baseGet; + } + }); + + // node_modules/lodash/get.js + var require_get = __commonJS({ + "node_modules/lodash/get.js"(exports, module) { + var baseGet = require_baseGet(); + function get2(object, path, defaultValue) { + var result = object == null ? void 0 : baseGet(object, path); + return result === void 0 ? defaultValue : result; + } + __name(get2, "get"); + module.exports = get2; + } + }); + + // node_modules/fast-deep-equal/es6/index.js + var require_es6 = __commonJS({ + "node_modules/fast-deep-equal/es6/index.js"(exports, module) { + module.exports = /* @__PURE__ */ __name(function equal2(a3, b2) { + if (a3 === b2) + return true; + if (a3 && b2 && typeof a3 == "object" && typeof b2 == "object") { + if (a3.constructor !== b2.constructor) + return false; + var length, i3, keys; + if (Array.isArray(a3)) { + length = a3.length; + if (length != b2.length) + return false; + for (i3 = length; i3-- !== 0; ) + if (!equal2(a3[i3], b2[i3])) + return false; + return true; + } + if (a3 instanceof Map && b2 instanceof Map) { + if (a3.size !== b2.size) + return false; + for (i3 of a3.entries()) + if (!b2.has(i3[0])) + return false; + for (i3 of a3.entries()) + if (!equal2(i3[1], b2.get(i3[0]))) + return false; + return true; + } + if (a3 instanceof Set && b2 instanceof Set) { + if (a3.size !== b2.size) + return false; + for (i3 of a3.entries()) + if (!b2.has(i3[0])) + return false; + return true; + } + if (ArrayBuffer.isView(a3) && ArrayBuffer.isView(b2)) { + length = a3.length; + if (length != b2.length) + return false; + for (i3 = length; i3-- !== 0; ) + if (a3[i3] !== b2[i3]) + return false; + return true; + } + if (a3.constructor === RegExp) + return a3.source === b2.source && a3.flags === b2.flags; + if (a3.valueOf !== Object.prototype.valueOf) + return a3.valueOf() === b2.valueOf(); + if (a3.toString !== Object.prototype.toString) + return a3.toString() === b2.toString(); + keys = Object.keys(a3); + length = keys.length; + if (length !== Object.keys(b2).length) + return false; + for (i3 = length; i3-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b2, keys[i3])) + return false; + for (i3 = length; i3-- !== 0; ) { + var key = keys[i3]; + if (!equal2(a3[key], b2[key])) + return false; + } + return true; + } + return a3 !== a3 && b2 !== b2; + }, "equal"); + } + }); + + // node_modules/lodash/_setCacheAdd.js + var require_setCacheAdd = __commonJS({ + "node_modules/lodash/_setCacheAdd.js"(exports, module) { + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + __name(setCacheAdd, "setCacheAdd"); + module.exports = setCacheAdd; + } + }); + + // node_modules/lodash/_setCacheHas.js + var require_setCacheHas = __commonJS({ + "node_modules/lodash/_setCacheHas.js"(exports, module) { + function setCacheHas(value) { + return this.__data__.has(value); + } + __name(setCacheHas, "setCacheHas"); + module.exports = setCacheHas; + } + }); + + // node_modules/lodash/_SetCache.js + var require_SetCache = __commonJS({ + "node_modules/lodash/_SetCache.js"(exports, module) { + var MapCache = require_MapCache(); + var setCacheAdd = require_setCacheAdd(); + var setCacheHas = require_setCacheHas(); + function SetCache(values) { + var index = -1, length = values == null ? 0 : values.length; + this.__data__ = new MapCache(); + while (++index < length) { + this.add(values[index]); + } + } + __name(SetCache, "SetCache"); + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + module.exports = SetCache; + } + }); + + // node_modules/lodash/_baseFindIndex.js + var require_baseFindIndex = __commonJS({ + "node_modules/lodash/_baseFindIndex.js"(exports, module) { + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + __name(baseFindIndex, "baseFindIndex"); + module.exports = baseFindIndex; + } + }); + + // node_modules/lodash/_baseIsNaN.js + var require_baseIsNaN = __commonJS({ + "node_modules/lodash/_baseIsNaN.js"(exports, module) { + function baseIsNaN(value) { + return value !== value; + } + __name(baseIsNaN, "baseIsNaN"); + module.exports = baseIsNaN; + } + }); + + // node_modules/lodash/_strictIndexOf.js + var require_strictIndexOf = __commonJS({ + "node_modules/lodash/_strictIndexOf.js"(exports, module) { + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + __name(strictIndexOf, "strictIndexOf"); + module.exports = strictIndexOf; + } + }); + + // node_modules/lodash/_baseIndexOf.js + var require_baseIndexOf = __commonJS({ + "node_modules/lodash/_baseIndexOf.js"(exports, module) { + var baseFindIndex = require_baseFindIndex(); + var baseIsNaN = require_baseIsNaN(); + var strictIndexOf = require_strictIndexOf(); + function baseIndexOf(array, value, fromIndex) { + return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); + } + __name(baseIndexOf, "baseIndexOf"); + module.exports = baseIndexOf; + } + }); + + // node_modules/lodash/_arrayIncludes.js + var require_arrayIncludes = __commonJS({ + "node_modules/lodash/_arrayIncludes.js"(exports, module) { + var baseIndexOf = require_baseIndexOf(); + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + __name(arrayIncludes, "arrayIncludes"); + module.exports = arrayIncludes; + } + }); + + // node_modules/lodash/_arrayIncludesWith.js + var require_arrayIncludesWith = __commonJS({ + "node_modules/lodash/_arrayIncludesWith.js"(exports, module) { + function arrayIncludesWith(array, value, comparator) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + __name(arrayIncludesWith, "arrayIncludesWith"); + module.exports = arrayIncludesWith; + } + }); + + // node_modules/lodash/_cacheHas.js + var require_cacheHas = __commonJS({ + "node_modules/lodash/_cacheHas.js"(exports, module) { + function cacheHas(cache, key) { + return cache.has(key); + } + __name(cacheHas, "cacheHas"); + module.exports = cacheHas; + } + }); + + // node_modules/lodash/_Set.js + var require_Set = __commonJS({ + "node_modules/lodash/_Set.js"(exports, module) { + var getNative = require_getNative(); + var root = require_root(); + var Set2 = getNative(root, "Set"); + module.exports = Set2; + } + }); + + // node_modules/lodash/noop.js + var require_noop = __commonJS({ + "node_modules/lodash/noop.js"(exports, module) { + function noop() { + } + __name(noop, "noop"); + module.exports = noop; + } + }); + + // node_modules/lodash/_setToArray.js + var require_setToArray = __commonJS({ + "node_modules/lodash/_setToArray.js"(exports, module) { + function setToArray(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + __name(setToArray, "setToArray"); + module.exports = setToArray; + } + }); + + // node_modules/lodash/_createSet.js + var require_createSet = __commonJS({ + "node_modules/lodash/_createSet.js"(exports, module) { + var Set2 = require_Set(); + var noop = require_noop(); + var setToArray = require_setToArray(); + var INFINITY = 1 / 0; + var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop : function(values) { + return new Set2(values); + }; + module.exports = createSet; + } + }); + + // node_modules/lodash/_baseUniq.js + var require_baseUniq = __commonJS({ + "node_modules/lodash/_baseUniq.js"(exports, module) { + var SetCache = require_SetCache(); + var arrayIncludes = require_arrayIncludes(); + var arrayIncludesWith = require_arrayIncludesWith(); + var cacheHas = require_cacheHas(); + var createSet = require_createSet(); + var setToArray = require_setToArray(); + var LARGE_ARRAY_SIZE = 200; + function baseUniq(array, iteratee, comparator) { + var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache(); + } else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], computed = iteratee ? iteratee(value) : value; + value = comparator || value !== 0 ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + __name(baseUniq, "baseUniq"); + module.exports = baseUniq; + } + }); + + // node_modules/lodash/uniqWith.js + var require_uniqWith = __commonJS({ + "node_modules/lodash/uniqWith.js"(exports, module) { + var baseUniq = require_baseUniq(); + function uniqWith2(array, comparator) { + comparator = typeof comparator == "function" ? comparator : void 0; + return array && array.length ? baseUniq(array, void 0, comparator) : []; + } + __name(uniqWith2, "uniqWith"); + module.exports = uniqWith2; + } + }); + + // src/lib/configs.ts + var validationEnabled = true; + function setGlobalValidationEnabled(enabled) { + validationEnabled = enabled; + } + __name(setGlobalValidationEnabled, "setGlobalValidationEnabled"); + function getGlobalValidationEnabled() { + return validationEnabled; + } + __name(getGlobalValidationEnabled, "getGlobalValidationEnabled"); + + // src/lib/Result.ts + var Result = class { + constructor(success, value, error) { + this.success = success; + if (success) { + this.value = value; + } else { + this.error = error; + } + } + isOk() { + return this.success; + } + isErr() { + return !this.success; + } + unwrap() { + if (this.isOk()) + return this.value; + throw this.error; + } + static ok(value) { + return new Result(true, value); + } + static err(error) { + return new Result(false, void 0, error); + } + }; + __name(Result, "Result"); + + // src/validators/util/getValue.ts + function getValue(valueOrFn) { + return typeof valueOrFn === "function" ? valueOrFn() : valueOrFn; + } + __name(getValue, "getValue"); + + // src/constraints/ObjectConstrains.ts + var import_get = __toESM(require_get()); + + // node-modules-polyfills:node:util + var e; + var t; + var n; + var r = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : globalThis; + var o = e = {}; + function i() { + throw new Error("setTimeout has not been defined"); + } + __name(i, "i"); + function u() { + throw new Error("clearTimeout has not been defined"); + } + __name(u, "u"); + function c(e3) { + if (t === setTimeout) + return setTimeout(e3, 0); + if ((t === i || !t) && setTimeout) + return t = setTimeout, setTimeout(e3, 0); + try { + return t(e3, 0); + } catch (n3) { + try { + return t.call(null, e3, 0); + } catch (n4) { + return t.call(this || r, e3, 0); + } + } + } + __name(c, "c"); + !function() { + try { + t = "function" == typeof setTimeout ? setTimeout : i; + } catch (e3) { + t = i; + } + try { + n = "function" == typeof clearTimeout ? clearTimeout : u; + } catch (e3) { + n = u; + } + }(); + var l; + var s = []; + var f = false; + var a = -1; + function h() { + f && l && (f = false, l.length ? s = l.concat(s) : a = -1, s.length && d()); + } + __name(h, "h"); + function d() { + if (!f) { + var e3 = c(h); + f = true; + for (var t3 = s.length; t3; ) { + for (l = s, s = []; ++a < t3; ) + l && l[a].run(); + a = -1, t3 = s.length; + } + l = null, f = false, function(e4) { + if (n === clearTimeout) + return clearTimeout(e4); + if ((n === u || !n) && clearTimeout) + return n = clearTimeout, clearTimeout(e4); + try { + n(e4); + } catch (t4) { + try { + return n.call(null, e4); + } catch (t5) { + return n.call(this || r, e4); + } + } + }(e3); + } + } + __name(d, "d"); + function m(e3, t3) { + (this || r).fun = e3, (this || r).array = t3; + } + __name(m, "m"); + function p() { + } + __name(p, "p"); + o.nextTick = function(e3) { + var t3 = new Array(arguments.length - 1); + if (arguments.length > 1) + for (var n3 = 1; n3 < arguments.length; n3++) + t3[n3 - 1] = arguments[n3]; + s.push(new m(e3, t3)), 1 !== s.length || f || c(d); + }, m.prototype.run = function() { + (this || r).fun.apply(null, (this || r).array); + }, o.title = "browser", o.browser = true, o.env = {}, o.argv = [], o.version = "", o.versions = {}, o.on = p, o.addListener = p, o.once = p, o.off = p, o.removeListener = p, o.removeAllListeners = p, o.emit = p, o.prependListener = p, o.prependOnceListener = p, o.listeners = function(e3) { + return []; + }, o.binding = function(e3) { + throw new Error("process.binding is not supported"); + }, o.cwd = function() { + return "/"; + }, o.chdir = function(e3) { + throw new Error("process.chdir is not supported"); + }, o.umask = function() { + return 0; + }; + var T = e; + T.addListener; + T.argv; + T.binding; + T.browser; + T.chdir; + T.cwd; + T.emit; + T.env; + T.listeners; + T.nextTick; + T.off; + T.on; + T.once; + T.prependListener; + T.prependOnceListener; + T.removeAllListeners; + T.removeListener; + T.title; + T.umask; + T.version; + T.versions; + var t2 = "function" == typeof Symbol && "symbol" == typeof Symbol.toStringTag; + var e2 = Object.prototype.toString; + var o2 = /* @__PURE__ */ __name(function(o3) { + return !(t2 && o3 && "object" == typeof o3 && Symbol.toStringTag in o3) && "[object Arguments]" === e2.call(o3); + }, "o2"); + var n2 = /* @__PURE__ */ __name(function(t3) { + return !!o2(t3) || null !== t3 && "object" == typeof t3 && "number" == typeof t3.length && t3.length >= 0 && "[object Array]" !== e2.call(t3) && "[object Function]" === e2.call(t3.callee); + }, "n2"); + var r2 = function() { + return o2(arguments); + }(); + o2.isLegacyArguments = n2; + var l2 = r2 ? o2 : n2; + var t$1 = Object.prototype.toString; + var o$1 = Function.prototype.toString; + var n$1 = /^\s*(?:function)?\*/; + var e$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.toStringTag; + var r$1 = Object.getPrototypeOf; + var c2 = function() { + if (!e$1) + return false; + try { + return Function("return function*() {}")(); + } catch (t3) { + } + }(); + var u2 = c2 ? r$1(c2) : {}; + var i2 = /* @__PURE__ */ __name(function(c3) { + return "function" == typeof c3 && (!!n$1.test(o$1.call(c3)) || (e$1 ? r$1(c3) === u2 : "[object GeneratorFunction]" === t$1.call(c3))); + }, "i2"); + var t$2 = "function" == typeof Object.create ? function(t3, e3) { + e3 && (t3.super_ = e3, t3.prototype = Object.create(e3.prototype, { constructor: { value: t3, enumerable: false, writable: true, configurable: true } })); + } : function(t3, e3) { + if (e3) { + t3.super_ = e3; + var o3 = /* @__PURE__ */ __name(function() { + }, "o3"); + o3.prototype = e3.prototype, t3.prototype = new o3(), t3.prototype.constructor = t3; + } + }; + var i$1 = /* @__PURE__ */ __name(function(e3) { + return e3 && "object" == typeof e3 && "function" == typeof e3.copy && "function" == typeof e3.fill && "function" == typeof e3.readUInt8; + }, "i$1"); + var o$2 = {}; + var u$1 = i$1; + var f2 = l2; + var a2 = i2; + function c$1(e3) { + return e3.call.bind(e3); + } + __name(c$1, "c$1"); + var s2 = "undefined" != typeof BigInt; + var p2 = "undefined" != typeof Symbol; + var y = p2 && void 0 !== Symbol.toStringTag; + var l$1 = "undefined" != typeof Uint8Array; + var d2 = "undefined" != typeof ArrayBuffer; + if (l$1 && y) + var g = Object.getPrototypeOf(Uint8Array.prototype), b = c$1(Object.getOwnPropertyDescriptor(g, Symbol.toStringTag).get); + var m2 = c$1(Object.prototype.toString); + var h2 = c$1(Number.prototype.valueOf); + var j = c$1(String.prototype.valueOf); + var A = c$1(Boolean.prototype.valueOf); + if (s2) + var w = c$1(BigInt.prototype.valueOf); + if (p2) + var v = c$1(Symbol.prototype.valueOf); + function O(e3, t3) { + if ("object" != typeof e3) + return false; + try { + return t3(e3), true; + } catch (e4) { + return false; + } + } + __name(O, "O"); + function S(e3) { + return l$1 && y ? void 0 !== b(e3) : B(e3) || k(e3) || E(e3) || D(e3) || U(e3) || P(e3) || x(e3) || I(e3) || M(e3) || z(e3) || F(e3); + } + __name(S, "S"); + function B(e3) { + return l$1 && y ? "Uint8Array" === b(e3) : "[object Uint8Array]" === m2(e3) || u$1(e3) && void 0 !== e3.buffer; + } + __name(B, "B"); + function k(e3) { + return l$1 && y ? "Uint8ClampedArray" === b(e3) : "[object Uint8ClampedArray]" === m2(e3); + } + __name(k, "k"); + function E(e3) { + return l$1 && y ? "Uint16Array" === b(e3) : "[object Uint16Array]" === m2(e3); + } + __name(E, "E"); + function D(e3) { + return l$1 && y ? "Uint32Array" === b(e3) : "[object Uint32Array]" === m2(e3); + } + __name(D, "D"); + function U(e3) { + return l$1 && y ? "Int8Array" === b(e3) : "[object Int8Array]" === m2(e3); + } + __name(U, "U"); + function P(e3) { + return l$1 && y ? "Int16Array" === b(e3) : "[object Int16Array]" === m2(e3); + } + __name(P, "P"); + function x(e3) { + return l$1 && y ? "Int32Array" === b(e3) : "[object Int32Array]" === m2(e3); + } + __name(x, "x"); + function I(e3) { + return l$1 && y ? "Float32Array" === b(e3) : "[object Float32Array]" === m2(e3); + } + __name(I, "I"); + function M(e3) { + return l$1 && y ? "Float64Array" === b(e3) : "[object Float64Array]" === m2(e3); + } + __name(M, "M"); + function z(e3) { + return l$1 && y ? "BigInt64Array" === b(e3) : "[object BigInt64Array]" === m2(e3); + } + __name(z, "z"); + function F(e3) { + return l$1 && y ? "BigUint64Array" === b(e3) : "[object BigUint64Array]" === m2(e3); + } + __name(F, "F"); + function T2(e3) { + return "[object Map]" === m2(e3); + } + __name(T2, "T2"); + function N(e3) { + return "[object Set]" === m2(e3); + } + __name(N, "N"); + function W(e3) { + return "[object WeakMap]" === m2(e3); + } + __name(W, "W"); + function $(e3) { + return "[object WeakSet]" === m2(e3); + } + __name($, "$"); + function C(e3) { + return "[object ArrayBuffer]" === m2(e3); + } + __name(C, "C"); + function V(e3) { + return "undefined" != typeof ArrayBuffer && (C.working ? C(e3) : e3 instanceof ArrayBuffer); + } + __name(V, "V"); + function G(e3) { + return "[object DataView]" === m2(e3); + } + __name(G, "G"); + function R(e3) { + return "undefined" != typeof DataView && (G.working ? G(e3) : e3 instanceof DataView); + } + __name(R, "R"); + function J(e3) { + return "[object SharedArrayBuffer]" === m2(e3); + } + __name(J, "J"); + function _(e3) { + return "undefined" != typeof SharedArrayBuffer && (J.working ? J(e3) : e3 instanceof SharedArrayBuffer); + } + __name(_, "_"); + function H(e3) { + return O(e3, h2); + } + __name(H, "H"); + function Z(e3) { + return O(e3, j); + } + __name(Z, "Z"); + function q(e3) { + return O(e3, A); + } + __name(q, "q"); + function K(e3) { + return s2 && O(e3, w); + } + __name(K, "K"); + function L(e3) { + return p2 && O(e3, v); + } + __name(L, "L"); + o$2.isArgumentsObject = f2, o$2.isGeneratorFunction = a2, o$2.isPromise = function(e3) { + return "undefined" != typeof Promise && e3 instanceof Promise || null !== e3 && "object" == typeof e3 && "function" == typeof e3.then && "function" == typeof e3.catch; + }, o$2.isArrayBufferView = function(e3) { + return d2 && ArrayBuffer.isView ? ArrayBuffer.isView(e3) : S(e3) || R(e3); + }, o$2.isTypedArray = S, o$2.isUint8Array = B, o$2.isUint8ClampedArray = k, o$2.isUint16Array = E, o$2.isUint32Array = D, o$2.isInt8Array = U, o$2.isInt16Array = P, o$2.isInt32Array = x, o$2.isFloat32Array = I, o$2.isFloat64Array = M, o$2.isBigInt64Array = z, o$2.isBigUint64Array = F, T2.working = "undefined" != typeof Map && T2(/* @__PURE__ */ new Map()), o$2.isMap = function(e3) { + return "undefined" != typeof Map && (T2.working ? T2(e3) : e3 instanceof Map); + }, N.working = "undefined" != typeof Set && N(/* @__PURE__ */ new Set()), o$2.isSet = function(e3) { + return "undefined" != typeof Set && (N.working ? N(e3) : e3 instanceof Set); + }, W.working = "undefined" != typeof WeakMap && W(/* @__PURE__ */ new WeakMap()), o$2.isWeakMap = function(e3) { + return "undefined" != typeof WeakMap && (W.working ? W(e3) : e3 instanceof WeakMap); + }, $.working = "undefined" != typeof WeakSet && $(/* @__PURE__ */ new WeakSet()), o$2.isWeakSet = function(e3) { + return $(e3); + }, C.working = "undefined" != typeof ArrayBuffer && C(new ArrayBuffer()), o$2.isArrayBuffer = V, G.working = "undefined" != typeof ArrayBuffer && "undefined" != typeof DataView && G(new DataView(new ArrayBuffer(1), 0, 1)), o$2.isDataView = R, J.working = "undefined" != typeof SharedArrayBuffer && J(new SharedArrayBuffer()), o$2.isSharedArrayBuffer = _, o$2.isAsyncFunction = function(e3) { + return "[object AsyncFunction]" === m2(e3); + }, o$2.isMapIterator = function(e3) { + return "[object Map Iterator]" === m2(e3); + }, o$2.isSetIterator = function(e3) { + return "[object Set Iterator]" === m2(e3); + }, o$2.isGeneratorObject = function(e3) { + return "[object Generator]" === m2(e3); + }, o$2.isWebAssemblyCompiledModule = function(e3) { + return "[object WebAssembly.Module]" === m2(e3); + }, o$2.isNumberObject = H, o$2.isStringObject = Z, o$2.isBooleanObject = q, o$2.isBigIntObject = K, o$2.isSymbolObject = L, o$2.isBoxedPrimitive = function(e3) { + return H(e3) || Z(e3) || q(e3) || K(e3) || L(e3); + }, o$2.isAnyArrayBuffer = function(e3) { + return l$1 && (V(e3) || _(e3)); + }, ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function(e3) { + Object.defineProperty(o$2, e3, { enumerable: false, value: function() { + throw new Error(e3 + " is not supported in userland"); + } }); + }); + var Q = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : globalThis; + var X = {}; + var Y = T; + var ee = Object.getOwnPropertyDescriptors || function(e3) { + for (var t3 = Object.keys(e3), r3 = {}, n3 = 0; n3 < t3.length; n3++) + r3[t3[n3]] = Object.getOwnPropertyDescriptor(e3, t3[n3]); + return r3; + }; + var te = /%[sdj%]/g; + X.format = function(e3) { + if (!ge(e3)) { + for (var t3 = [], r3 = 0; r3 < arguments.length; r3++) + t3.push(oe(arguments[r3])); + return t3.join(" "); + } + r3 = 1; + for (var n3 = arguments, i3 = n3.length, o3 = String(e3).replace(te, function(e4) { + if ("%%" === e4) + return "%"; + if (r3 >= i3) + return e4; + switch (e4) { + case "%s": + return String(n3[r3++]); + case "%d": + return Number(n3[r3++]); + case "%j": + try { + return JSON.stringify(n3[r3++]); + } catch (e5) { + return "[Circular]"; + } + default: + return e4; + } + }), u3 = n3[r3]; r3 < i3; u3 = n3[++r3]) + le(u3) || !he(u3) ? o3 += " " + u3 : o3 += " " + oe(u3); + return o3; + }, X.deprecate = function(e3, t3) { + if (void 0 !== Y && true === Y.noDeprecation) + return e3; + if (void 0 === Y) + return function() { + return X.deprecate(e3, t3).apply(this || Q, arguments); + }; + var r3 = false; + return function() { + if (!r3) { + if (Y.throwDeprecation) + throw new Error(t3); + Y.traceDeprecation ? console.trace(t3) : console.error(t3), r3 = true; + } + return e3.apply(this || Q, arguments); + }; + }; + var re = {}; + var ne = /^$/; + if (Y.env.NODE_DEBUG) { + ie = Y.env.NODE_DEBUG; + ie = ie.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase(), ne = new RegExp("^" + ie + "$", "i"); + } + var ie; + function oe(e3, t3) { + var r3 = { seen: [], stylize: fe }; + return arguments.length >= 3 && (r3.depth = arguments[2]), arguments.length >= 4 && (r3.colors = arguments[3]), ye(t3) ? r3.showHidden = t3 : t3 && X._extend(r3, t3), be(r3.showHidden) && (r3.showHidden = false), be(r3.depth) && (r3.depth = 2), be(r3.colors) && (r3.colors = false), be(r3.customInspect) && (r3.customInspect = true), r3.colors && (r3.stylize = ue), ae(r3, e3, r3.depth); + } + __name(oe, "oe"); + function ue(e3, t3) { + var r3 = oe.styles[t3]; + return r3 ? "\x1B[" + oe.colors[r3][0] + "m" + e3 + "\x1B[" + oe.colors[r3][1] + "m" : e3; + } + __name(ue, "ue"); + function fe(e3, t3) { + return e3; + } + __name(fe, "fe"); + function ae(e3, t3, r3) { + if (e3.customInspect && t3 && we(t3.inspect) && t3.inspect !== X.inspect && (!t3.constructor || t3.constructor.prototype !== t3)) { + var n3 = t3.inspect(r3, e3); + return ge(n3) || (n3 = ae(e3, n3, r3)), n3; + } + var i3 = function(e4, t4) { + if (be(t4)) + return e4.stylize("undefined", "undefined"); + if (ge(t4)) { + var r4 = "'" + JSON.stringify(t4).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; + return e4.stylize(r4, "string"); + } + if (de(t4)) + return e4.stylize("" + t4, "number"); + if (ye(t4)) + return e4.stylize("" + t4, "boolean"); + if (le(t4)) + return e4.stylize("null", "null"); + }(e3, t3); + if (i3) + return i3; + var o3 = Object.keys(t3), u3 = function(e4) { + var t4 = {}; + return e4.forEach(function(e5, r4) { + t4[e5] = true; + }), t4; + }(o3); + if (e3.showHidden && (o3 = Object.getOwnPropertyNames(t3)), Ae(t3) && (o3.indexOf("message") >= 0 || o3.indexOf("description") >= 0)) + return ce(t3); + if (0 === o3.length) { + if (we(t3)) { + var f3 = t3.name ? ": " + t3.name : ""; + return e3.stylize("[Function" + f3 + "]", "special"); + } + if (me(t3)) + return e3.stylize(RegExp.prototype.toString.call(t3), "regexp"); + if (je(t3)) + return e3.stylize(Date.prototype.toString.call(t3), "date"); + if (Ae(t3)) + return ce(t3); + } + var a3, c3 = "", s32 = false, p3 = ["{", "}"]; + (pe(t3) && (s32 = true, p3 = ["[", "]"]), we(t3)) && (c3 = " [Function" + (t3.name ? ": " + t3.name : "") + "]"); + return me(t3) && (c3 = " " + RegExp.prototype.toString.call(t3)), je(t3) && (c3 = " " + Date.prototype.toUTCString.call(t3)), Ae(t3) && (c3 = " " + ce(t3)), 0 !== o3.length || s32 && 0 != t3.length ? r3 < 0 ? me(t3) ? e3.stylize(RegExp.prototype.toString.call(t3), "regexp") : e3.stylize("[Object]", "special") : (e3.seen.push(t3), a3 = s32 ? function(e4, t4, r4, n4, i4) { + for (var o4 = [], u4 = 0, f4 = t4.length; u4 < f4; ++u4) + ke(t4, String(u4)) ? o4.push(se(e4, t4, r4, n4, String(u4), true)) : o4.push(""); + return i4.forEach(function(i5) { + i5.match(/^\d+$/) || o4.push(se(e4, t4, r4, n4, i5, true)); + }), o4; + }(e3, t3, r3, u3, o3) : o3.map(function(n4) { + return se(e3, t3, r3, u3, n4, s32); + }), e3.seen.pop(), function(e4, t4, r4) { + var n4 = 0; + if (e4.reduce(function(e5, t5) { + return n4++, t5.indexOf("\n") >= 0 && n4++, e5 + t5.replace(/\u001b\[\d\d?m/g, "").length + 1; + }, 0) > 60) + return r4[0] + ("" === t4 ? "" : t4 + "\n ") + " " + e4.join(",\n ") + " " + r4[1]; + return r4[0] + t4 + " " + e4.join(", ") + " " + r4[1]; + }(a3, c3, p3)) : p3[0] + c3 + p3[1]; + } + __name(ae, "ae"); + function ce(e3) { + return "[" + Error.prototype.toString.call(e3) + "]"; + } + __name(ce, "ce"); + function se(e3, t3, r3, n3, i3, o3) { + var u3, f3, a3; + if ((a3 = Object.getOwnPropertyDescriptor(t3, i3) || { value: t3[i3] }).get ? f3 = a3.set ? e3.stylize("[Getter/Setter]", "special") : e3.stylize("[Getter]", "special") : a3.set && (f3 = e3.stylize("[Setter]", "special")), ke(n3, i3) || (u3 = "[" + i3 + "]"), f3 || (e3.seen.indexOf(a3.value) < 0 ? (f3 = le(r3) ? ae(e3, a3.value, null) : ae(e3, a3.value, r3 - 1)).indexOf("\n") > -1 && (f3 = o3 ? f3.split("\n").map(function(e4) { + return " " + e4; + }).join("\n").substr(2) : "\n" + f3.split("\n").map(function(e4) { + return " " + e4; + }).join("\n")) : f3 = e3.stylize("[Circular]", "special")), be(u3)) { + if (o3 && i3.match(/^\d+$/)) + return f3; + (u3 = JSON.stringify("" + i3)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/) ? (u3 = u3.substr(1, u3.length - 2), u3 = e3.stylize(u3, "name")) : (u3 = u3.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"), u3 = e3.stylize(u3, "string")); + } + return u3 + ": " + f3; + } + __name(se, "se"); + function pe(e3) { + return Array.isArray(e3); + } + __name(pe, "pe"); + function ye(e3) { + return "boolean" == typeof e3; + } + __name(ye, "ye"); + function le(e3) { + return null === e3; + } + __name(le, "le"); + function de(e3) { + return "number" == typeof e3; + } + __name(de, "de"); + function ge(e3) { + return "string" == typeof e3; + } + __name(ge, "ge"); + function be(e3) { + return void 0 === e3; + } + __name(be, "be"); + function me(e3) { + return he(e3) && "[object RegExp]" === ve(e3); + } + __name(me, "me"); + function he(e3) { + return "object" == typeof e3 && null !== e3; + } + __name(he, "he"); + function je(e3) { + return he(e3) && "[object Date]" === ve(e3); + } + __name(je, "je"); + function Ae(e3) { + return he(e3) && ("[object Error]" === ve(e3) || e3 instanceof Error); + } + __name(Ae, "Ae"); + function we(e3) { + return "function" == typeof e3; + } + __name(we, "we"); + function ve(e3) { + return Object.prototype.toString.call(e3); + } + __name(ve, "ve"); + function Oe(e3) { + return e3 < 10 ? "0" + e3.toString(10) : e3.toString(10); + } + __name(Oe, "Oe"); + X.debuglog = function(e3) { + if (e3 = e3.toUpperCase(), !re[e3]) + if (ne.test(e3)) { + var t3 = Y.pid; + re[e3] = function() { + var r3 = X.format.apply(X, arguments); + console.error("%s %d: %s", e3, t3, r3); + }; + } else + re[e3] = function() { + }; + return re[e3]; + }, X.inspect = oe, oe.colors = { bold: [1, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], white: [37, 39], grey: [90, 39], black: [30, 39], blue: [34, 39], cyan: [36, 39], green: [32, 39], magenta: [35, 39], red: [31, 39], yellow: [33, 39] }, oe.styles = { special: "cyan", number: "yellow", boolean: "yellow", undefined: "grey", null: "bold", string: "green", date: "magenta", regexp: "red" }, X.types = o$2, X.isArray = pe, X.isBoolean = ye, X.isNull = le, X.isNullOrUndefined = function(e3) { + return null == e3; + }, X.isNumber = de, X.isString = ge, X.isSymbol = function(e3) { + return "symbol" == typeof e3; + }, X.isUndefined = be, X.isRegExp = me, X.types.isRegExp = me, X.isObject = he, X.isDate = je, X.types.isDate = je, X.isError = Ae, X.types.isNativeError = Ae, X.isFunction = we, X.isPrimitive = function(e3) { + return null === e3 || "boolean" == typeof e3 || "number" == typeof e3 || "string" == typeof e3 || "symbol" == typeof e3 || void 0 === e3; + }, X.isBuffer = i$1; + var Se = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + function Be() { + var e3 = new Date(), t3 = [Oe(e3.getHours()), Oe(e3.getMinutes()), Oe(e3.getSeconds())].join(":"); + return [e3.getDate(), Se[e3.getMonth()], t3].join(" "); + } + __name(Be, "Be"); + function ke(e3, t3) { + return Object.prototype.hasOwnProperty.call(e3, t3); + } + __name(ke, "ke"); + X.log = function() { + console.log("%s - %s", Be(), X.format.apply(X, arguments)); + }, X.inherits = t$2, X._extend = function(e3, t3) { + if (!t3 || !he(t3)) + return e3; + for (var r3 = Object.keys(t3), n3 = r3.length; n3--; ) + e3[r3[n3]] = t3[r3[n3]]; + return e3; + }; + var Ee = "undefined" != typeof Symbol ? Symbol("util.promisify.custom") : void 0; + function De(e3, t3) { + if (!e3) { + var r3 = new Error("Promise was rejected with a falsy value"); + r3.reason = e3, e3 = r3; + } + return t3(e3); + } + __name(De, "De"); + X.promisify = function(e3) { + if ("function" != typeof e3) + throw new TypeError('The "original" argument must be of type Function'); + if (Ee && e3[Ee]) { + var t3; + if ("function" != typeof (t3 = e3[Ee])) + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + return Object.defineProperty(t3, Ee, { value: t3, enumerable: false, writable: false, configurable: true }), t3; + } + function t3() { + for (var t4, r3, n3 = new Promise(function(e4, n4) { + t4 = e4, r3 = n4; + }), i3 = [], o3 = 0; o3 < arguments.length; o3++) + i3.push(arguments[o3]); + i3.push(function(e4, n4) { + e4 ? r3(e4) : t4(n4); + }); + try { + e3.apply(this || Q, i3); + } catch (e4) { + r3(e4); + } + return n3; + } + __name(t3, "t3"); + return Object.setPrototypeOf(t3, Object.getPrototypeOf(e3)), Ee && Object.defineProperty(t3, Ee, { value: t3, enumerable: false, writable: false, configurable: true }), Object.defineProperties(t3, ee(e3)); + }, X.promisify.custom = Ee, X.callbackify = function(e3) { + if ("function" != typeof e3) + throw new TypeError('The "original" argument must be of type Function'); + function t3() { + for (var t4 = [], r3 = 0; r3 < arguments.length; r3++) + t4.push(arguments[r3]); + var n3 = t4.pop(); + if ("function" != typeof n3) + throw new TypeError("The last argument must be of type Function"); + var i3 = this || Q, o3 = /* @__PURE__ */ __name(function() { + return n3.apply(i3, arguments); + }, "o3"); + e3.apply(this || Q, t4).then(function(e4) { + Y.nextTick(o3.bind(null, null, e4)); + }, function(e4) { + Y.nextTick(De.bind(null, e4, o3)); + }); + } + __name(t3, "t3"); + return Object.setPrototypeOf(t3, Object.getPrototypeOf(e3)), Object.defineProperties(t3, ee(e3)), t3; + }; + X._extend; + X.callbackify; + X.debuglog; + X.deprecate; + X.format; + X.inherits; + X.inspect; + X.isArray; + X.isBoolean; + X.isBuffer; + X.isDate; + X.isError; + X.isFunction; + X.isNull; + X.isNullOrUndefined; + X.isNumber; + X.isObject; + X.isPrimitive; + X.isRegExp; + X.isString; + X.isSymbol; + X.isUndefined; + X.log; + X.promisify; + X._extend; + X.callbackify; + X.debuglog; + X.deprecate; + X.format; + X.inherits; + X.inspect; + X.isArray; + X.isBoolean; + X.isBuffer; + X.isDate; + X.isError; + X.isFunction; + X.isNull; + X.isNullOrUndefined; + X.isNumber; + X.isObject; + X.isPrimitive; + X.isRegExp; + X.isString; + X.isSymbol; + X.isUndefined; + X.log; + X.promisify; + X.types; + X._extend; + X.callbackify; + X.debuglog; + X.deprecate; + X.format; + X.inherits; + var inspect2 = X.inspect; + X.isArray; + X.isBoolean; + X.isBuffer; + X.isDate; + X.isError; + X.isFunction; + X.isNull; + X.isNullOrUndefined; + X.isNumber; + X.isObject; + X.isPrimitive; + X.isRegExp; + X.isString; + X.isSymbol; + X.isUndefined; + X.log; + X.promisify; + X.types; + X.TextEncoder = globalThis.TextEncoder; + X.TextDecoder = globalThis.TextDecoder; + + // src/lib/errors/BaseError.ts + var customInspectSymbol = Symbol.for("nodejs.util.inspect.custom"); + var customInspectSymbolStackLess = Symbol.for("nodejs.util.inspect.custom.stack-less"); + var BaseError = class extends Error { + [customInspectSymbol](depth, options) { + return `${this[customInspectSymbolStackLess](depth, options)} +${this.stack.slice(this.stack.indexOf("\n"))}`; + } + }; + __name(BaseError, "BaseError"); + + // src/lib/errors/BaseConstraintError.ts + var BaseConstraintError = class extends BaseError { + constructor(constraint, message, given) { + super(message); + this.constraint = constraint; + this.given = given; + } + }; + __name(BaseConstraintError, "BaseConstraintError"); + + // src/lib/errors/ExpectedConstraintError.ts + var ExpectedConstraintError = class extends BaseConstraintError { + constructor(constraint, message, given, expected) { + super(constraint, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + constraint: this.constraint, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const constraint = options.stylize(this.constraint, "string"); + if (depth < 0) { + return options.stylize(`[ExpectedConstraintError: ${constraint}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = inspect2(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ExpectedConstraintError", "special")} > ${constraint}`; + const message = options.stylize(this.message, "regexp"); + const expectedBlock = ` + ${options.stylize("Expected: ", "string")}${options.stylize(this.expected, "boolean")}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } + }; + __name(ExpectedConstraintError, "ExpectedConstraintError"); + + // src/constraints/ObjectConstrains.ts + function whenConstraint(key, options, validator) { + return { + run(input, parent) { + if (!parent) { + return Result.err(new ExpectedConstraintError("s.object(T.when)", "Validator has no parent", parent, "Validator to have a parent")); + } + const isKeyArray = Array.isArray(key); + const value = isKeyArray ? key.map((k2) => (0, import_get.default)(parent, k2)) : (0, import_get.default)(parent, key); + const predicate = resolveBooleanIs(options, value, isKeyArray) ? options.then : options.otherwise; + if (predicate) { + return predicate(validator).run(input); + } + return Result.ok(input); + } + }; + } + __name(whenConstraint, "whenConstraint"); + function resolveBooleanIs(options, value, isKeyArray) { + if (options.is === void 0) { + return isKeyArray ? !value.some((val) => !val) : Boolean(value); + } + if (typeof options.is === "function") { + return options.is(value); + } + return value === options.is; + } + __name(resolveBooleanIs, "resolveBooleanIs"); + + // src/validators/BaseValidator.ts + var BaseValidator = class { + constructor(constraints = []) { + this.constraints = []; + this.isValidationEnabled = null; + this.constraints = constraints; + } + setParent(parent) { + this.parent = parent; + return this; + } + get optional() { + return new UnionValidator([new LiteralValidator(void 0), this.clone()]); + } + get nullable() { + return new UnionValidator([new LiteralValidator(null), this.clone()]); + } + get nullish() { + return new UnionValidator([new NullishValidator(), this.clone()]); + } + get array() { + return new ArrayValidator(this.clone()); + } + get set() { + return new SetValidator(this.clone()); + } + or(...predicates) { + return new UnionValidator([this.clone(), ...predicates]); + } + transform(cb) { + return this.addConstraint({ run: (input) => Result.ok(cb(input)) }); + } + reshape(cb) { + return this.addConstraint({ run: cb }); + } + default(value) { + return new DefaultValidator(this.clone(), value); + } + when(key, options) { + return this.addConstraint(whenConstraint(key, options, this)); + } + run(value) { + let result = this.handle(value); + if (result.isErr()) + return result; + for (const constraint of this.constraints) { + result = constraint.run(result.value, this.parent); + if (result.isErr()) + break; + } + return result; + } + parse(value) { + if (!this.shouldRunConstraints) { + return this.handle(value).unwrap(); + } + return this.constraints.reduce((v2, constraint) => constraint.run(v2).unwrap(), this.handle(value).unwrap()); + } + is(value) { + return this.run(value).isOk(); + } + setValidationEnabled(isValidationEnabled) { + const clone = this.clone(); + clone.isValidationEnabled = isValidationEnabled; + return clone; + } + getValidationEnabled() { + return getValue(this.isValidationEnabled); + } + get shouldRunConstraints() { + return getValue(this.isValidationEnabled) ?? getGlobalValidationEnabled(); + } + clone() { + const clone = Reflect.construct(this.constructor, [this.constraints]); + clone.isValidationEnabled = this.isValidationEnabled; + return clone; + } + addConstraint(constraint) { + const clone = this.clone(); + clone.constraints = clone.constraints.concat(constraint); + return clone; + } + }; + __name(BaseValidator, "BaseValidator"); + + // src/constraints/util/isUnique.ts + var import_es6 = __toESM(require_es6()); + var import_uniqWith = __toESM(require_uniqWith()); + function isUnique(input) { + if (input.length < 2) + return true; + const uniqueArray2 = (0, import_uniqWith.default)(input, import_es6.default); + return uniqueArray2.length === input.length; + } + __name(isUnique, "isUnique"); + + // src/constraints/util/operators.ts + function lessThan(a3, b2) { + return a3 < b2; + } + __name(lessThan, "lessThan"); + function lessThanOrEqual(a3, b2) { + return a3 <= b2; + } + __name(lessThanOrEqual, "lessThanOrEqual"); + function greaterThan(a3, b2) { + return a3 > b2; + } + __name(greaterThan, "greaterThan"); + function greaterThanOrEqual(a3, b2) { + return a3 >= b2; + } + __name(greaterThanOrEqual, "greaterThanOrEqual"); + function equal(a3, b2) { + return a3 === b2; + } + __name(equal, "equal"); + function notEqual(a3, b2) { + return a3 !== b2; + } + __name(notEqual, "notEqual"); + + // src/constraints/ArrayConstraints.ts + function arrayLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Array length", input, expected)); + } + }; + } + __name(arrayLengthComparator, "arrayLengthComparator"); + function arrayLengthLessThan(value) { + const expected = `expected.length < ${value}`; + return arrayLengthComparator(lessThan, "s.array(T).lengthLessThan", expected, value); + } + __name(arrayLengthLessThan, "arrayLengthLessThan"); + function arrayLengthLessThanOrEqual(value) { + const expected = `expected.length <= ${value}`; + return arrayLengthComparator(lessThanOrEqual, "s.array(T).lengthLessThanOrEqual", expected, value); + } + __name(arrayLengthLessThanOrEqual, "arrayLengthLessThanOrEqual"); + function arrayLengthGreaterThan(value) { + const expected = `expected.length > ${value}`; + return arrayLengthComparator(greaterThan, "s.array(T).lengthGreaterThan", expected, value); + } + __name(arrayLengthGreaterThan, "arrayLengthGreaterThan"); + function arrayLengthGreaterThanOrEqual(value) { + const expected = `expected.length >= ${value}`; + return arrayLengthComparator(greaterThanOrEqual, "s.array(T).lengthGreaterThanOrEqual", expected, value); + } + __name(arrayLengthGreaterThanOrEqual, "arrayLengthGreaterThanOrEqual"); + function arrayLengthEqual(value) { + const expected = `expected.length === ${value}`; + return arrayLengthComparator(equal, "s.array(T).lengthEqual", expected, value); + } + __name(arrayLengthEqual, "arrayLengthEqual"); + function arrayLengthNotEqual(value) { + const expected = `expected.length !== ${value}`; + return arrayLengthComparator(notEqual, "s.array(T).lengthNotEqual", expected, value); + } + __name(arrayLengthNotEqual, "arrayLengthNotEqual"); + function arrayLengthRange(start, endBefore) { + const expected = `expected.length >= ${start} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length >= start && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRange", "Invalid Array length", input, expected)); + } + }; + } + __name(arrayLengthRange, "arrayLengthRange"); + function arrayLengthRangeInclusive(start, end) { + const expected = `expected.length >= ${start} && expected.length <= ${end}`; + return { + run(input) { + return input.length >= start && input.length <= end ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRangeInclusive", "Invalid Array length", input, expected)); + } + }; + } + __name(arrayLengthRangeInclusive, "arrayLengthRangeInclusive"); + function arrayLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length > startAfter && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRangeExclusive", "Invalid Array length", input, expected)); + } + }; + } + __name(arrayLengthRangeExclusive, "arrayLengthRangeExclusive"); + var uniqueArray = { + run(input) { + return isUnique(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).unique", "Array values are not unique", input, "Expected all values to be unique")); + } + }; + + // src/lib/errors/CombinedPropertyError.ts + var CombinedPropertyError = class extends BaseError { + constructor(errors) { + super("Received one or more errors"); + this.errors = errors; + } + [customInspectSymbolStackLess](depth, options) { + if (depth < 0) { + return options.stylize("[CombinedPropertyError]", "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const header = `${options.stylize("CombinedPropertyError", "special")} (${options.stylize(this.errors.length.toString(), "number")})`; + const message = options.stylize(this.message, "regexp"); + const errors = this.errors.map(([key, error]) => { + const property = CombinedPropertyError.formatProperty(key, options); + const body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\n/g, padding); + return ` input${property}${padding}${body}`; + }).join("\n\n"); + return `${header} + ${message} + +${errors}`; + } + static formatProperty(key, options) { + if (typeof key === "string") + return options.stylize(`.${key}`, "symbol"); + if (typeof key === "number") + return `[${options.stylize(key.toString(), "number")}]`; + return `[${options.stylize("Symbol", "symbol")}(${key.description})]`; + } + }; + __name(CombinedPropertyError, "CombinedPropertyError"); + + // src/lib/errors/ValidationError.ts + var ValidationError = class extends BaseError { + constructor(validator, message, given) { + super(message); + this.validator = validator; + this.given = given; + } + toJSON() { + return { + name: this.name, + validator: this.validator, + given: this.given + }; + } + [customInspectSymbolStackLess](depth, options) { + const validator = options.stylize(this.validator, "string"); + if (depth < 0) { + return options.stylize(`[ValidationError: ${validator}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = inspect2(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ValidationError", "special")} > ${validator}`; + const message = options.stylize(this.message, "regexp"); + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${givenBlock}`; + } + }; + __name(ValidationError, "ValidationError"); + + // src/validators/ArrayValidator.ts + var ArrayValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + lengthLessThan(length) { + return this.addConstraint(arrayLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(arrayLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(arrayLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(arrayLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(arrayLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(arrayLengthNotEqual(length)); + } + lengthRange(start, endBefore) { + return this.addConstraint(arrayLengthRange(start, endBefore)); + } + lengthRangeInclusive(startAt, endAt) { + return this.addConstraint(arrayLengthRangeInclusive(startAt, endAt)); + } + lengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(arrayLengthRangeExclusive(startAfter, endBefore)); + } + get unique() { + return this.addConstraint(uniqueArray); + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + if (!Array.isArray(values)) { + return Result.err(new ValidationError("s.array(T)", "Expected an array", values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = []; + for (let i3 = 0; i3 < values.length; i3++) { + const result = this.validator.run(values[i3]); + if (result.isOk()) + transformed.push(result.value); + else + errors.push([i3, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } + }; + __name(ArrayValidator, "ArrayValidator"); + + // src/constraints/BigIntConstraints.ts + function bigintComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input, number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid bigint value", input, expected)); + } + }; + } + __name(bigintComparator, "bigintComparator"); + function bigintLessThan(value) { + const expected = `expected < ${value}n`; + return bigintComparator(lessThan, "s.bigint.lessThan", expected, value); + } + __name(bigintLessThan, "bigintLessThan"); + function bigintLessThanOrEqual(value) { + const expected = `expected <= ${value}n`; + return bigintComparator(lessThanOrEqual, "s.bigint.lessThanOrEqual", expected, value); + } + __name(bigintLessThanOrEqual, "bigintLessThanOrEqual"); + function bigintGreaterThan(value) { + const expected = `expected > ${value}n`; + return bigintComparator(greaterThan, "s.bigint.greaterThan", expected, value); + } + __name(bigintGreaterThan, "bigintGreaterThan"); + function bigintGreaterThanOrEqual(value) { + const expected = `expected >= ${value}n`; + return bigintComparator(greaterThanOrEqual, "s.bigint.greaterThanOrEqual", expected, value); + } + __name(bigintGreaterThanOrEqual, "bigintGreaterThanOrEqual"); + function bigintEqual(value) { + const expected = `expected === ${value}n`; + return bigintComparator(equal, "s.bigint.equal", expected, value); + } + __name(bigintEqual, "bigintEqual"); + function bigintNotEqual(value) { + const expected = `expected !== ${value}n`; + return bigintComparator(notEqual, "s.bigint.notEqual", expected, value); + } + __name(bigintNotEqual, "bigintNotEqual"); + function bigintDivisibleBy(divider) { + const expected = `expected % ${divider}n === 0n`; + return { + run(input) { + return input % divider === 0n ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.bigint.divisibleBy", "BigInt is not divisible", input, expected)); + } + }; + } + __name(bigintDivisibleBy, "bigintDivisibleBy"); + + // src/validators/BigIntValidator.ts + var BigIntValidator = class extends BaseValidator { + lessThan(number) { + return this.addConstraint(bigintLessThan(number)); + } + lessThanOrEqual(number) { + return this.addConstraint(bigintLessThanOrEqual(number)); + } + greaterThan(number) { + return this.addConstraint(bigintGreaterThan(number)); + } + greaterThanOrEqual(number) { + return this.addConstraint(bigintGreaterThanOrEqual(number)); + } + equal(number) { + return this.addConstraint(bigintEqual(number)); + } + notEqual(number) { + return this.addConstraint(bigintNotEqual(number)); + } + get positive() { + return this.greaterThanOrEqual(0n); + } + get negative() { + return this.lessThan(0n); + } + divisibleBy(number) { + return this.addConstraint(bigintDivisibleBy(number)); + } + get abs() { + return this.transform((value) => value < 0 ? -value : value); + } + intN(bits) { + return this.transform((value) => BigInt.asIntN(bits, value)); + } + uintN(bits) { + return this.transform((value) => BigInt.asUintN(bits, value)); + } + handle(value) { + return typeof value === "bigint" ? Result.ok(value) : Result.err(new ValidationError("s.bigint", "Expected a bigint primitive", value)); + } + }; + __name(BigIntValidator, "BigIntValidator"); + + // src/constraints/BooleanConstraints.ts + var booleanTrue = { + run(input) { + return input ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.boolean.true", "Invalid boolean value", input, "true")); + } + }; + var booleanFalse = { + run(input) { + return input ? Result.err(new ExpectedConstraintError("s.boolean.false", "Invalid boolean value", input, "false")) : Result.ok(input); + } + }; + + // src/validators/BooleanValidator.ts + var BooleanValidator = class extends BaseValidator { + get true() { + return this.addConstraint(booleanTrue); + } + get false() { + return this.addConstraint(booleanFalse); + } + equal(value) { + return value ? this.true : this.false; + } + notEqual(value) { + return value ? this.false : this.true; + } + handle(value) { + return typeof value === "boolean" ? Result.ok(value) : Result.err(new ValidationError("s.boolean", "Expected a boolean primitive", value)); + } + }; + __name(BooleanValidator, "BooleanValidator"); + + // src/constraints/DateConstraints.ts + function dateComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input.getTime(), number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Date value", input, expected)); + } + }; + } + __name(dateComparator, "dateComparator"); + function dateLessThan(value) { + const expected = `expected < ${value.toISOString()}`; + return dateComparator(lessThan, "s.date.lessThan", expected, value.getTime()); + } + __name(dateLessThan, "dateLessThan"); + function dateLessThanOrEqual(value) { + const expected = `expected <= ${value.toISOString()}`; + return dateComparator(lessThanOrEqual, "s.date.lessThanOrEqual", expected, value.getTime()); + } + __name(dateLessThanOrEqual, "dateLessThanOrEqual"); + function dateGreaterThan(value) { + const expected = `expected > ${value.toISOString()}`; + return dateComparator(greaterThan, "s.date.greaterThan", expected, value.getTime()); + } + __name(dateGreaterThan, "dateGreaterThan"); + function dateGreaterThanOrEqual(value) { + const expected = `expected >= ${value.toISOString()}`; + return dateComparator(greaterThanOrEqual, "s.date.greaterThanOrEqual", expected, value.getTime()); + } + __name(dateGreaterThanOrEqual, "dateGreaterThanOrEqual"); + function dateEqual(value) { + const expected = `expected === ${value.toISOString()}`; + return dateComparator(equal, "s.date.equal", expected, value.getTime()); + } + __name(dateEqual, "dateEqual"); + function dateNotEqual(value) { + const expected = `expected !== ${value.toISOString()}`; + return dateComparator(notEqual, "s.date.notEqual", expected, value.getTime()); + } + __name(dateNotEqual, "dateNotEqual"); + var dateInvalid = { + run(input) { + return Number.isNaN(input.getTime()) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.date.invalid", "Invalid Date value", input, "expected === NaN")); + } + }; + var dateValid = { + run(input) { + return Number.isNaN(input.getTime()) ? Result.err(new ExpectedConstraintError("s.date.valid", "Invalid Date value", input, "expected !== NaN")) : Result.ok(input); + } + }; + + // src/validators/DateValidator.ts + var DateValidator = class extends BaseValidator { + lessThan(date) { + return this.addConstraint(dateLessThan(new Date(date))); + } + lessThanOrEqual(date) { + return this.addConstraint(dateLessThanOrEqual(new Date(date))); + } + greaterThan(date) { + return this.addConstraint(dateGreaterThan(new Date(date))); + } + greaterThanOrEqual(date) { + return this.addConstraint(dateGreaterThanOrEqual(new Date(date))); + } + equal(date) { + const resolved = new Date(date); + return Number.isNaN(resolved.getTime()) ? this.invalid : this.addConstraint(dateEqual(resolved)); + } + notEqual(date) { + const resolved = new Date(date); + return Number.isNaN(resolved.getTime()) ? this.valid : this.addConstraint(dateNotEqual(resolved)); + } + get valid() { + return this.addConstraint(dateValid); + } + get invalid() { + return this.addConstraint(dateInvalid); + } + handle(value) { + return value instanceof Date ? Result.ok(value) : Result.err(new ValidationError("s.date", "Expected a Date", value)); + } + }; + __name(DateValidator, "DateValidator"); + + // src/lib/errors/ExpectedValidationError.ts + var ExpectedValidationError = class extends ValidationError { + constructor(validator, message, given, expected) { + super(validator, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + validator: this.validator, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const validator = options.stylize(this.validator, "string"); + if (depth < 0) { + return options.stylize(`[ExpectedValidationError: ${validator}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const expected = inspect2(this.expected, newOptions).replace(/\n/g, padding); + const given = inspect2(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ExpectedValidationError", "special")} > ${validator}`; + const message = options.stylize(this.message, "regexp"); + const expectedBlock = ` + ${options.stylize("Expected:", "string")}${padding}${expected}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } + }; + __name(ExpectedValidationError, "ExpectedValidationError"); + + // src/validators/InstanceValidator.ts + var InstanceValidator = class extends BaseValidator { + constructor(expected, constraints = []) { + super(constraints); + this.expected = expected; + } + handle(value) { + return value instanceof this.expected ? Result.ok(value) : Result.err(new ExpectedValidationError("s.instance(V)", "Expected", value, this.expected)); + } + clone() { + return Reflect.construct(this.constructor, [this.expected, this.constraints]); + } + }; + __name(InstanceValidator, "InstanceValidator"); + + // src/validators/LiteralValidator.ts + var LiteralValidator = class extends BaseValidator { + constructor(literal, constraints = []) { + super(constraints); + this.expected = literal; + } + handle(value) { + return Object.is(value, this.expected) ? Result.ok(value) : Result.err(new ExpectedValidationError("s.literal(V)", "Expected values to be equals", value, this.expected)); + } + clone() { + return Reflect.construct(this.constructor, [this.expected, this.constraints]); + } + }; + __name(LiteralValidator, "LiteralValidator"); + + // src/validators/NeverValidator.ts + var NeverValidator = class extends BaseValidator { + handle(value) { + return Result.err(new ValidationError("s.never", "Expected a value to not be passed", value)); + } + }; + __name(NeverValidator, "NeverValidator"); + + // src/validators/NullishValidator.ts + var NullishValidator = class extends BaseValidator { + handle(value) { + return value === void 0 || value === null ? Result.ok(value) : Result.err(new ValidationError("s.nullish", "Expected undefined or null", value)); + } + }; + __name(NullishValidator, "NullishValidator"); + + // src/constraints/NumberConstraints.ts + function numberComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input, number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid number value", input, expected)); + } + }; + } + __name(numberComparator, "numberComparator"); + function numberLessThan(value) { + const expected = `expected < ${value}`; + return numberComparator(lessThan, "s.number.lessThan", expected, value); + } + __name(numberLessThan, "numberLessThan"); + function numberLessThanOrEqual(value) { + const expected = `expected <= ${value}`; + return numberComparator(lessThanOrEqual, "s.number.lessThanOrEqual", expected, value); + } + __name(numberLessThanOrEqual, "numberLessThanOrEqual"); + function numberGreaterThan(value) { + const expected = `expected > ${value}`; + return numberComparator(greaterThan, "s.number.greaterThan", expected, value); + } + __name(numberGreaterThan, "numberGreaterThan"); + function numberGreaterThanOrEqual(value) { + const expected = `expected >= ${value}`; + return numberComparator(greaterThanOrEqual, "s.number.greaterThanOrEqual", expected, value); + } + __name(numberGreaterThanOrEqual, "numberGreaterThanOrEqual"); + function numberEqual(value) { + const expected = `expected === ${value}`; + return numberComparator(equal, "s.number.equal", expected, value); + } + __name(numberEqual, "numberEqual"); + function numberNotEqual(value) { + const expected = `expected !== ${value}`; + return numberComparator(notEqual, "s.number.notEqual", expected, value); + } + __name(numberNotEqual, "numberNotEqual"); + var numberInt = { + run(input) { + return Number.isInteger(input) ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.number.int", "Given value is not an integer", input, "Number.isInteger(expected) to be true") + ); + } + }; + var numberSafeInt = { + run(input) { + return Number.isSafeInteger(input) ? Result.ok(input) : Result.err( + new ExpectedConstraintError( + "s.number.safeInt", + "Given value is not a safe integer", + input, + "Number.isSafeInteger(expected) to be true" + ) + ); + } + }; + var numberFinite = { + run(input) { + return Number.isFinite(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.finite", "Given value is not finite", input, "Number.isFinite(expected) to be true")); + } + }; + var numberNaN = { + run(input) { + return Number.isNaN(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.equal(NaN)", "Invalid number value", input, "expected === NaN")); + } + }; + var numberNotNaN = { + run(input) { + return Number.isNaN(input) ? Result.err(new ExpectedConstraintError("s.number.notEqual(NaN)", "Invalid number value", input, "expected !== NaN")) : Result.ok(input); + } + }; + function numberDivisibleBy(divider) { + const expected = `expected % ${divider} === 0`; + return { + run(input) { + return input % divider === 0 ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.divisibleBy", "Number is not divisible", input, expected)); + } + }; + } + __name(numberDivisibleBy, "numberDivisibleBy"); + + // src/validators/NumberValidator.ts + var NumberValidator = class extends BaseValidator { + lessThan(number) { + return this.addConstraint(numberLessThan(number)); + } + lessThanOrEqual(number) { + return this.addConstraint(numberLessThanOrEqual(number)); + } + greaterThan(number) { + return this.addConstraint(numberGreaterThan(number)); + } + greaterThanOrEqual(number) { + return this.addConstraint(numberGreaterThanOrEqual(number)); + } + equal(number) { + return Number.isNaN(number) ? this.addConstraint(numberNaN) : this.addConstraint(numberEqual(number)); + } + notEqual(number) { + return Number.isNaN(number) ? this.addConstraint(numberNotNaN) : this.addConstraint(numberNotEqual(number)); + } + get int() { + return this.addConstraint(numberInt); + } + get safeInt() { + return this.addConstraint(numberSafeInt); + } + get finite() { + return this.addConstraint(numberFinite); + } + get positive() { + return this.greaterThanOrEqual(0); + } + get negative() { + return this.lessThan(0); + } + divisibleBy(divider) { + return this.addConstraint(numberDivisibleBy(divider)); + } + get abs() { + return this.transform(Math.abs); + } + get sign() { + return this.transform(Math.sign); + } + get trunc() { + return this.transform(Math.trunc); + } + get floor() { + return this.transform(Math.floor); + } + get fround() { + return this.transform(Math.fround); + } + get round() { + return this.transform(Math.round); + } + get ceil() { + return this.transform(Math.ceil); + } + handle(value) { + return typeof value === "number" ? Result.ok(value) : Result.err(new ValidationError("s.number", "Expected a number primitive", value)); + } + }; + __name(NumberValidator, "NumberValidator"); + + // src/lib/errors/MissingPropertyError.ts + var MissingPropertyError = class extends BaseError { + constructor(property) { + super("A required property is missing"); + this.property = property; + } + toJSON() { + return { + name: this.name, + property: this.property + }; + } + [customInspectSymbolStackLess](depth, options) { + const property = options.stylize(this.property.toString(), "string"); + if (depth < 0) { + return options.stylize(`[MissingPropertyError: ${property}]`, "special"); + } + const header = `${options.stylize("MissingPropertyError", "special")} > ${property}`; + const message = options.stylize(this.message, "regexp"); + return `${header} + ${message}`; + } + }; + __name(MissingPropertyError, "MissingPropertyError"); + + // src/lib/errors/UnknownPropertyError.ts + var UnknownPropertyError = class extends BaseError { + constructor(property, value) { + super("Received unexpected property"); + this.property = property; + this.value = value; + } + toJSON() { + return { + name: this.name, + property: this.property, + value: this.value + }; + } + [customInspectSymbolStackLess](depth, options) { + const property = options.stylize(this.property.toString(), "string"); + if (depth < 0) { + return options.stylize(`[UnknownPropertyError: ${property}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = inspect2(this.value, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("UnknownPropertyError", "special")} > ${property}`; + const message = options.stylize(this.message, "regexp"); + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${givenBlock}`; + } + }; + __name(UnknownPropertyError, "UnknownPropertyError"); + + // src/validators/DefaultValidator.ts + var DefaultValidator = class extends BaseValidator { + constructor(validator, value, constraints = []) { + super(constraints); + this.validator = validator; + this.defaultValue = value; + } + default(value) { + const clone = this.clone(); + clone.defaultValue = value; + return clone; + } + handle(value) { + return typeof value === "undefined" ? Result.ok(getValue(this.defaultValue)) : this.validator["handle"](value); + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.defaultValue, this.constraints]); + } + }; + __name(DefaultValidator, "DefaultValidator"); + + // src/lib/errors/CombinedError.ts + var CombinedError = class extends BaseError { + constructor(errors) { + super("Received one or more errors"); + this.errors = errors; + } + [customInspectSymbolStackLess](depth, options) { + if (depth < 0) { + return options.stylize("[CombinedError]", "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const header = `${options.stylize("CombinedError", "special")} (${options.stylize(this.errors.length.toString(), "number")})`; + const message = options.stylize(this.message, "regexp"); + const errors = this.errors.map((error, i3) => { + const index = options.stylize((i3 + 1).toString(), "number"); + const body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\n/g, padding); + return ` ${index} ${body}`; + }).join("\n\n"); + return `${header} + ${message} + +${errors}`; + } + }; + __name(CombinedError, "CombinedError"); + + // src/validators/UnionValidator.ts + var UnionValidator = class extends BaseValidator { + constructor(validators, constraints = []) { + super(constraints); + this.validators = validators; + } + get optional() { + if (this.validators.length === 0) + return new UnionValidator([new LiteralValidator(void 0)], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) + return this.clone(); + if (validator.expected === null) { + return new UnionValidator( + [new NullishValidator(), ...this.validators.slice(1)], + this.constraints + ); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new LiteralValidator(void 0), ...this.validators]); + } + get required() { + if (this.validators.length === 0) + return this.clone(); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) + return new UnionValidator(this.validators.slice(1), this.constraints); + } else if (validator instanceof NullishValidator) { + return new UnionValidator([new LiteralValidator(null), ...this.validators.slice(1)], this.constraints); + } + return this.clone(); + } + get nullable() { + if (this.validators.length === 0) + return new UnionValidator([new LiteralValidator(null)], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === null) + return this.clone(); + if (validator.expected === void 0) { + return new UnionValidator( + [new NullishValidator(), ...this.validators.slice(1)], + this.constraints + ); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new LiteralValidator(null), ...this.validators]); + } + get nullish() { + if (this.validators.length === 0) + return new UnionValidator([new NullishValidator()], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === null || validator.expected === void 0) { + return new UnionValidator([new NullishValidator(), ...this.validators.slice(1)], this.constraints); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new NullishValidator(), ...this.validators]); + } + or(...predicates) { + return new UnionValidator([...this.validators, ...predicates]); + } + clone() { + return Reflect.construct(this.constructor, [this.validators, this.constraints]); + } + handle(value) { + const errors = []; + for (const validator of this.validators) { + const result = validator.run(value); + if (result.isOk()) + return result; + errors.push(result.error); + } + return Result.err(new CombinedError(errors)); + } + }; + __name(UnionValidator, "UnionValidator"); + + // src/validators/ObjectValidator.ts + var ObjectValidator = class extends BaseValidator { + constructor(shape, strategy = ObjectValidatorStrategy.Ignore, constraints = []) { + super(constraints); + this.keys = []; + this.requiredKeys = /* @__PURE__ */ new Map(); + this.possiblyUndefinedKeys = /* @__PURE__ */ new Map(); + this.possiblyUndefinedKeysWithDefaults = /* @__PURE__ */ new Map(); + this.shape = shape; + this.strategy = strategy; + switch (this.strategy) { + case ObjectValidatorStrategy.Ignore: + this.handleStrategy = (value) => this.handleIgnoreStrategy(value); + break; + case ObjectValidatorStrategy.Strict: { + this.handleStrategy = (value) => this.handleStrictStrategy(value); + break; + } + case ObjectValidatorStrategy.Passthrough: + this.handleStrategy = (value) => this.handlePassthroughStrategy(value); + break; + } + const shapeEntries = Object.entries(shape); + this.keys = shapeEntries.map(([key]) => key); + for (const [key, validator] of shapeEntries) { + if (validator instanceof UnionValidator) { + const [possiblyLiteralOrNullishPredicate] = validator["validators"]; + if (possiblyLiteralOrNullishPredicate instanceof NullishValidator) { + this.possiblyUndefinedKeys.set(key, validator); + } else if (possiblyLiteralOrNullishPredicate instanceof LiteralValidator) { + if (possiblyLiteralOrNullishPredicate.expected === void 0) { + this.possiblyUndefinedKeys.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof DefaultValidator) { + this.possiblyUndefinedKeysWithDefaults.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof NullishValidator) { + this.possiblyUndefinedKeys.set(key, validator); + } else if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) { + this.possiblyUndefinedKeys.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof DefaultValidator) { + this.possiblyUndefinedKeysWithDefaults.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } + } + get strict() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Strict, this.constraints]); + } + get ignore() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Ignore, this.constraints]); + } + get passthrough() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Passthrough, this.constraints]); + } + get partial() { + const shape = Object.fromEntries(this.keys.map((key) => [key, this.shape[key].optional])); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + get required() { + const shape = Object.fromEntries( + this.keys.map((key) => { + let validator = this.shape[key]; + if (validator instanceof UnionValidator) + validator = validator.required; + return [key, validator]; + }) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + extend(schema) { + const shape = { ...this.shape, ...schema instanceof ObjectValidator ? schema.shape : schema }; + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + pick(keys) { + const shape = Object.fromEntries( + keys.filter((key) => this.keys.includes(key)).map((key) => [key, this.shape[key]]) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + omit(keys) { + const shape = Object.fromEntries( + this.keys.filter((key) => !keys.includes(key)).map((key) => [key, this.shape[key]]) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + handle(value) { + const typeOfValue = typeof value; + if (typeOfValue !== "object") { + return Result.err(new ValidationError("s.object(T)", `Expected the value to be an object, but received ${typeOfValue} instead`, value)); + } + if (value === null) { + return Result.err(new ValidationError("s.object(T)", "Expected the value to not be null", value)); + } + if (Array.isArray(value)) { + return Result.err(new ValidationError("s.object(T)", "Expected the value to not be an array", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + for (const predicate of Object.values(this.shape)) { + predicate.setParent(this.parent ?? value); + } + return this.handleStrategy(value); + } + clone() { + return Reflect.construct(this.constructor, [this.shape, this.strategy, this.constraints]); + } + handleIgnoreStrategy(value) { + const errors = []; + const finalObject = {}; + const inputEntries = new Map(Object.entries(value)); + const runPredicate = /* @__PURE__ */ __name((key, predicate) => { + const result = predicate.run(value[key]); + if (result.isOk()) { + finalObject[key] = result.value; + } else { + const error = result.error; + errors.push([key, error]); + } + }, "runPredicate"); + for (const [key, predicate] of this.requiredKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } else { + errors.push([key, new MissingPropertyError(key)]); + } + } + for (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) { + inputEntries.delete(key); + runPredicate(key, validator); + } + if (inputEntries.size === 0) { + return errors.length === 0 ? Result.ok(finalObject) : Result.err(new CombinedPropertyError(errors)); + } + const checkInputEntriesInsteadOfSchemaKeys = this.possiblyUndefinedKeys.size > inputEntries.size; + if (checkInputEntriesInsteadOfSchemaKeys) { + for (const [key] of inputEntries) { + const predicate = this.possiblyUndefinedKeys.get(key); + if (predicate) { + runPredicate(key, predicate); + } + } + } else { + for (const [key, predicate] of this.possiblyUndefinedKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } + } + } + return errors.length === 0 ? Result.ok(finalObject) : Result.err(new CombinedPropertyError(errors)); + } + handleStrictStrategy(value) { + const errors = []; + const finalResult = {}; + const inputEntries = new Map(Object.entries(value)); + const runPredicate = /* @__PURE__ */ __name((key, predicate) => { + const result = predicate.run(value[key]); + if (result.isOk()) { + finalResult[key] = result.value; + } else { + const error = result.error; + errors.push([key, error]); + } + }, "runPredicate"); + for (const [key, predicate] of this.requiredKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } else { + errors.push([key, new MissingPropertyError(key)]); + } + } + for (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) { + inputEntries.delete(key); + runPredicate(key, validator); + } + for (const [key, predicate] of this.possiblyUndefinedKeys) { + if (inputEntries.size === 0) { + break; + } + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } + } + if (inputEntries.size !== 0) { + for (const [key, value2] of inputEntries.entries()) { + errors.push([key, new UnknownPropertyError(key, value2)]); + } + } + return errors.length === 0 ? Result.ok(finalResult) : Result.err(new CombinedPropertyError(errors)); + } + handlePassthroughStrategy(value) { + const result = this.handleIgnoreStrategy(value); + return result.isErr() ? result : Result.ok({ ...value, ...result.value }); + } + }; + __name(ObjectValidator, "ObjectValidator"); + var ObjectValidatorStrategy = /* @__PURE__ */ ((ObjectValidatorStrategy2) => { + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Ignore"] = 0] = "Ignore"; + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Strict"] = 1] = "Strict"; + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Passthrough"] = 2] = "Passthrough"; + return ObjectValidatorStrategy2; + })(ObjectValidatorStrategy || {}); + + // src/validators/PassthroughValidator.ts + var PassthroughValidator = class extends BaseValidator { + handle(value) { + return Result.ok(value); + } + }; + __name(PassthroughValidator, "PassthroughValidator"); + + // src/validators/RecordValidator.ts + var RecordValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(value) { + if (typeof value !== "object") { + return Result.err(new ValidationError("s.record(T)", "Expected an object", value)); + } + if (value === null) { + return Result.err(new ValidationError("s.record(T)", "Expected the value to not be null", value)); + } + if (Array.isArray(value)) { + return Result.err(new ValidationError("s.record(T)", "Expected the value to not be an array", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + const errors = []; + const transformed = {}; + for (const [key, val] of Object.entries(value)) { + const result = this.validator.run(val); + if (result.isOk()) + transformed[key] = result.value; + else + errors.push([key, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } + }; + __name(RecordValidator, "RecordValidator"); + + // src/validators/SetValidator.ts + var SetValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + if (!(values instanceof Set)) { + return Result.err(new ValidationError("s.set(T)", "Expected a set", values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = /* @__PURE__ */ new Set(); + for (const value of values) { + const result = this.validator.run(value); + if (result.isOk()) + transformed.add(result.value); + else + errors.push(result.error); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedError(errors)); + } + }; + __name(SetValidator, "SetValidator"); + + // src/constraints/util/emailValidator.ts + var accountRegex = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")$/; + function validateEmail(email) { + if (!email) + return false; + const atIndex = email.indexOf("@"); + if (atIndex === -1) + return false; + if (atIndex > 64) + return false; + const domainIndex = atIndex + 1; + if (email.includes("@", domainIndex)) + return false; + if (email.length - domainIndex > 255) + return false; + let dotIndex = email.indexOf(".", domainIndex); + if (dotIndex === -1) + return false; + let lastDotIndex = domainIndex; + do { + if (dotIndex - lastDotIndex > 63) + return false; + lastDotIndex = dotIndex + 1; + } while ((dotIndex = email.indexOf(".", lastDotIndex)) !== -1); + if (email.length - lastDotIndex > 63) + return false; + return accountRegex.test(email.slice(0, atIndex)) && validateEmailDomain(email.slice(domainIndex)); + } + __name(validateEmail, "validateEmail"); + function validateEmailDomain(domain) { + try { + return new URL(`http://${domain}`).hostname === domain; + } catch { + return false; + } + } + __name(validateEmailDomain, "validateEmailDomain"); + + // src/constraints/util/net.ts + var v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; + var v4Str = `(${v4Seg}[.]){3}${v4Seg}`; + var IPv4Reg = new RegExp(`^${v4Str}$`); + var v6Seg = "(?:[0-9a-fA-F]{1,4})"; + var IPv6Reg = new RegExp( + `^((?:${v6Seg}:){7}(?:${v6Seg}|:)|(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$` + ); + function isIPv4(s4) { + return IPv4Reg.test(s4); + } + __name(isIPv4, "isIPv4"); + function isIPv6(s4) { + return IPv6Reg.test(s4); + } + __name(isIPv6, "isIPv6"); + function isIP(s4) { + if (isIPv4(s4)) + return 4; + if (isIPv6(s4)) + return 6; + return 0; + } + __name(isIP, "isIP"); + + // src/constraints/util/phoneValidator.ts + var phoneNumberRegex = /^((?:\+|0{0,2})\d{1,2}\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/; + function validatePhoneNumber(input) { + return phoneNumberRegex.test(input); + } + __name(validatePhoneNumber, "validatePhoneNumber"); + + // src/lib/errors/MultiplePossibilitiesConstraintError.ts + var MultiplePossibilitiesConstraintError = class extends BaseConstraintError { + constructor(constraint, message, given, expected) { + super(constraint, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + constraint: this.constraint, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const constraint = options.stylize(this.constraint, "string"); + if (depth < 0) { + return options.stylize(`[MultiplePossibilitiesConstraintError: ${constraint}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const verticalLine = options.stylize("|", "undefined"); + const padding = ` + ${verticalLine} `; + const given = inspect2(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("MultiplePossibilitiesConstraintError", "special")} > ${constraint}`; + const message = options.stylize(this.message, "regexp"); + const expectedPadding = ` + ${verticalLine} - `; + const expectedBlock = ` + ${options.stylize("Expected any of the following:", "string")}${expectedPadding}${this.expected.map((possible) => options.stylize(possible, "boolean")).join(expectedPadding)}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } + }; + __name(MultiplePossibilitiesConstraintError, "MultiplePossibilitiesConstraintError"); + + // src/constraints/util/common/combinedResultFn.ts + function combinedErrorFn(...fns) { + switch (fns.length) { + case 0: + return () => null; + case 1: + return fns[0]; + case 2: { + const [fn0, fn1] = fns; + return (...params) => fn0(...params) || fn1(...params); + } + default: { + return (...params) => { + for (const fn of fns) { + const result = fn(...params); + if (result) + return result; + } + return null; + }; + } + } + } + __name(combinedErrorFn, "combinedErrorFn"); + + // src/constraints/util/urlValidators.ts + function createUrlValidators(options) { + const fns = []; + if (options?.allowedProtocols?.length) + fns.push(allowedProtocolsFn(options.allowedProtocols)); + if (options?.allowedDomains?.length) + fns.push(allowedDomainsFn(options.allowedDomains)); + return combinedErrorFn(...fns); + } + __name(createUrlValidators, "createUrlValidators"); + function allowedProtocolsFn(allowedProtocols) { + return (input, url) => allowedProtocols.includes(url.protocol) ? null : new MultiplePossibilitiesConstraintError("s.string.url", "Invalid URL protocol", input, allowedProtocols); + } + __name(allowedProtocolsFn, "allowedProtocolsFn"); + function allowedDomainsFn(allowedDomains) { + return (input, url) => allowedDomains.includes(url.hostname) ? null : new MultiplePossibilitiesConstraintError("s.string.url", "Invalid URL domain", input, allowedDomains); + } + __name(allowedDomainsFn, "allowedDomainsFn"); + + // src/constraints/StringConstraints.ts + function stringLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid string length", input, expected)); + } + }; + } + __name(stringLengthComparator, "stringLengthComparator"); + function stringLengthLessThan(length) { + const expected = `expected.length < ${length}`; + return stringLengthComparator(lessThan, "s.string.lengthLessThan", expected, length); + } + __name(stringLengthLessThan, "stringLengthLessThan"); + function stringLengthLessThanOrEqual(length) { + const expected = `expected.length <= ${length}`; + return stringLengthComparator(lessThanOrEqual, "s.string.lengthLessThanOrEqual", expected, length); + } + __name(stringLengthLessThanOrEqual, "stringLengthLessThanOrEqual"); + function stringLengthGreaterThan(length) { + const expected = `expected.length > ${length}`; + return stringLengthComparator(greaterThan, "s.string.lengthGreaterThan", expected, length); + } + __name(stringLengthGreaterThan, "stringLengthGreaterThan"); + function stringLengthGreaterThanOrEqual(length) { + const expected = `expected.length >= ${length}`; + return stringLengthComparator(greaterThanOrEqual, "s.string.lengthGreaterThanOrEqual", expected, length); + } + __name(stringLengthGreaterThanOrEqual, "stringLengthGreaterThanOrEqual"); + function stringLengthEqual(length) { + const expected = `expected.length === ${length}`; + return stringLengthComparator(equal, "s.string.lengthEqual", expected, length); + } + __name(stringLengthEqual, "stringLengthEqual"); + function stringLengthNotEqual(length) { + const expected = `expected.length !== ${length}`; + return stringLengthComparator(notEqual, "s.string.lengthNotEqual", expected, length); + } + __name(stringLengthNotEqual, "stringLengthNotEqual"); + function stringEmail() { + return { + run(input) { + return validateEmail(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.string.email", "Invalid email address", input, "expected to be an email address")); + } + }; + } + __name(stringEmail, "stringEmail"); + function stringRegexValidator(type, expected, regex) { + return { + run(input) { + return regex.test(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(type, "Invalid string format", input, expected)); + } + }; + } + __name(stringRegexValidator, "stringRegexValidator"); + function stringUrl(options) { + const validatorFn = createUrlValidators(options); + return { + run(input) { + let url; + try { + url = new URL(input); + } catch { + return Result.err(new ExpectedConstraintError("s.string.url", "Invalid URL", input, "expected to match an URL")); + } + const validatorFnResult = validatorFn(input, url); + if (validatorFnResult === null) + return Result.ok(input); + return Result.err(validatorFnResult); + } + }; + } + __name(stringUrl, "stringUrl"); + function stringIp(version) { + const ipVersion = version ? `v${version}` : ""; + const validatorFn = version === 4 ? isIPv4 : version === 6 ? isIPv6 : isIP; + const name = `s.string.ip${ipVersion}`; + const message = `Invalid IP${ipVersion} address`; + const expected = `expected to be an IP${ipVersion} address`; + return { + run(input) { + return validatorFn(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, message, input, expected)); + } + }; + } + __name(stringIp, "stringIp"); + function stringRegex(regex) { + return stringRegexValidator("s.string.regex", `expected ${regex}.test(expected) to be true`, regex); + } + __name(stringRegex, "stringRegex"); + function stringUuid({ version = 4, nullable = false } = {}) { + version ?? (version = "1-5"); + const regex = new RegExp( + `^(?:[0-9A-F]{8}-[0-9A-F]{4}-[${version}][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}${nullable ? "|00000000-0000-0000-0000-000000000000" : ""})$`, + "i" + ); + const expected = `expected to match UUID${typeof version === "number" ? `v${version}` : ` in range of ${version}`}`; + return stringRegexValidator("s.string.uuid", expected, regex); + } + __name(stringUuid, "stringUuid"); + function stringDate() { + return { + run(input) { + const time = Date.parse(input); + return Number.isNaN(time) ? Result.err( + new ExpectedConstraintError( + "s.string.date", + "Invalid date string", + input, + "expected to be a valid date string (in the ISO 8601 or ECMA-262 format)" + ) + ) : Result.ok(input); + } + }; + } + __name(stringDate, "stringDate"); + function stringPhone() { + return { + run(input) { + return validatePhoneNumber(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.string.phone", "Invalid phone number", input, "expected to be a phone number")); + } + }; + } + __name(stringPhone, "stringPhone"); + + // src/validators/StringValidator.ts + var StringValidator = class extends BaseValidator { + lengthLessThan(length) { + return this.addConstraint(stringLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(stringLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(stringLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(stringLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(stringLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(stringLengthNotEqual(length)); + } + get email() { + return this.addConstraint(stringEmail()); + } + url(options) { + return this.addConstraint(stringUrl(options)); + } + uuid(options) { + return this.addConstraint(stringUuid(options)); + } + regex(regex) { + return this.addConstraint(stringRegex(regex)); + } + get date() { + return this.addConstraint(stringDate()); + } + get ipv4() { + return this.ip(4); + } + get ipv6() { + return this.ip(6); + } + ip(version) { + return this.addConstraint(stringIp(version)); + } + phone() { + return this.addConstraint(stringPhone()); + } + handle(value) { + return typeof value === "string" ? Result.ok(value) : Result.err(new ValidationError("s.string", "Expected a string primitive", value)); + } + }; + __name(StringValidator, "StringValidator"); + + // src/validators/TupleValidator.ts + var TupleValidator = class extends BaseValidator { + constructor(validators, constraints = []) { + super(constraints); + this.validators = []; + this.validators = validators; + } + clone() { + return Reflect.construct(this.constructor, [this.validators, this.constraints]); + } + handle(values) { + if (!Array.isArray(values)) { + return Result.err(new ValidationError("s.tuple(T)", "Expected an array", values)); + } + if (values.length !== this.validators.length) { + return Result.err(new ValidationError("s.tuple(T)", `Expected an array of length ${this.validators.length}`, values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = []; + for (let i3 = 0; i3 < values.length; i3++) { + const result = this.validators[i3].run(values[i3]); + if (result.isOk()) + transformed.push(result.value); + else + errors.push([i3, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } + }; + __name(TupleValidator, "TupleValidator"); + + // src/validators/MapValidator.ts + var MapValidator = class extends BaseValidator { + constructor(keyValidator, valueValidator, constraints = []) { + super(constraints); + this.keyValidator = keyValidator; + this.valueValidator = valueValidator; + } + clone() { + return Reflect.construct(this.constructor, [this.keyValidator, this.valueValidator, this.constraints]); + } + handle(value) { + if (!(value instanceof Map)) { + return Result.err(new ValidationError("s.map(K, V)", "Expected a map", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + const errors = []; + const transformed = /* @__PURE__ */ new Map(); + for (const [key, val] of value.entries()) { + const keyResult = this.keyValidator.run(key); + const valueResult = this.valueValidator.run(val); + const { length } = errors; + if (keyResult.isErr()) + errors.push([key, keyResult.error]); + if (valueResult.isErr()) + errors.push([key, valueResult.error]); + if (errors.length === length) + transformed.set(keyResult.value, valueResult.value); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } + }; + __name(MapValidator, "MapValidator"); + + // src/validators/LazyValidator.ts + var LazyValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + return this.validator(values).run(values); + } + }; + __name(LazyValidator, "LazyValidator"); + + // src/lib/errors/UnknownEnumValueError.ts + var UnknownEnumValueError = class extends BaseError { + constructor(value, keys, enumMappings) { + super("Expected the value to be one of the following enum values:"); + this.value = value; + this.enumKeys = keys; + this.enumMappings = enumMappings; + } + toJSON() { + return { + name: this.name, + value: this.value, + enumKeys: this.enumKeys, + enumMappings: [...this.enumMappings.entries()] + }; + } + [customInspectSymbolStackLess](depth, options) { + const value = options.stylize(this.value.toString(), "string"); + if (depth < 0) { + return options.stylize(`[UnknownEnumValueError: ${value}]`, "special"); + } + const padding = ` + ${options.stylize("|", "undefined")} `; + const pairs = this.enumKeys.map((key) => { + const enumValue = this.enumMappings.get(key); + return `${options.stylize(key, "string")} or ${options.stylize( + enumValue.toString(), + typeof enumValue === "number" ? "number" : "string" + )}`; + }).join(padding); + const header = `${options.stylize("UnknownEnumValueError", "special")} > ${value}`; + const message = options.stylize(this.message, "regexp"); + const pairsBlock = `${padding}${pairs}`; + return `${header} + ${message} +${pairsBlock}`; + } + }; + __name(UnknownEnumValueError, "UnknownEnumValueError"); + + // src/validators/NativeEnumValidator.ts + var NativeEnumValidator = class extends BaseValidator { + constructor(enumShape) { + super(); + this.hasNumericElements = false; + this.enumMapping = /* @__PURE__ */ new Map(); + this.enumShape = enumShape; + this.enumKeys = Object.keys(enumShape).filter((key) => { + return typeof enumShape[enumShape[key]] !== "number"; + }); + for (const key of this.enumKeys) { + const enumValue = enumShape[key]; + this.enumMapping.set(key, enumValue); + this.enumMapping.set(enumValue, enumValue); + if (typeof enumValue === "number") { + this.hasNumericElements = true; + this.enumMapping.set(`${enumValue}`, enumValue); + } + } + } + handle(value) { + const typeOfValue = typeof value; + if (typeOfValue === "number") { + if (!this.hasNumericElements) { + return Result.err(new ValidationError("s.nativeEnum(T)", "Expected the value to be a string", value)); + } + } else if (typeOfValue !== "string") { + return Result.err(new ValidationError("s.nativeEnum(T)", "Expected the value to be a string or number", value)); + } + const casted = value; + const possibleEnumValue = this.enumMapping.get(casted); + return typeof possibleEnumValue === "undefined" ? Result.err(new UnknownEnumValueError(casted, this.enumKeys, this.enumMapping)) : Result.ok(possibleEnumValue); + } + clone() { + return Reflect.construct(this.constructor, [this.enumShape]); + } + }; + __name(NativeEnumValidator, "NativeEnumValidator"); + + // src/constraints/TypedArrayLengthConstraints.ts + function typedArrayByteLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.byteLength, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Typed Array byte length", input, expected)); + } + }; + } + __name(typedArrayByteLengthComparator, "typedArrayByteLengthComparator"); + function typedArrayByteLengthLessThan(value) { + const expected = `expected.byteLength < ${value}`; + return typedArrayByteLengthComparator(lessThan, "s.typedArray(T).byteLengthLessThan", expected, value); + } + __name(typedArrayByteLengthLessThan, "typedArrayByteLengthLessThan"); + function typedArrayByteLengthLessThanOrEqual(value) { + const expected = `expected.byteLength <= ${value}`; + return typedArrayByteLengthComparator(lessThanOrEqual, "s.typedArray(T).byteLengthLessThanOrEqual", expected, value); + } + __name(typedArrayByteLengthLessThanOrEqual, "typedArrayByteLengthLessThanOrEqual"); + function typedArrayByteLengthGreaterThan(value) { + const expected = `expected.byteLength > ${value}`; + return typedArrayByteLengthComparator(greaterThan, "s.typedArray(T).byteLengthGreaterThan", expected, value); + } + __name(typedArrayByteLengthGreaterThan, "typedArrayByteLengthGreaterThan"); + function typedArrayByteLengthGreaterThanOrEqual(value) { + const expected = `expected.byteLength >= ${value}`; + return typedArrayByteLengthComparator(greaterThanOrEqual, "s.typedArray(T).byteLengthGreaterThanOrEqual", expected, value); + } + __name(typedArrayByteLengthGreaterThanOrEqual, "typedArrayByteLengthGreaterThanOrEqual"); + function typedArrayByteLengthEqual(value) { + const expected = `expected.byteLength === ${value}`; + return typedArrayByteLengthComparator(equal, "s.typedArray(T).byteLengthEqual", expected, value); + } + __name(typedArrayByteLengthEqual, "typedArrayByteLengthEqual"); + function typedArrayByteLengthNotEqual(value) { + const expected = `expected.byteLength !== ${value}`; + return typedArrayByteLengthComparator(notEqual, "s.typedArray(T).byteLengthNotEqual", expected, value); + } + __name(typedArrayByteLengthNotEqual, "typedArrayByteLengthNotEqual"); + function typedArrayByteLengthRange(start, endBefore) { + const expected = `expected.byteLength >= ${start} && expected.byteLength < ${endBefore}`; + return { + run(input) { + return input.byteLength >= start && input.byteLength < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).byteLengthRange", "Invalid Typed Array byte length", input, expected)); + } + }; + } + __name(typedArrayByteLengthRange, "typedArrayByteLengthRange"); + function typedArrayByteLengthRangeInclusive(start, end) { + const expected = `expected.byteLength >= ${start} && expected.byteLength <= ${end}`; + return { + run(input) { + return input.byteLength >= start && input.byteLength <= end ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.typedArray(T).byteLengthRangeInclusive", "Invalid Typed Array byte length", input, expected) + ); + } + }; + } + __name(typedArrayByteLengthRangeInclusive, "typedArrayByteLengthRangeInclusive"); + function typedArrayByteLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.byteLength > ${startAfter} && expected.byteLength < ${endBefore}`; + return { + run(input) { + return input.byteLength > startAfter && input.byteLength < endBefore ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.typedArray(T).byteLengthRangeExclusive", "Invalid Typed Array byte length", input, expected) + ); + } + }; + } + __name(typedArrayByteLengthRangeExclusive, "typedArrayByteLengthRangeExclusive"); + function typedArrayLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Typed Array length", input, expected)); + } + }; + } + __name(typedArrayLengthComparator, "typedArrayLengthComparator"); + function typedArrayLengthLessThan(value) { + const expected = `expected.length < ${value}`; + return typedArrayLengthComparator(lessThan, "s.typedArray(T).lengthLessThan", expected, value); + } + __name(typedArrayLengthLessThan, "typedArrayLengthLessThan"); + function typedArrayLengthLessThanOrEqual(value) { + const expected = `expected.length <= ${value}`; + return typedArrayLengthComparator(lessThanOrEqual, "s.typedArray(T).lengthLessThanOrEqual", expected, value); + } + __name(typedArrayLengthLessThanOrEqual, "typedArrayLengthLessThanOrEqual"); + function typedArrayLengthGreaterThan(value) { + const expected = `expected.length > ${value}`; + return typedArrayLengthComparator(greaterThan, "s.typedArray(T).lengthGreaterThan", expected, value); + } + __name(typedArrayLengthGreaterThan, "typedArrayLengthGreaterThan"); + function typedArrayLengthGreaterThanOrEqual(value) { + const expected = `expected.length >= ${value}`; + return typedArrayLengthComparator(greaterThanOrEqual, "s.typedArray(T).lengthGreaterThanOrEqual", expected, value); + } + __name(typedArrayLengthGreaterThanOrEqual, "typedArrayLengthGreaterThanOrEqual"); + function typedArrayLengthEqual(value) { + const expected = `expected.length === ${value}`; + return typedArrayLengthComparator(equal, "s.typedArray(T).lengthEqual", expected, value); + } + __name(typedArrayLengthEqual, "typedArrayLengthEqual"); + function typedArrayLengthNotEqual(value) { + const expected = `expected.length !== ${value}`; + return typedArrayLengthComparator(notEqual, "s.typedArray(T).lengthNotEqual", expected, value); + } + __name(typedArrayLengthNotEqual, "typedArrayLengthNotEqual"); + function typedArrayLengthRange(start, endBefore) { + const expected = `expected.length >= ${start} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length >= start && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRange", "Invalid Typed Array length", input, expected)); + } + }; + } + __name(typedArrayLengthRange, "typedArrayLengthRange"); + function typedArrayLengthRangeInclusive(start, end) { + const expected = `expected.length >= ${start} && expected.length <= ${end}`; + return { + run(input) { + return input.length >= start && input.length <= end ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRangeInclusive", "Invalid Typed Array length", input, expected)); + } + }; + } + __name(typedArrayLengthRangeInclusive, "typedArrayLengthRangeInclusive"); + function typedArrayLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length > startAfter && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRangeExclusive", "Invalid Typed Array length", input, expected)); + } + }; + } + __name(typedArrayLengthRangeExclusive, "typedArrayLengthRangeExclusive"); + + // src/constraints/util/common/vowels.ts + var vowels = ["a", "e", "i", "o", "u"]; + var aOrAn = /* @__PURE__ */ __name((word) => { + return `${vowels.includes(word[0].toLowerCase()) ? "an" : "a"} ${word}`; + }, "aOrAn"); + + // src/constraints/util/typedArray.ts + var TypedArrays = { + Int8Array: (x2) => x2 instanceof Int8Array, + Uint8Array: (x2) => x2 instanceof Uint8Array, + Uint8ClampedArray: (x2) => x2 instanceof Uint8ClampedArray, + Int16Array: (x2) => x2 instanceof Int16Array, + Uint16Array: (x2) => x2 instanceof Uint16Array, + Int32Array: (x2) => x2 instanceof Int32Array, + Uint32Array: (x2) => x2 instanceof Uint32Array, + Float32Array: (x2) => x2 instanceof Float32Array, + Float64Array: (x2) => x2 instanceof Float64Array, + BigInt64Array: (x2) => x2 instanceof BigInt64Array, + BigUint64Array: (x2) => x2 instanceof BigUint64Array, + TypedArray: (x2) => ArrayBuffer.isView(x2) && !(x2 instanceof DataView) + }; + + // src/validators/TypedArrayValidator.ts + var TypedArrayValidator = class extends BaseValidator { + constructor(type, constraints = []) { + super(constraints); + this.type = type; + } + byteLengthLessThan(length) { + return this.addConstraint(typedArrayByteLengthLessThan(length)); + } + byteLengthLessThanOrEqual(length) { + return this.addConstraint(typedArrayByteLengthLessThanOrEqual(length)); + } + byteLengthGreaterThan(length) { + return this.addConstraint(typedArrayByteLengthGreaterThan(length)); + } + byteLengthGreaterThanOrEqual(length) { + return this.addConstraint(typedArrayByteLengthGreaterThanOrEqual(length)); + } + byteLengthEqual(length) { + return this.addConstraint(typedArrayByteLengthEqual(length)); + } + byteLengthNotEqual(length) { + return this.addConstraint(typedArrayByteLengthNotEqual(length)); + } + byteLengthRange(start, endBefore) { + return this.addConstraint(typedArrayByteLengthRange(start, endBefore)); + } + byteLengthRangeInclusive(startAt, endAt) { + return this.addConstraint(typedArrayByteLengthRangeInclusive(startAt, endAt)); + } + byteLengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(typedArrayByteLengthRangeExclusive(startAfter, endBefore)); + } + lengthLessThan(length) { + return this.addConstraint(typedArrayLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(typedArrayLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(typedArrayLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(typedArrayLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(typedArrayLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(typedArrayLengthNotEqual(length)); + } + lengthRange(start, endBefore) { + return this.addConstraint(typedArrayLengthRange(start, endBefore)); + } + lengthRangeInclusive(startAt, endAt) { + return this.addConstraint(typedArrayLengthRangeInclusive(startAt, endAt)); + } + lengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(typedArrayLengthRangeExclusive(startAfter, endBefore)); + } + clone() { + return Reflect.construct(this.constructor, [this.type, this.constraints]); + } + handle(value) { + return TypedArrays[this.type](value) ? Result.ok(value) : Result.err(new ValidationError("s.typedArray", `Expected ${aOrAn(this.type)}`, value)); + } + }; + __name(TypedArrayValidator, "TypedArrayValidator"); + + // src/lib/Shapes.ts + var Shapes = class { + get string() { + return new StringValidator(); + } + get number() { + return new NumberValidator(); + } + get bigint() { + return new BigIntValidator(); + } + get boolean() { + return new BooleanValidator(); + } + get date() { + return new DateValidator(); + } + object(shape) { + return new ObjectValidator(shape); + } + get undefined() { + return this.literal(void 0); + } + get null() { + return this.literal(null); + } + get nullish() { + return new NullishValidator(); + } + get any() { + return new PassthroughValidator(); + } + get unknown() { + return new PassthroughValidator(); + } + get never() { + return new NeverValidator(); + } + enum(...values) { + return this.union(...values.map((value) => this.literal(value))); + } + nativeEnum(enumShape) { + return new NativeEnumValidator(enumShape); + } + literal(value) { + if (value instanceof Date) + return this.date.equal(value); + return new LiteralValidator(value); + } + instance(expected) { + return new InstanceValidator(expected); + } + union(...validators) { + return new UnionValidator(validators); + } + array(validator) { + return new ArrayValidator(validator); + } + typedArray(type = "TypedArray") { + return new TypedArrayValidator(type); + } + get int8Array() { + return this.typedArray("Int8Array"); + } + get uint8Array() { + return this.typedArray("Uint8Array"); + } + get uint8ClampedArray() { + return this.typedArray("Uint8ClampedArray"); + } + get int16Array() { + return this.typedArray("Int16Array"); + } + get uint16Array() { + return this.typedArray("Uint16Array"); + } + get int32Array() { + return this.typedArray("Int32Array"); + } + get uint32Array() { + return this.typedArray("Uint32Array"); + } + get float32Array() { + return this.typedArray("Float32Array"); + } + get float64Array() { + return this.typedArray("Float64Array"); + } + get bigInt64Array() { + return this.typedArray("BigInt64Array"); + } + get bigUint64Array() { + return this.typedArray("BigUint64Array"); + } + tuple(validators) { + return new TupleValidator(validators); + } + set(validator) { + return new SetValidator(validator); + } + record(validator) { + return new RecordValidator(validator); + } + map(keyValidator, valueValidator) { + return new MapValidator(keyValidator, valueValidator); + } + lazy(validator) { + return new LazyValidator(validator); + } + }; + __name(Shapes, "Shapes"); + + // src/index.ts + var s3 = new Shapes(); + + exports.BaseError = BaseError; + exports.CombinedError = CombinedError; + exports.CombinedPropertyError = CombinedPropertyError; + exports.ExpectedConstraintError = ExpectedConstraintError; + exports.ExpectedValidationError = ExpectedValidationError; + exports.MissingPropertyError = MissingPropertyError; + exports.MultiplePossibilitiesConstraintError = MultiplePossibilitiesConstraintError; + exports.Result = Result; + exports.UnknownEnumValueError = UnknownEnumValueError; + exports.UnknownPropertyError = UnknownPropertyError; + exports.ValidationError = ValidationError; + exports.customInspectSymbol = customInspectSymbol; + exports.customInspectSymbolStackLess = customInspectSymbolStackLess; + exports.getGlobalValidationEnabled = getGlobalValidationEnabled; + exports.s = s3; + exports.setGlobalValidationEnabled = setGlobalValidationEnabled; + + return exports; + +})({}); +//# sourceMappingURL=out.js.map +//# sourceMappingURL=index.global.js.map \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/dist/index.global.js.map b/node_modules/@sapphire/shapeshift/dist/index.global.js.map new file mode 100644 index 0000000..aa77f50 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/dist/index.global.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../node_modules/lodash/isArray.js","../node_modules/lodash/_freeGlobal.js","../node_modules/lodash/_root.js","../node_modules/lodash/_Symbol.js","../node_modules/lodash/_getRawTag.js","../node_modules/lodash/_objectToString.js","../node_modules/lodash/_baseGetTag.js","../node_modules/lodash/isObjectLike.js","../node_modules/lodash/isSymbol.js","../node_modules/lodash/_isKey.js","../node_modules/lodash/isObject.js","../node_modules/lodash/isFunction.js","../node_modules/lodash/_coreJsData.js","../node_modules/lodash/_isMasked.js","../node_modules/lodash/_toSource.js","../node_modules/lodash/_baseIsNative.js","../node_modules/lodash/_getValue.js","../node_modules/lodash/_getNative.js","../node_modules/lodash/_nativeCreate.js","../node_modules/lodash/_hashClear.js","../node_modules/lodash/_hashDelete.js","../node_modules/lodash/_hashGet.js","../node_modules/lodash/_hashHas.js","../node_modules/lodash/_hashSet.js","../node_modules/lodash/_Hash.js","../node_modules/lodash/_listCacheClear.js","../node_modules/lodash/eq.js","../node_modules/lodash/_assocIndexOf.js","../node_modules/lodash/_listCacheDelete.js","../node_modules/lodash/_listCacheGet.js","../node_modules/lodash/_listCacheHas.js","../node_modules/lodash/_listCacheSet.js","../node_modules/lodash/_ListCache.js","../node_modules/lodash/_Map.js","../node_modules/lodash/_mapCacheClear.js","../node_modules/lodash/_isKeyable.js","../node_modules/lodash/_getMapData.js","../node_modules/lodash/_mapCacheDelete.js","../node_modules/lodash/_mapCacheGet.js","../node_modules/lodash/_mapCacheHas.js","../node_modules/lodash/_mapCacheSet.js","../node_modules/lodash/_MapCache.js","../node_modules/lodash/memoize.js","../node_modules/lodash/_memoizeCapped.js","../node_modules/lodash/_stringToPath.js","../node_modules/lodash/_arrayMap.js","../node_modules/lodash/_baseToString.js","../node_modules/lodash/toString.js","../node_modules/lodash/_castPath.js","../node_modules/lodash/_toKey.js","../node_modules/lodash/_baseGet.js","../node_modules/lodash/get.js","../node_modules/fast-deep-equal/es6/index.js","../node_modules/lodash/_setCacheAdd.js","../node_modules/lodash/_setCacheHas.js","../node_modules/lodash/_SetCache.js","../node_modules/lodash/_baseFindIndex.js","../node_modules/lodash/_baseIsNaN.js","../node_modules/lodash/_strictIndexOf.js","../node_modules/lodash/_baseIndexOf.js","../node_modules/lodash/_arrayIncludes.js","../node_modules/lodash/_arrayIncludesWith.js","../node_modules/lodash/_cacheHas.js","../node_modules/lodash/_Set.js","../node_modules/lodash/noop.js","../node_modules/lodash/_setToArray.js","../node_modules/lodash/_createSet.js","../node_modules/lodash/_baseUniq.js","../node_modules/lodash/uniqWith.js","../src/lib/configs.ts","../src/lib/Result.ts","../src/validators/util/getValue.ts","../src/constraints/ObjectConstrains.ts","node-modules-polyfills:node:util","../src/lib/errors/BaseError.ts","../src/lib/errors/BaseConstraintError.ts","../src/lib/errors/ExpectedConstraintError.ts","../src/validators/BaseValidator.ts","../src/constraints/util/isUnique.ts","../src/constraints/util/operators.ts","../src/constraints/ArrayConstraints.ts","../src/lib/errors/CombinedPropertyError.ts","../src/lib/errors/ValidationError.ts","../src/validators/ArrayValidator.ts","../src/constraints/BigIntConstraints.ts","../src/validators/BigIntValidator.ts","../src/constraints/BooleanConstraints.ts","../src/validators/BooleanValidator.ts","../src/constraints/DateConstraints.ts","../src/validators/DateValidator.ts","../src/lib/errors/ExpectedValidationError.ts","../src/validators/InstanceValidator.ts","../src/validators/LiteralValidator.ts","../src/validators/NeverValidator.ts","../src/validators/NullishValidator.ts","../src/constraints/NumberConstraints.ts","../src/validators/NumberValidator.ts","../src/lib/errors/MissingPropertyError.ts","../src/lib/errors/UnknownPropertyError.ts","../src/validators/DefaultValidator.ts","../src/lib/errors/CombinedError.ts","../src/validators/UnionValidator.ts","../src/validators/ObjectValidator.ts","../src/validators/PassthroughValidator.ts","../src/validators/RecordValidator.ts","../src/validators/SetValidator.ts","../src/constraints/util/emailValidator.ts","../src/constraints/util/net.ts","../src/constraints/util/phoneValidator.ts","../src/lib/errors/MultiplePossibilitiesConstraintError.ts","../src/constraints/util/common/combinedResultFn.ts","../src/constraints/util/urlValidators.ts","../src/constraints/StringConstraints.ts","../src/validators/StringValidator.ts","../src/validators/TupleValidator.ts","../src/validators/MapValidator.ts","../src/validators/LazyValidator.ts","../src/lib/errors/UnknownEnumValueError.ts","../src/validators/NativeEnumValidator.ts","../src/constraints/TypedArrayLengthConstraints.ts","../src/constraints/util/common/vowels.ts","../src/constraints/util/typedArray.ts","../src/validators/TypedArrayValidator.ts","../src/lib/Shapes.ts","../src/index.ts"],"names":["isArray","Symbol","e","isSymbol","isObject","isFunction","getValue","Map","get","equal","a","b","i","Set","uniqWith","s3","k","v","uniqueArray","fastDeepEqual","value","ObjectValidatorStrategy","s","x"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAuBA,QAAIA,WAAU,MAAM;AAEpB,WAAO,UAAUA;AAAA;AAAA;;;ACzBjB;AAAA;AACA,QAAI,aAAa,OAAO,cAAU,YAAY,cAAU,WAAO,WAAW,UAAU;AAEpF,WAAO,UAAU;AAAA;AAAA;;;ACHjB;AAAA;AAAA,QAAI,aAAa;AAGjB,QAAI,WAAW,OAAO,QAAQ,YAAY,QAAQ,KAAK,WAAW,UAAU;AAG5E,QAAI,OAAO,cAAc,YAAY,SAAS,aAAa,EAAE;AAE7D,WAAO,UAAU;AAAA;AAAA;;;ACRjB;AAAA;AAAA,QAAI,OAAO;AAGX,QAAIC,UAAS,KAAK;AAElB,WAAO,UAAUA;AAAA;AAAA;;;ACLjB;AAAA;AAAA,QAAIA,UAAS;AAGb,QAAI,cAAc,OAAO;AAGzB,QAAI,iBAAiB,YA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ACD;AA/Ia;;;ACzBN,IAAMD,KAAI,IAAI,OAAO","sourcesContent":["/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nmodule.exports = isKey;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var MapCache = require('./_MapCache');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nmodule.exports = memoize;\n","var memoize = require('./memoize');\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nmodule.exports = memoizeCapped;\n","var memoizeCapped = require('./_memoizeCapped');\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nmodule.exports = stringToPath;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nmodule.exports = arrayMap;\n","var Symbol = require('./_Symbol'),\n arrayMap = require('./_arrayMap'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = baseToString;\n","var baseToString = require('./_baseToString');\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nmodule.exports = toString;\n","var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","var castPath = require('./_castPath'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nmodule.exports = baseGet;\n","var baseGet = require('./_baseGet');\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nmodule.exports = get;\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n if ((a instanceof Map) && (b instanceof Map)) {\n if (a.size !== b.size) return false;\n for (i of a.entries())\n if (!b.has(i[0])) return false;\n for (i of a.entries())\n if (!equal(i[1], b.get(i[0]))) return false;\n return true;\n }\n\n if ((a instanceof Set) && (b instanceof Set)) {\n if (a.size !== b.size) return false;\n for (i of a.entries())\n if (!b.has(i[0])) return false;\n return true;\n }\n\n if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (a[i] !== b[i]) return false;\n return true;\n }\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nmodule.exports = setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n","var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nmodule.exports = baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = strictIndexOf;\n","var baseFindIndex = require('./_baseFindIndex'),\n baseIsNaN = require('./_baseIsNaN'),\n strictIndexOf = require('./_strictIndexOf');\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nmodule.exports = baseIndexOf;\n","var baseIndexOf = require('./_baseIndexOf');\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nmodule.exports = arrayIncludes;\n","/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arrayIncludesWith;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nmodule.exports = noop;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nmodule.exports = setToArray;\n","var Set = require('./_Set'),\n noop = require('./noop'),\n setToArray = require('./_setToArray');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n};\n\nmodule.exports = createSet;\n","var SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n cacheHas = require('./_cacheHas'),\n createSet = require('./_createSet'),\n setToArray = require('./_setToArray');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\nfunction baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseUniq;\n","var baseUniq = require('./_baseUniq');\n\n/**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\nfunction uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n}\n\nmodule.exports = uniqWith;\n","let validationEnabled = true;\n\n/**\n * Sets whether validators should run on the input, or if the input should be passed through.\n * @param enabled Whether validation should be done on inputs\n */\nexport function setGlobalValidationEnabled(enabled: boolean) {\n\tvalidationEnabled = enabled;\n}\n\n/**\n * @returns Whether validation is enabled\n */\nexport function getGlobalValidationEnabled() {\n\treturn validationEnabled;\n}\n","export class Result {\n\tpublic readonly success: boolean;\n\tpublic readonly value?: T;\n\tpublic readonly error?: E;\n\n\tprivate constructor(success: boolean, value?: T, error?: E) {\n\t\tthis.success = success;\n\t\tif (success) {\n\t\t\tthis.value = value;\n\t\t} else {\n\t\t\tthis.error = error;\n\t\t}\n\t}\n\n\tpublic isOk(): this is { success: true; value: T } {\n\t\treturn this.success;\n\t}\n\n\tpublic isErr(): this is { success: false; error: E } {\n\t\treturn !this.success;\n\t}\n\n\tpublic unwrap(): T {\n\t\tif (this.isOk()) return this.value;\n\t\tthrow this.error as Error;\n\t}\n\n\tpublic static ok(value: T): Result {\n\t\treturn new Result(true, value);\n\t}\n\n\tpublic static err(error: E): Result {\n\t\treturn new Result(false, undefined, error);\n\t}\n}\n","// https://github.com/microsoft/TypeScript/issues/37663\ntype Fn = (...args: unknown[]) => unknown;\n\nexport function getValue : T>(valueOrFn: T): U {\n\treturn typeof valueOrFn === 'function' ? valueOrFn() : valueOrFn;\n}\n","import get from 'lodash/get.js';\nimport { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { BaseValidator } from '../type-exports';\nimport type { IConstraint } from './type-exports';\n\nexport type ObjectConstraintName = `s.object(T.when)`;\n\nexport type WhenKey = PropertyKey | PropertyKey[];\n\nexport interface WhenOptions, Key extends WhenKey> {\n\tis?: boolean | ((value: Key extends Array ? any[] : any) => boolean);\n\tthen: (predicate: T) => T;\n\totherwise?: (predicate: T) => T;\n}\n\nexport function whenConstraint, I, Key extends WhenKey>(\n\tkey: Key,\n\toptions: WhenOptions,\n\tvalidator: T\n): IConstraint {\n\treturn {\n\t\trun(input: I, parent?: any) {\n\t\t\tif (!parent) {\n\t\t\t\treturn Result.err(new ExpectedConstraintError('s.object(T.when)', 'Validator has no parent', parent, 'Validator to have a parent'));\n\t\t\t}\n\n\t\t\tconst isKeyArray = Array.isArray(key);\n\n\t\t\tconst value = isKeyArray ? key.map((k) => get(parent, k)) : get(parent, key);\n\n\t\t\tconst predicate = resolveBooleanIs(options, value, isKeyArray) ? options.then : options.otherwise;\n\n\t\t\tif (predicate) {\n\t\t\t\treturn predicate(validator).run(input) as Result>;\n\t\t\t}\n\n\t\t\treturn Result.ok(input);\n\t\t}\n\t};\n}\n\nfunction resolveBooleanIs, Key extends WhenKey>(options: WhenOptions, value: any, isKeyArray: boolean) {\n\tif (options.is === undefined) {\n\t\treturn isKeyArray ? !value.some((val: any) => !val) : Boolean(value);\n\t}\n\n\tif (typeof options.is === 'function') {\n\t\treturn options.is(value);\n\t}\n\n\treturn value === options.is;\n}\n","// node_modules/@jspm/core/nodelibs/browser/chunk-5decc758.js\nvar e;\nvar t;\nvar n;\nvar r = \"undefined\" != typeof globalThis ? globalThis : \"undefined\" != typeof self ? self : global;\nvar o = e = {};\nfunction i() {\n throw new Error(\"setTimeout has not been defined\");\n}\nfunction u() {\n throw new Error(\"clearTimeout has not been defined\");\n}\nfunction c(e3) {\n if (t === setTimeout)\n return setTimeout(e3, 0);\n if ((t === i || !t) && setTimeout)\n return t = setTimeout, setTimeout(e3, 0);\n try {\n return t(e3, 0);\n } catch (n3) {\n try {\n return t.call(null, e3, 0);\n } catch (n4) {\n return t.call(this || r, e3, 0);\n }\n }\n}\n!function() {\n try {\n t = \"function\" == typeof setTimeout ? setTimeout : i;\n } catch (e3) {\n t = i;\n }\n try {\n n = \"function\" == typeof clearTimeout ? clearTimeout : u;\n } catch (e3) {\n n = u;\n }\n}();\nvar l;\nvar s = [];\nvar f = false;\nvar a = -1;\nfunction h() {\n f && l && (f = false, l.length ? s = l.concat(s) : a = -1, s.length && d());\n}\nfunction d() {\n if (!f) {\n var e3 = c(h);\n f = true;\n for (var t3 = s.length; t3; ) {\n for (l = s, s = []; ++a < t3; )\n l && l[a].run();\n a = -1, t3 = s.length;\n }\n l = null, f = false, function(e4) {\n if (n === clearTimeout)\n return clearTimeout(e4);\n if ((n === u || !n) && clearTimeout)\n return n = clearTimeout, clearTimeout(e4);\n try {\n n(e4);\n } catch (t4) {\n try {\n return n.call(null, e4);\n } catch (t5) {\n return n.call(this || r, e4);\n }\n }\n }(e3);\n }\n}\nfunction m(e3, t3) {\n (this || r).fun = e3, (this || r).array = t3;\n}\nfunction p() {\n}\no.nextTick = function(e3) {\n var t3 = new Array(arguments.length - 1);\n if (arguments.length > 1)\n for (var n3 = 1; n3 < arguments.length; n3++)\n t3[n3 - 1] = arguments[n3];\n s.push(new m(e3, t3)), 1 !== s.length || f || c(d);\n}, m.prototype.run = function() {\n (this || r).fun.apply(null, (this || r).array);\n}, o.title = \"browser\", o.browser = true, o.env = {}, o.argv = [], o.version = \"\", o.versions = {}, o.on = p, o.addListener = p, o.once = p, o.off = p, o.removeListener = p, o.removeAllListeners = p, o.emit = p, o.prependListener = p, o.prependOnceListener = p, o.listeners = function(e3) {\n return [];\n}, o.binding = function(e3) {\n throw new Error(\"process.binding is not supported\");\n}, o.cwd = function() {\n return \"/\";\n}, o.chdir = function(e3) {\n throw new Error(\"process.chdir is not supported\");\n}, o.umask = function() {\n return 0;\n};\nvar T = e;\nT.addListener;\nT.argv;\nT.binding;\nT.browser;\nT.chdir;\nT.cwd;\nT.emit;\nT.env;\nT.listeners;\nT.nextTick;\nT.off;\nT.on;\nT.once;\nT.prependListener;\nT.prependOnceListener;\nT.removeAllListeners;\nT.removeListener;\nT.title;\nT.umask;\nT.version;\nT.versions;\n\n// node_modules/@jspm/core/nodelibs/browser/chunk-b4205b57.js\nvar t2 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.toStringTag;\nvar e2 = Object.prototype.toString;\nvar o2 = function(o3) {\n return !(t2 && o3 && \"object\" == typeof o3 && Symbol.toStringTag in o3) && \"[object Arguments]\" === e2.call(o3);\n};\nvar n2 = function(t3) {\n return !!o2(t3) || null !== t3 && \"object\" == typeof t3 && \"number\" == typeof t3.length && t3.length >= 0 && \"[object Array]\" !== e2.call(t3) && \"[object Function]\" === e2.call(t3.callee);\n};\nvar r2 = function() {\n return o2(arguments);\n}();\no2.isLegacyArguments = n2;\nvar l2 = r2 ? o2 : n2;\nvar t$1 = Object.prototype.toString;\nvar o$1 = Function.prototype.toString;\nvar n$1 = /^\\s*(?:function)?\\*/;\nvar e$1 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.toStringTag;\nvar r$1 = Object.getPrototypeOf;\nvar c2 = function() {\n if (!e$1)\n return false;\n try {\n return Function(\"return function*() {}\")();\n } catch (t3) {\n }\n}();\nvar u2 = c2 ? r$1(c2) : {};\nvar i2 = function(c3) {\n return \"function\" == typeof c3 && (!!n$1.test(o$1.call(c3)) || (e$1 ? r$1(c3) === u2 : \"[object GeneratorFunction]\" === t$1.call(c3)));\n};\nvar t$2 = \"function\" == typeof Object.create ? function(t3, e3) {\n e3 && (t3.super_ = e3, t3.prototype = Object.create(e3.prototype, { constructor: { value: t3, enumerable: false, writable: true, configurable: true } }));\n} : function(t3, e3) {\n if (e3) {\n t3.super_ = e3;\n var o3 = function() {\n };\n o3.prototype = e3.prototype, t3.prototype = new o3(), t3.prototype.constructor = t3;\n }\n};\nvar i$1 = function(e3) {\n return e3 && \"object\" == typeof e3 && \"function\" == typeof e3.copy && \"function\" == typeof e3.fill && \"function\" == typeof e3.readUInt8;\n};\nvar o$2 = {};\nvar u$1 = i$1;\nvar f2 = l2;\nvar a2 = i2;\nfunction c$1(e3) {\n return e3.call.bind(e3);\n}\nvar s2 = \"undefined\" != typeof BigInt;\nvar p2 = \"undefined\" != typeof Symbol;\nvar y = p2 && void 0 !== Symbol.toStringTag;\nvar l$1 = \"undefined\" != typeof Uint8Array;\nvar d2 = \"undefined\" != typeof ArrayBuffer;\nif (l$1 && y)\n var g = Object.getPrototypeOf(Uint8Array.prototype), b = c$1(Object.getOwnPropertyDescriptor(g, Symbol.toStringTag).get);\nvar m2 = c$1(Object.prototype.toString);\nvar h2 = c$1(Number.prototype.valueOf);\nvar j = c$1(String.prototype.valueOf);\nvar A = c$1(Boolean.prototype.valueOf);\nif (s2)\n var w = c$1(BigInt.prototype.valueOf);\nif (p2)\n var v = c$1(Symbol.prototype.valueOf);\nfunction O(e3, t3) {\n if (\"object\" != typeof e3)\n return false;\n try {\n return t3(e3), true;\n } catch (e4) {\n return false;\n }\n}\nfunction S(e3) {\n return l$1 && y ? void 0 !== b(e3) : B(e3) || k(e3) || E(e3) || D(e3) || U(e3) || P(e3) || x(e3) || I(e3) || M(e3) || z(e3) || F(e3);\n}\nfunction B(e3) {\n return l$1 && y ? \"Uint8Array\" === b(e3) : \"[object Uint8Array]\" === m2(e3) || u$1(e3) && void 0 !== e3.buffer;\n}\nfunction k(e3) {\n return l$1 && y ? \"Uint8ClampedArray\" === b(e3) : \"[object Uint8ClampedArray]\" === m2(e3);\n}\nfunction E(e3) {\n return l$1 && y ? \"Uint16Array\" === b(e3) : \"[object Uint16Array]\" === m2(e3);\n}\nfunction D(e3) {\n return l$1 && y ? \"Uint32Array\" === b(e3) : \"[object Uint32Array]\" === m2(e3);\n}\nfunction U(e3) {\n return l$1 && y ? \"Int8Array\" === b(e3) : \"[object Int8Array]\" === m2(e3);\n}\nfunction P(e3) {\n return l$1 && y ? \"Int16Array\" === b(e3) : \"[object Int16Array]\" === m2(e3);\n}\nfunction x(e3) {\n return l$1 && y ? \"Int32Array\" === b(e3) : \"[object Int32Array]\" === m2(e3);\n}\nfunction I(e3) {\n return l$1 && y ? \"Float32Array\" === b(e3) : \"[object Float32Array]\" === m2(e3);\n}\nfunction M(e3) {\n return l$1 && y ? \"Float64Array\" === b(e3) : \"[object Float64Array]\" === m2(e3);\n}\nfunction z(e3) {\n return l$1 && y ? \"BigInt64Array\" === b(e3) : \"[object BigInt64Array]\" === m2(e3);\n}\nfunction F(e3) {\n return l$1 && y ? \"BigUint64Array\" === b(e3) : \"[object BigUint64Array]\" === m2(e3);\n}\nfunction T2(e3) {\n return \"[object Map]\" === m2(e3);\n}\nfunction N(e3) {\n return \"[object Set]\" === m2(e3);\n}\nfunction W(e3) {\n return \"[object WeakMap]\" === m2(e3);\n}\nfunction $(e3) {\n return \"[object WeakSet]\" === m2(e3);\n}\nfunction C(e3) {\n return \"[object ArrayBuffer]\" === m2(e3);\n}\nfunction V(e3) {\n return \"undefined\" != typeof ArrayBuffer && (C.working ? C(e3) : e3 instanceof ArrayBuffer);\n}\nfunction G(e3) {\n return \"[object DataView]\" === m2(e3);\n}\nfunction R(e3) {\n return \"undefined\" != typeof DataView && (G.working ? G(e3) : e3 instanceof DataView);\n}\nfunction J(e3) {\n return \"[object SharedArrayBuffer]\" === m2(e3);\n}\nfunction _(e3) {\n return \"undefined\" != typeof SharedArrayBuffer && (J.working ? J(e3) : e3 instanceof SharedArrayBuffer);\n}\nfunction H(e3) {\n return O(e3, h2);\n}\nfunction Z(e3) {\n return O(e3, j);\n}\nfunction q(e3) {\n return O(e3, A);\n}\nfunction K(e3) {\n return s2 && O(e3, w);\n}\nfunction L(e3) {\n return p2 && O(e3, v);\n}\no$2.isArgumentsObject = f2, o$2.isGeneratorFunction = a2, o$2.isPromise = function(e3) {\n return \"undefined\" != typeof Promise && e3 instanceof Promise || null !== e3 && \"object\" == typeof e3 && \"function\" == typeof e3.then && \"function\" == typeof e3.catch;\n}, o$2.isArrayBufferView = function(e3) {\n return d2 && ArrayBuffer.isView ? ArrayBuffer.isView(e3) : S(e3) || R(e3);\n}, o$2.isTypedArray = S, o$2.isUint8Array = B, o$2.isUint8ClampedArray = k, o$2.isUint16Array = E, o$2.isUint32Array = D, o$2.isInt8Array = U, o$2.isInt16Array = P, o$2.isInt32Array = x, o$2.isFloat32Array = I, o$2.isFloat64Array = M, o$2.isBigInt64Array = z, o$2.isBigUint64Array = F, T2.working = \"undefined\" != typeof Map && T2(/* @__PURE__ */ new Map()), o$2.isMap = function(e3) {\n return \"undefined\" != typeof Map && (T2.working ? T2(e3) : e3 instanceof Map);\n}, N.working = \"undefined\" != typeof Set && N(/* @__PURE__ */ new Set()), o$2.isSet = function(e3) {\n return \"undefined\" != typeof Set && (N.working ? N(e3) : e3 instanceof Set);\n}, W.working = \"undefined\" != typeof WeakMap && W(/* @__PURE__ */ new WeakMap()), o$2.isWeakMap = function(e3) {\n return \"undefined\" != typeof WeakMap && (W.working ? W(e3) : e3 instanceof WeakMap);\n}, $.working = \"undefined\" != typeof WeakSet && $(/* @__PURE__ */ new WeakSet()), o$2.isWeakSet = function(e3) {\n return $(e3);\n}, C.working = \"undefined\" != typeof ArrayBuffer && C(new ArrayBuffer()), o$2.isArrayBuffer = V, G.working = \"undefined\" != typeof ArrayBuffer && \"undefined\" != typeof DataView && G(new DataView(new ArrayBuffer(1), 0, 1)), o$2.isDataView = R, J.working = \"undefined\" != typeof SharedArrayBuffer && J(new SharedArrayBuffer()), o$2.isSharedArrayBuffer = _, o$2.isAsyncFunction = function(e3) {\n return \"[object AsyncFunction]\" === m2(e3);\n}, o$2.isMapIterator = function(e3) {\n return \"[object Map Iterator]\" === m2(e3);\n}, o$2.isSetIterator = function(e3) {\n return \"[object Set Iterator]\" === m2(e3);\n}, o$2.isGeneratorObject = function(e3) {\n return \"[object Generator]\" === m2(e3);\n}, o$2.isWebAssemblyCompiledModule = function(e3) {\n return \"[object WebAssembly.Module]\" === m2(e3);\n}, o$2.isNumberObject = H, o$2.isStringObject = Z, o$2.isBooleanObject = q, o$2.isBigIntObject = K, o$2.isSymbolObject = L, o$2.isBoxedPrimitive = function(e3) {\n return H(e3) || Z(e3) || q(e3) || K(e3) || L(e3);\n}, o$2.isAnyArrayBuffer = function(e3) {\n return l$1 && (V(e3) || _(e3));\n}, [\"isProxy\", \"isExternal\", \"isModuleNamespaceObject\"].forEach(function(e3) {\n Object.defineProperty(o$2, e3, { enumerable: false, value: function() {\n throw new Error(e3 + \" is not supported in userland\");\n } });\n});\nvar Q = \"undefined\" != typeof globalThis ? globalThis : \"undefined\" != typeof self ? self : global;\nvar X = {};\nvar Y = T;\nvar ee = Object.getOwnPropertyDescriptors || function(e3) {\n for (var t3 = Object.keys(e3), r3 = {}, n3 = 0; n3 < t3.length; n3++)\n r3[t3[n3]] = Object.getOwnPropertyDescriptor(e3, t3[n3]);\n return r3;\n};\nvar te = /%[sdj%]/g;\nX.format = function(e3) {\n if (!ge(e3)) {\n for (var t3 = [], r3 = 0; r3 < arguments.length; r3++)\n t3.push(oe(arguments[r3]));\n return t3.join(\" \");\n }\n r3 = 1;\n for (var n3 = arguments, i3 = n3.length, o3 = String(e3).replace(te, function(e4) {\n if (\"%%\" === e4)\n return \"%\";\n if (r3 >= i3)\n return e4;\n switch (e4) {\n case \"%s\":\n return String(n3[r3++]);\n case \"%d\":\n return Number(n3[r3++]);\n case \"%j\":\n try {\n return JSON.stringify(n3[r3++]);\n } catch (e5) {\n return \"[Circular]\";\n }\n default:\n return e4;\n }\n }), u3 = n3[r3]; r3 < i3; u3 = n3[++r3])\n le(u3) || !he(u3) ? o3 += \" \" + u3 : o3 += \" \" + oe(u3);\n return o3;\n}, X.deprecate = function(e3, t3) {\n if (void 0 !== Y && true === Y.noDeprecation)\n return e3;\n if (void 0 === Y)\n return function() {\n return X.deprecate(e3, t3).apply(this || Q, arguments);\n };\n var r3 = false;\n return function() {\n if (!r3) {\n if (Y.throwDeprecation)\n throw new Error(t3);\n Y.traceDeprecation ? console.trace(t3) : console.error(t3), r3 = true;\n }\n return e3.apply(this || Q, arguments);\n };\n};\nvar re = {};\nvar ne = /^$/;\nif (Y.env.NODE_DEBUG) {\n ie = Y.env.NODE_DEBUG;\n ie = ie.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\").replace(/\\*/g, \".*\").replace(/,/g, \"$|^\").toUpperCase(), ne = new RegExp(\"^\" + ie + \"$\", \"i\");\n}\nvar ie;\nfunction oe(e3, t3) {\n var r3 = { seen: [], stylize: fe };\n return arguments.length >= 3 && (r3.depth = arguments[2]), arguments.length >= 4 && (r3.colors = arguments[3]), ye(t3) ? r3.showHidden = t3 : t3 && X._extend(r3, t3), be(r3.showHidden) && (r3.showHidden = false), be(r3.depth) && (r3.depth = 2), be(r3.colors) && (r3.colors = false), be(r3.customInspect) && (r3.customInspect = true), r3.colors && (r3.stylize = ue), ae(r3, e3, r3.depth);\n}\nfunction ue(e3, t3) {\n var r3 = oe.styles[t3];\n return r3 ? \"\\x1B[\" + oe.colors[r3][0] + \"m\" + e3 + \"\\x1B[\" + oe.colors[r3][1] + \"m\" : e3;\n}\nfunction fe(e3, t3) {\n return e3;\n}\nfunction ae(e3, t3, r3) {\n if (e3.customInspect && t3 && we(t3.inspect) && t3.inspect !== X.inspect && (!t3.constructor || t3.constructor.prototype !== t3)) {\n var n3 = t3.inspect(r3, e3);\n return ge(n3) || (n3 = ae(e3, n3, r3)), n3;\n }\n var i3 = function(e4, t4) {\n if (be(t4))\n return e4.stylize(\"undefined\", \"undefined\");\n if (ge(t4)) {\n var r4 = \"'\" + JSON.stringify(t4).replace(/^\"|\"$/g, \"\").replace(/'/g, \"\\\\'\").replace(/\\\\\"/g, '\"') + \"'\";\n return e4.stylize(r4, \"string\");\n }\n if (de(t4))\n return e4.stylize(\"\" + t4, \"number\");\n if (ye(t4))\n return e4.stylize(\"\" + t4, \"boolean\");\n if (le(t4))\n return e4.stylize(\"null\", \"null\");\n }(e3, t3);\n if (i3)\n return i3;\n var o3 = Object.keys(t3), u3 = function(e4) {\n var t4 = {};\n return e4.forEach(function(e5, r4) {\n t4[e5] = true;\n }), t4;\n }(o3);\n if (e3.showHidden && (o3 = Object.getOwnPropertyNames(t3)), Ae(t3) && (o3.indexOf(\"message\") >= 0 || o3.indexOf(\"description\") >= 0))\n return ce(t3);\n if (0 === o3.length) {\n if (we(t3)) {\n var f3 = t3.name ? \": \" + t3.name : \"\";\n return e3.stylize(\"[Function\" + f3 + \"]\", \"special\");\n }\n if (me(t3))\n return e3.stylize(RegExp.prototype.toString.call(t3), \"regexp\");\n if (je(t3))\n return e3.stylize(Date.prototype.toString.call(t3), \"date\");\n if (Ae(t3))\n return ce(t3);\n }\n var a3, c3 = \"\", s3 = false, p3 = [\"{\", \"}\"];\n (pe(t3) && (s3 = true, p3 = [\"[\", \"]\"]), we(t3)) && (c3 = \" [Function\" + (t3.name ? \": \" + t3.name : \"\") + \"]\");\n return me(t3) && (c3 = \" \" + RegExp.prototype.toString.call(t3)), je(t3) && (c3 = \" \" + Date.prototype.toUTCString.call(t3)), Ae(t3) && (c3 = \" \" + ce(t3)), 0 !== o3.length || s3 && 0 != t3.length ? r3 < 0 ? me(t3) ? e3.stylize(RegExp.prototype.toString.call(t3), \"regexp\") : e3.stylize(\"[Object]\", \"special\") : (e3.seen.push(t3), a3 = s3 ? function(e4, t4, r4, n4, i4) {\n for (var o4 = [], u4 = 0, f4 = t4.length; u4 < f4; ++u4)\n ke(t4, String(u4)) ? o4.push(se(e4, t4, r4, n4, String(u4), true)) : o4.push(\"\");\n return i4.forEach(function(i5) {\n i5.match(/^\\d+$/) || o4.push(se(e4, t4, r4, n4, i5, true));\n }), o4;\n }(e3, t3, r3, u3, o3) : o3.map(function(n4) {\n return se(e3, t3, r3, u3, n4, s3);\n }), e3.seen.pop(), function(e4, t4, r4) {\n var n4 = 0;\n if (e4.reduce(function(e5, t5) {\n return n4++, t5.indexOf(\"\\n\") >= 0 && n4++, e5 + t5.replace(/\\u001b\\[\\d\\d?m/g, \"\").length + 1;\n }, 0) > 60)\n return r4[0] + (\"\" === t4 ? \"\" : t4 + \"\\n \") + \" \" + e4.join(\",\\n \") + \" \" + r4[1];\n return r4[0] + t4 + \" \" + e4.join(\", \") + \" \" + r4[1];\n }(a3, c3, p3)) : p3[0] + c3 + p3[1];\n}\nfunction ce(e3) {\n return \"[\" + Error.prototype.toString.call(e3) + \"]\";\n}\nfunction se(e3, t3, r3, n3, i3, o3) {\n var u3, f3, a3;\n if ((a3 = Object.getOwnPropertyDescriptor(t3, i3) || { value: t3[i3] }).get ? f3 = a3.set ? e3.stylize(\"[Getter/Setter]\", \"special\") : e3.stylize(\"[Getter]\", \"special\") : a3.set && (f3 = e3.stylize(\"[Setter]\", \"special\")), ke(n3, i3) || (u3 = \"[\" + i3 + \"]\"), f3 || (e3.seen.indexOf(a3.value) < 0 ? (f3 = le(r3) ? ae(e3, a3.value, null) : ae(e3, a3.value, r3 - 1)).indexOf(\"\\n\") > -1 && (f3 = o3 ? f3.split(\"\\n\").map(function(e4) {\n return \" \" + e4;\n }).join(\"\\n\").substr(2) : \"\\n\" + f3.split(\"\\n\").map(function(e4) {\n return \" \" + e4;\n }).join(\"\\n\")) : f3 = e3.stylize(\"[Circular]\", \"special\")), be(u3)) {\n if (o3 && i3.match(/^\\d+$/))\n return f3;\n (u3 = JSON.stringify(\"\" + i3)).match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/) ? (u3 = u3.substr(1, u3.length - 2), u3 = e3.stylize(u3, \"name\")) : (u3 = u3.replace(/'/g, \"\\\\'\").replace(/\\\\\"/g, '\"').replace(/(^\"|\"$)/g, \"'\"), u3 = e3.stylize(u3, \"string\"));\n }\n return u3 + \": \" + f3;\n}\nfunction pe(e3) {\n return Array.isArray(e3);\n}\nfunction ye(e3) {\n return \"boolean\" == typeof e3;\n}\nfunction le(e3) {\n return null === e3;\n}\nfunction de(e3) {\n return \"number\" == typeof e3;\n}\nfunction ge(e3) {\n return \"string\" == typeof e3;\n}\nfunction be(e3) {\n return void 0 === e3;\n}\nfunction me(e3) {\n return he(e3) && \"[object RegExp]\" === ve(e3);\n}\nfunction he(e3) {\n return \"object\" == typeof e3 && null !== e3;\n}\nfunction je(e3) {\n return he(e3) && \"[object Date]\" === ve(e3);\n}\nfunction Ae(e3) {\n return he(e3) && (\"[object Error]\" === ve(e3) || e3 instanceof Error);\n}\nfunction we(e3) {\n return \"function\" == typeof e3;\n}\nfunction ve(e3) {\n return Object.prototype.toString.call(e3);\n}\nfunction Oe(e3) {\n return e3 < 10 ? \"0\" + e3.toString(10) : e3.toString(10);\n}\nX.debuglog = function(e3) {\n if (e3 = e3.toUpperCase(), !re[e3])\n if (ne.test(e3)) {\n var t3 = Y.pid;\n re[e3] = function() {\n var r3 = X.format.apply(X, arguments);\n console.error(\"%s %d: %s\", e3, t3, r3);\n };\n } else\n re[e3] = function() {\n };\n return re[e3];\n}, X.inspect = oe, oe.colors = { bold: [1, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], white: [37, 39], grey: [90, 39], black: [30, 39], blue: [34, 39], cyan: [36, 39], green: [32, 39], magenta: [35, 39], red: [31, 39], yellow: [33, 39] }, oe.styles = { special: \"cyan\", number: \"yellow\", boolean: \"yellow\", undefined: \"grey\", null: \"bold\", string: \"green\", date: \"magenta\", regexp: \"red\" }, X.types = o$2, X.isArray = pe, X.isBoolean = ye, X.isNull = le, X.isNullOrUndefined = function(e3) {\n return null == e3;\n}, X.isNumber = de, X.isString = ge, X.isSymbol = function(e3) {\n return \"symbol\" == typeof e3;\n}, X.isUndefined = be, X.isRegExp = me, X.types.isRegExp = me, X.isObject = he, X.isDate = je, X.types.isDate = je, X.isError = Ae, X.types.isNativeError = Ae, X.isFunction = we, X.isPrimitive = function(e3) {\n return null === e3 || \"boolean\" == typeof e3 || \"number\" == typeof e3 || \"string\" == typeof e3 || \"symbol\" == typeof e3 || void 0 === e3;\n}, X.isBuffer = i$1;\nvar Se = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\nfunction Be() {\n var e3 = new Date(), t3 = [Oe(e3.getHours()), Oe(e3.getMinutes()), Oe(e3.getSeconds())].join(\":\");\n return [e3.getDate(), Se[e3.getMonth()], t3].join(\" \");\n}\nfunction ke(e3, t3) {\n return Object.prototype.hasOwnProperty.call(e3, t3);\n}\nX.log = function() {\n console.log(\"%s - %s\", Be(), X.format.apply(X, arguments));\n}, X.inherits = t$2, X._extend = function(e3, t3) {\n if (!t3 || !he(t3))\n return e3;\n for (var r3 = Object.keys(t3), n3 = r3.length; n3--; )\n e3[r3[n3]] = t3[r3[n3]];\n return e3;\n};\nvar Ee = \"undefined\" != typeof Symbol ? Symbol(\"util.promisify.custom\") : void 0;\nfunction De(e3, t3) {\n if (!e3) {\n var r3 = new Error(\"Promise was rejected with a falsy value\");\n r3.reason = e3, e3 = r3;\n }\n return t3(e3);\n}\nX.promisify = function(e3) {\n if (\"function\" != typeof e3)\n throw new TypeError('The \"original\" argument must be of type Function');\n if (Ee && e3[Ee]) {\n var t3;\n if (\"function\" != typeof (t3 = e3[Ee]))\n throw new TypeError('The \"util.promisify.custom\" argument must be of type Function');\n return Object.defineProperty(t3, Ee, { value: t3, enumerable: false, writable: false, configurable: true }), t3;\n }\n function t3() {\n for (var t4, r3, n3 = new Promise(function(e4, n4) {\n t4 = e4, r3 = n4;\n }), i3 = [], o3 = 0; o3 < arguments.length; o3++)\n i3.push(arguments[o3]);\n i3.push(function(e4, n4) {\n e4 ? r3(e4) : t4(n4);\n });\n try {\n e3.apply(this || Q, i3);\n } catch (e4) {\n r3(e4);\n }\n return n3;\n }\n return Object.setPrototypeOf(t3, Object.getPrototypeOf(e3)), Ee && Object.defineProperty(t3, Ee, { value: t3, enumerable: false, writable: false, configurable: true }), Object.defineProperties(t3, ee(e3));\n}, X.promisify.custom = Ee, X.callbackify = function(e3) {\n if (\"function\" != typeof e3)\n throw new TypeError('The \"original\" argument must be of type Function');\n function t3() {\n for (var t4 = [], r3 = 0; r3 < arguments.length; r3++)\n t4.push(arguments[r3]);\n var n3 = t4.pop();\n if (\"function\" != typeof n3)\n throw new TypeError(\"The last argument must be of type Function\");\n var i3 = this || Q, o3 = function() {\n return n3.apply(i3, arguments);\n };\n e3.apply(this || Q, t4).then(function(e4) {\n Y.nextTick(o3.bind(null, null, e4));\n }, function(e4) {\n Y.nextTick(De.bind(null, e4, o3));\n });\n }\n return Object.setPrototypeOf(t3, Object.getPrototypeOf(e3)), Object.defineProperties(t3, ee(e3)), t3;\n};\n\n// node_modules/@jspm/core/nodelibs/browser/chunk-ce0fbc82.js\nX._extend;\nX.callbackify;\nX.debuglog;\nX.deprecate;\nX.format;\nX.inherits;\nX.inspect;\nX.isArray;\nX.isBoolean;\nX.isBuffer;\nX.isDate;\nX.isError;\nX.isFunction;\nX.isNull;\nX.isNullOrUndefined;\nX.isNumber;\nX.isObject;\nX.isPrimitive;\nX.isRegExp;\nX.isString;\nX.isSymbol;\nX.isUndefined;\nX.log;\nX.promisify;\nvar _extend = X._extend;\nvar callbackify = X.callbackify;\nvar debuglog = X.debuglog;\nvar deprecate = X.deprecate;\nvar format = X.format;\nvar inherits = X.inherits;\nvar inspect = X.inspect;\nvar isArray = X.isArray;\nvar isBoolean = X.isBoolean;\nvar isBuffer = X.isBuffer;\nvar isDate = X.isDate;\nvar isError = X.isError;\nvar isFunction = X.isFunction;\nvar isNull = X.isNull;\nvar isNullOrUndefined = X.isNullOrUndefined;\nvar isNumber = X.isNumber;\nvar isObject = X.isObject;\nvar isPrimitive = X.isPrimitive;\nvar isRegExp = X.isRegExp;\nvar isString = X.isString;\nvar isSymbol = X.isSymbol;\nvar isUndefined = X.isUndefined;\nvar log = X.log;\nvar promisify = X.promisify;\nvar types = X.types;\nvar TextEncoder = self.TextEncoder;\nvar TextDecoder = self.TextDecoder;\n\n// node_modules/@jspm/core/nodelibs/browser/util.js\nvar _extend2 = X._extend;\nvar callbackify2 = X.callbackify;\nvar debuglog2 = X.debuglog;\nvar deprecate2 = X.deprecate;\nvar format2 = X.format;\nvar inherits2 = X.inherits;\nvar inspect2 = X.inspect;\nvar isArray2 = X.isArray;\nvar isBoolean2 = X.isBoolean;\nvar isBuffer2 = X.isBuffer;\nvar isDate2 = X.isDate;\nvar isError2 = X.isError;\nvar isFunction2 = X.isFunction;\nvar isNull2 = X.isNull;\nvar isNullOrUndefined2 = X.isNullOrUndefined;\nvar isNumber2 = X.isNumber;\nvar isObject2 = X.isObject;\nvar isPrimitive2 = X.isPrimitive;\nvar isRegExp2 = X.isRegExp;\nvar isString2 = X.isString;\nvar isSymbol2 = X.isSymbol;\nvar isUndefined2 = X.isUndefined;\nvar log2 = X.log;\nvar promisify2 = X.promisify;\nvar types2 = X.types;\nvar TextEncoder2 = X.TextEncoder = globalThis.TextEncoder;\nvar TextDecoder2 = X.TextDecoder = globalThis.TextDecoder;\nexport {\n TextDecoder2 as TextDecoder,\n TextEncoder2 as TextEncoder,\n _extend2 as _extend,\n callbackify2 as callbackify,\n debuglog2 as debuglog,\n X as default,\n deprecate2 as deprecate,\n format2 as format,\n inherits2 as inherits,\n inspect2 as inspect,\n isArray2 as isArray,\n isBoolean2 as isBoolean,\n isBuffer2 as isBuffer,\n isDate2 as isDate,\n isError2 as isError,\n isFunction2 as isFunction,\n isNull2 as isNull,\n isNullOrUndefined2 as isNullOrUndefined,\n isNumber2 as isNumber,\n isObject2 as isObject,\n isPrimitive2 as isPrimitive,\n isRegExp2 as isRegExp,\n isString2 as isString,\n isSymbol2 as isSymbol,\n isUndefined2 as isUndefined,\n log2 as log,\n promisify2 as promisify,\n types2 as types\n};\n","import type { InspectOptionsStylized } from 'node:util';\n\nexport const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');\nexport const customInspectSymbolStackLess = Symbol.for('nodejs.util.inspect.custom.stack-less');\n\nexport abstract class BaseError extends Error {\n\tprotected [customInspectSymbol](depth: number, options: InspectOptionsStylized) {\n\t\treturn `${this[customInspectSymbolStackLess](depth, options)}\\n${this.stack!.slice(this.stack!.indexOf('\\n'))}`;\n\t}\n\n\tprotected abstract [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;\n}\n","import type {\n\tArrayConstraintName,\n\tBigIntConstraintName,\n\tBooleanConstraintName,\n\tDateConstraintName,\n\tNumberConstraintName,\n\tObjectConstraintName,\n\tStringConstraintName,\n\tTypedArrayConstraintName\n} from '../../constraints/type-exports';\nimport { BaseError } from './BaseError';\n\nexport type ConstraintErrorNames =\n\t| TypedArrayConstraintName\n\t| ArrayConstraintName\n\t| BigIntConstraintName\n\t| BooleanConstraintName\n\t| DateConstraintName\n\t| NumberConstraintName\n\t| ObjectConstraintName\n\t| StringConstraintName;\n\nexport abstract class BaseConstraintError extends BaseError {\n\tpublic readonly constraint: ConstraintErrorNames;\n\tpublic readonly given: T;\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T) {\n\t\tsuper(message);\n\t\tthis.constraint = constraint;\n\t\tthis.given = given;\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { BaseConstraintError, type ConstraintErrorNames } from './BaseConstraintError';\n\nexport class ExpectedConstraintError extends BaseConstraintError {\n\tpublic readonly expected: string;\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: string) {\n\t\tsuper(constraint, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tconstraint: this.constraint,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst constraint = options.stylize(this.constraint, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ExpectedConstraintError: ${constraint}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ExpectedConstraintError', 'special')} > ${constraint}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected: ', 'string')}${options.stylize(this.expected, 'boolean')}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","import { getGlobalValidationEnabled } from '../lib/configs';\nimport { Result } from '../lib/Result';\nimport { ArrayValidator, DefaultValidator, LiteralValidator, NullishValidator, SetValidator, UnionValidator } from './imports';\nimport { getValue } from './util/getValue';\nimport { whenConstraint, type WhenKey, type WhenOptions } from '../constraints/ObjectConstrains';\nimport type { CombinedError } from '../lib/errors/CombinedError';\nimport type { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport type { UnknownEnumValueError } from '../lib/errors/UnknownEnumValueError';\nimport type { ValidationError } from '../lib/errors/ValidationError';\nimport type { BaseConstraintError, InferResultType } from '../type-exports';\nimport type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\n\nexport abstract class BaseValidator {\n\tprotected parent?: object;\n\tprotected constraints: readonly IConstraint[] = [];\n\tprotected isValidationEnabled: boolean | (() => boolean) | null = null;\n\n\tpublic constructor(constraints: readonly IConstraint[] = []) {\n\t\tthis.constraints = constraints;\n\t}\n\n\tpublic setParent(parent: object): this {\n\t\tthis.parent = parent;\n\t\treturn this;\n\t}\n\n\tpublic get optional(): UnionValidator {\n\t\treturn new UnionValidator([new LiteralValidator(undefined), this.clone()]);\n\t}\n\n\tpublic get nullable(): UnionValidator {\n\t\treturn new UnionValidator([new LiteralValidator(null), this.clone()]);\n\t}\n\n\tpublic get nullish(): UnionValidator {\n\t\treturn new UnionValidator([new NullishValidator(), this.clone()]);\n\t}\n\n\tpublic get array(): ArrayValidator {\n\t\treturn new ArrayValidator(this.clone());\n\t}\n\n\tpublic get set(): SetValidator {\n\t\treturn new SetValidator(this.clone());\n\t}\n\n\tpublic or(...predicates: readonly BaseValidator[]): UnionValidator {\n\t\treturn new UnionValidator([this.clone(), ...predicates]);\n\t}\n\n\tpublic transform(cb: (value: T) => T): this;\n\tpublic transform(cb: (value: T) => O): BaseValidator;\n\tpublic transform(cb: (value: T) => O): BaseValidator {\n\t\treturn this.addConstraint({ run: (input) => Result.ok(cb(input) as unknown as T) }) as unknown as BaseValidator;\n\t}\n\n\tpublic reshape(cb: (input: T) => Result): this;\n\tpublic reshape, O = InferResultType>(cb: (input: T) => R): BaseValidator;\n\tpublic reshape, O = InferResultType>(cb: (input: T) => R): BaseValidator {\n\t\treturn this.addConstraint({ run: cb as unknown as (input: T) => Result> }) as unknown as BaseValidator;\n\t}\n\n\tpublic default(value: Exclude | (() => Exclude)): DefaultValidator> {\n\t\treturn new DefaultValidator(this.clone() as unknown as BaseValidator>, value);\n\t}\n\n\tpublic when = this>(key: Key, options: WhenOptions): this {\n\t\treturn this.addConstraint(whenConstraint(key, options, this as unknown as This));\n\t}\n\n\tpublic run(value: unknown): Result {\n\t\tlet result = this.handle(value) as Result;\n\t\tif (result.isErr()) return result;\n\n\t\tfor (const constraint of this.constraints) {\n\t\t\tresult = constraint.run(result.value as T, this.parent);\n\t\t\tif (result.isErr()) break;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic parse(value: unknown): R {\n\t\t// If validation is disabled (at the validator or global level), we only run the `handle` method, which will do some basic checks\n\t\t// (like that the input is a string for a string validator)\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn this.handle(value).unwrap() as R;\n\t\t}\n\n\t\treturn this.constraints.reduce((v, constraint) => constraint.run(v).unwrap(), this.handle(value).unwrap()) as R;\n\t}\n\n\tpublic is(value: unknown): value is R {\n\t\treturn this.run(value).isOk();\n\t}\n\n\t/**\n\t * Sets if the validator should also run constraints or just do basic checks.\n\t * @param isValidationEnabled Whether this validator should be enabled or disabled. You can pass boolean or a function returning boolean which will be called just before parsing.\n\t * Set to `null` to go off of the global configuration.\n\t */\n\tpublic setValidationEnabled(isValidationEnabled: boolean | (() => boolean) | null): this {\n\t\tconst clone = this.clone();\n\t\tclone.isValidationEnabled = isValidationEnabled;\n\t\treturn clone;\n\t}\n\n\tpublic getValidationEnabled() {\n\t\treturn getValue(this.isValidationEnabled);\n\t}\n\n\tprotected get shouldRunConstraints(): boolean {\n\t\treturn getValue(this.isValidationEnabled) ?? getGlobalValidationEnabled();\n\t}\n\n\tprotected clone(): this {\n\t\tconst clone: this = Reflect.construct(this.constructor, [this.constraints]);\n\t\tclone.isValidationEnabled = this.isValidationEnabled;\n\t\treturn clone;\n\t}\n\n\tprotected abstract handle(value: unknown): Result;\n\n\tprotected addConstraint(constraint: IConstraint): this {\n\t\tconst clone = this.clone();\n\t\tclone.constraints = clone.constraints.concat(constraint);\n\t\treturn clone;\n\t}\n}\n\nexport type ValidatorError = ValidationError | CombinedError | CombinedPropertyError | UnknownEnumValueError;\n","import fastDeepEqual from 'fast-deep-equal/es6/index.js';\nimport uniqWith from 'lodash/uniqWith.js';\n\nexport function isUnique(input: unknown[]) {\n\tif (input.length < 2) return true;\n\tconst uniqueArray = uniqWith(input, fastDeepEqual);\n\treturn uniqueArray.length === input.length;\n}\n","export function lessThan(a: number, b: number): boolean;\nexport function lessThan(a: bigint, b: bigint): boolean;\nexport function lessThan(a: number | bigint, b: number | bigint): boolean {\n\treturn a < b;\n}\n\nexport function lessThanOrEqual(a: number, b: number): boolean;\nexport function lessThanOrEqual(a: bigint, b: bigint): boolean;\nexport function lessThanOrEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a <= b;\n}\n\nexport function greaterThan(a: number, b: number): boolean;\nexport function greaterThan(a: bigint, b: bigint): boolean;\nexport function greaterThan(a: number | bigint, b: number | bigint): boolean {\n\treturn a > b;\n}\n\nexport function greaterThanOrEqual(a: number, b: number): boolean;\nexport function greaterThanOrEqual(a: bigint, b: bigint): boolean;\nexport function greaterThanOrEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a >= b;\n}\n\nexport function equal(a: number, b: number): boolean;\nexport function equal(a: bigint, b: bigint): boolean;\nexport function equal(a: number | bigint, b: number | bigint): boolean {\n\treturn a === b;\n}\n\nexport function notEqual(a: number, b: number): boolean;\nexport function notEqual(a: bigint, b: bigint): boolean;\nexport function notEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a !== b;\n}\n\nexport interface Comparator {\n\t(a: number, b: number): boolean;\n\t(a: bigint, b: bigint): boolean;\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { isUnique } from './util/isUnique';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type ArrayConstraintName = `s.array(T).${\n\t| 'unique'\n\t| `length${\n\t\t\t| 'LessThan'\n\t\t\t| 'LessThanOrEqual'\n\t\t\t| 'GreaterThan'\n\t\t\t| 'GreaterThanOrEqual'\n\t\t\t| 'Equal'\n\t\t\t| 'NotEqual'\n\t\t\t| 'Range'\n\t\t\t| 'RangeInclusive'\n\t\t\t| 'RangeExclusive'}`}`;\n\nfunction arrayLengthComparator(comparator: Comparator, name: ArrayConstraintName, expected: string, length: number): IConstraint {\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.length < ${value}`;\n\treturn arrayLengthComparator(lessThan, 's.array(T).lengthLessThan', expected, value);\n}\n\nexport function arrayLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length <= ${value}`;\n\treturn arrayLengthComparator(lessThanOrEqual, 's.array(T).lengthLessThanOrEqual', expected, value);\n}\n\nexport function arrayLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.length > ${value}`;\n\treturn arrayLengthComparator(greaterThan, 's.array(T).lengthGreaterThan', expected, value);\n}\n\nexport function arrayLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length >= ${value}`;\n\treturn arrayLengthComparator(greaterThanOrEqual, 's.array(T).lengthGreaterThanOrEqual', expected, value);\n}\n\nexport function arrayLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.length === ${value}`;\n\treturn arrayLengthComparator(equal, 's.array(T).lengthEqual', expected, value);\n}\n\nexport function arrayLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.length !== ${value}`;\n\treturn arrayLengthComparator(notEqual, 's.array(T).lengthNotEqual', expected, value);\n}\n\nexport function arrayLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length >= start && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRange', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthRangeInclusive(start: number, end: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length <= ${end}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length >= start && input.length <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRangeInclusive', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length > startAfter && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRangeExclusive', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport const uniqueArray: IConstraint = {\n\trun(input: unknown[]) {\n\t\treturn isUnique(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).unique', 'Array values are not unique', input, 'Expected all values to be unique'));\n\t}\n};\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class CombinedPropertyError extends BaseError {\n\tpublic readonly errors: [PropertyKey, BaseError][];\n\n\tpublic constructor(errors: [PropertyKey, BaseError][]) {\n\t\tsuper('Received one or more errors');\n\n\t\tthis.errors = errors;\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize('[CombinedPropertyError]', 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\n\t\tconst header = `${options.stylize('CombinedPropertyError', 'special')} (${options.stylize(this.errors.length.toString(), 'number')})`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst errors = this.errors\n\t\t\t.map(([key, error]) => {\n\t\t\t\tconst property = CombinedPropertyError.formatProperty(key, options);\n\t\t\t\tconst body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\\n/g, padding);\n\n\t\t\t\treturn ` input${property}${padding}${body}`;\n\t\t\t})\n\t\t\t.join('\\n\\n');\n\t\treturn `${header}\\n ${message}\\n\\n${errors}`;\n\t}\n\n\tprivate static formatProperty(key: PropertyKey, options: InspectOptionsStylized): string {\n\t\tif (typeof key === 'string') return options.stylize(`.${key}`, 'symbol');\n\t\tif (typeof key === 'number') return `[${options.stylize(key.toString(), 'number')}]`;\n\t\treturn `[${options.stylize('Symbol', 'symbol')}(${key.description})]`;\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class ValidationError extends BaseError {\n\tpublic readonly validator: string;\n\tpublic readonly given: unknown;\n\n\tpublic constructor(validator: string, message: string, given: unknown) {\n\t\tsuper(message);\n\n\t\tthis.validator = validator;\n\t\tthis.given = given;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalidator: this.validator,\n\t\t\tgiven: this.given\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst validator = options.stylize(this.validator, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ValidationError: ${validator}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ValidationError', 'special')} > ${validator}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${givenBlock}`;\n\t}\n}\n","import {\n\tarrayLengthEqual,\n\tarrayLengthGreaterThan,\n\tarrayLengthGreaterThanOrEqual,\n\tarrayLengthLessThan,\n\tarrayLengthLessThanOrEqual,\n\tarrayLengthNotEqual,\n\tarrayLengthRange,\n\tarrayLengthRangeExclusive,\n\tarrayLengthRangeInclusive,\n\tuniqueArray\n} from '../constraints/ArrayConstraints';\nimport type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport type { ExpandSmallerTuples, Tuple, UnshiftTuple } from '../lib/util-types';\nimport { BaseValidator } from './imports';\n\nexport class ArrayValidator extends BaseValidator {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tpublic lengthLessThan(length: N): ArrayValidator]>>> {\n\t\treturn this.addConstraint(arrayLengthLessThan(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthLessThanOrEqual(length: N): ArrayValidator]>> {\n\t\treturn this.addConstraint(arrayLengthLessThanOrEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthGreaterThan(length: N): ArrayValidator<[...Tuple, I, ...T]> {\n\t\treturn this.addConstraint(arrayLengthGreaterThan(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: N): ArrayValidator<[...Tuple, ...T]> {\n\t\treturn this.addConstraint(arrayLengthGreaterThanOrEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthEqual(length: N): ArrayValidator<[...Tuple]> {\n\t\treturn this.addConstraint(arrayLengthEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthNotEqual(length: number): ArrayValidator<[...T]> {\n\t\treturn this.addConstraint(arrayLengthNotEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthRange(\n\t\tstart: S,\n\t\tendBefore: E\n\t): ArrayValidator]>>, ExpandSmallerTuples]>>>> {\n\t\treturn this.addConstraint(arrayLengthRange(start, endBefore) as IConstraint) as any;\n\t}\n\n\tpublic lengthRangeInclusive(\n\t\tstartAt: S,\n\t\tendAt: E\n\t): ArrayValidator]>, ExpandSmallerTuples]>>>> {\n\t\treturn this.addConstraint(arrayLengthRangeInclusive(startAt, endAt) as IConstraint) as any;\n\t}\n\n\tpublic lengthRangeExclusive(\n\t\tstartAfter: S,\n\t\tendBefore: E\n\t): ArrayValidator]>>, ExpandSmallerTuples<[...Tuple]>>> {\n\t\treturn this.addConstraint(arrayLengthRangeExclusive(startAfter, endBefore) as IConstraint) as any;\n\t}\n\n\tpublic get unique(): this {\n\t\treturn this.addConstraint(uniqueArray as IConstraint);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result {\n\t\tif (!Array.isArray(values)) {\n\t\t\treturn Result.err(new ValidationError('s.array(T)', 'Expected an array', values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values as T);\n\t\t}\n\n\t\tconst errors: [number, BaseError][] = [];\n\t\tconst transformed: T = [] as unknown as T;\n\n\t\tfor (let i = 0; i < values.length; i++) {\n\t\t\tconst result = this.validator.run(values[i]);\n\t\t\tif (result.isOk()) transformed.push(result.value);\n\t\t\telse errors.push([i, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type BigIntConstraintName = `s.bigint.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'notEqual'\n\t| 'divisibleBy'}`;\n\nfunction bigintComparator(comparator: Comparator, name: BigIntConstraintName, expected: string, number: bigint): IConstraint {\n\treturn {\n\t\trun(input: bigint) {\n\t\t\treturn comparator(input, number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid bigint value', input, expected));\n\t\t}\n\t};\n}\n\nexport function bigintLessThan(value: bigint): IConstraint {\n\tconst expected = `expected < ${value}n`;\n\treturn bigintComparator(lessThan, 's.bigint.lessThan', expected, value);\n}\n\nexport function bigintLessThanOrEqual(value: bigint): IConstraint {\n\tconst expected = `expected <= ${value}n`;\n\treturn bigintComparator(lessThanOrEqual, 's.bigint.lessThanOrEqual', expected, value);\n}\n\nexport function bigintGreaterThan(value: bigint): IConstraint {\n\tconst expected = `expected > ${value}n`;\n\treturn bigintComparator(greaterThan, 's.bigint.greaterThan', expected, value);\n}\n\nexport function bigintGreaterThanOrEqual(value: bigint): IConstraint {\n\tconst expected = `expected >= ${value}n`;\n\treturn bigintComparator(greaterThanOrEqual, 's.bigint.greaterThanOrEqual', expected, value);\n}\n\nexport function bigintEqual(value: bigint): IConstraint {\n\tconst expected = `expected === ${value}n`;\n\treturn bigintComparator(equal, 's.bigint.equal', expected, value);\n}\n\nexport function bigintNotEqual(value: bigint): IConstraint {\n\tconst expected = `expected !== ${value}n`;\n\treturn bigintComparator(notEqual, 's.bigint.notEqual', expected, value);\n}\n\nexport function bigintDivisibleBy(divider: bigint): IConstraint {\n\tconst expected = `expected % ${divider}n === 0n`;\n\treturn {\n\t\trun(input: bigint) {\n\t\t\treturn input % divider === 0n //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.bigint.divisibleBy', 'BigInt is not divisible', input, expected));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tbigintDivisibleBy,\n\tbigintEqual,\n\tbigintGreaterThan,\n\tbigintGreaterThanOrEqual,\n\tbigintLessThan,\n\tbigintLessThanOrEqual,\n\tbigintNotEqual\n} from '../constraints/BigIntConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class BigIntValidator extends BaseValidator {\n\tpublic lessThan(number: bigint): this {\n\t\treturn this.addConstraint(bigintLessThan(number) as IConstraint);\n\t}\n\n\tpublic lessThanOrEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintLessThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic greaterThan(number: bigint): this {\n\t\treturn this.addConstraint(bigintGreaterThan(number) as IConstraint);\n\t}\n\n\tpublic greaterThanOrEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintGreaterThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic equal(number: N): BigIntValidator {\n\t\treturn this.addConstraint(bigintEqual(number) as IConstraint) as unknown as BigIntValidator;\n\t}\n\n\tpublic notEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintNotEqual(number) as IConstraint);\n\t}\n\n\tpublic get positive(): this {\n\t\treturn this.greaterThanOrEqual(0n);\n\t}\n\n\tpublic get negative(): this {\n\t\treturn this.lessThan(0n);\n\t}\n\n\tpublic divisibleBy(number: bigint): this {\n\t\treturn this.addConstraint(bigintDivisibleBy(number) as IConstraint);\n\t}\n\n\tpublic get abs(): this {\n\t\treturn this.transform((value) => (value < 0 ? -value : value) as T);\n\t}\n\n\tpublic intN(bits: number): this {\n\t\treturn this.transform((value) => BigInt.asIntN(bits, value) as T);\n\t}\n\n\tpublic uintN(bits: number): this {\n\t\treturn this.transform((value) => BigInt.asUintN(bits, value) as T);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'bigint' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.bigint', 'Expected a bigint primitive', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\n\nexport type BooleanConstraintName = `s.boolean.${boolean}`;\n\nexport const booleanTrue: IConstraint = {\n\trun(input: boolean) {\n\t\treturn input //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.boolean.true', 'Invalid boolean value', input, 'true'));\n\t}\n};\n\nexport const booleanFalse: IConstraint = {\n\trun(input: boolean) {\n\t\treturn input //\n\t\t\t? Result.err(new ExpectedConstraintError('s.boolean.false', 'Invalid boolean value', input, 'false'))\n\t\t\t: Result.ok(input);\n\t}\n};\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { booleanFalse, booleanTrue } from '../constraints/BooleanConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class BooleanValidator extends BaseValidator {\n\tpublic get true(): BooleanValidator {\n\t\treturn this.addConstraint(booleanTrue as IConstraint) as BooleanValidator;\n\t}\n\n\tpublic get false(): BooleanValidator {\n\t\treturn this.addConstraint(booleanFalse as IConstraint) as BooleanValidator;\n\t}\n\n\tpublic equal(value: R): BooleanValidator {\n\t\treturn (value ? this.true : this.false) as BooleanValidator;\n\t}\n\n\tpublic notEqual(value: R): BooleanValidator {\n\t\treturn (value ? this.false : this.true) as BooleanValidator;\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'boolean' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.boolean', 'Expected a boolean primitive', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type DateConstraintName = `s.date.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'notEqual'\n\t| 'valid'\n\t| 'invalid'}`;\n\nfunction dateComparator(comparator: Comparator, name: DateConstraintName, expected: string, number: number): IConstraint {\n\treturn {\n\t\trun(input: Date) {\n\t\t\treturn comparator(input.getTime(), number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Date value', input, expected));\n\t\t}\n\t};\n}\n\nexport function dateLessThan(value: Date): IConstraint {\n\tconst expected = `expected < ${value.toISOString()}`;\n\treturn dateComparator(lessThan, 's.date.lessThan', expected, value.getTime());\n}\n\nexport function dateLessThanOrEqual(value: Date): IConstraint {\n\tconst expected = `expected <= ${value.toISOString()}`;\n\treturn dateComparator(lessThanOrEqual, 's.date.lessThanOrEqual', expected, value.getTime());\n}\n\nexport function dateGreaterThan(value: Date): IConstraint {\n\tconst expected = `expected > ${value.toISOString()}`;\n\treturn dateComparator(greaterThan, 's.date.greaterThan', expected, value.getTime());\n}\n\nexport function dateGreaterThanOrEqual(value: Date): IConstraint {\n\tconst expected = `expected >= ${value.toISOString()}`;\n\treturn dateComparator(greaterThanOrEqual, 's.date.greaterThanOrEqual', expected, value.getTime());\n}\n\nexport function dateEqual(value: Date): IConstraint {\n\tconst expected = `expected === ${value.toISOString()}`;\n\treturn dateComparator(equal, 's.date.equal', expected, value.getTime());\n}\n\nexport function dateNotEqual(value: Date): IConstraint {\n\tconst expected = `expected !== ${value.toISOString()}`;\n\treturn dateComparator(notEqual, 's.date.notEqual', expected, value.getTime());\n}\n\nexport const dateInvalid: IConstraint = {\n\trun(input: Date) {\n\t\treturn Number.isNaN(input.getTime()) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.date.invalid', 'Invalid Date value', input, 'expected === NaN'));\n\t}\n};\n\nexport const dateValid: IConstraint = {\n\trun(input: Date) {\n\t\treturn Number.isNaN(input.getTime()) //\n\t\t\t? Result.err(new ExpectedConstraintError('s.date.valid', 'Invalid Date value', input, 'expected !== NaN'))\n\t\t\t: Result.ok(input);\n\t}\n};\n","import {\n\tdateEqual,\n\tdateGreaterThan,\n\tdateGreaterThanOrEqual,\n\tdateInvalid,\n\tdateLessThan,\n\tdateLessThanOrEqual,\n\tdateNotEqual,\n\tdateValid\n} from '../constraints/DateConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class DateValidator extends BaseValidator {\n\tpublic lessThan(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateLessThan(new Date(date)));\n\t}\n\n\tpublic lessThanOrEqual(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateLessThanOrEqual(new Date(date)));\n\t}\n\n\tpublic greaterThan(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateGreaterThan(new Date(date)));\n\t}\n\n\tpublic greaterThanOrEqual(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateGreaterThanOrEqual(new Date(date)));\n\t}\n\n\tpublic equal(date: Date | number | string): this {\n\t\tconst resolved = new Date(date);\n\t\treturn Number.isNaN(resolved.getTime()) //\n\t\t\t? this.invalid\n\t\t\t: this.addConstraint(dateEqual(resolved));\n\t}\n\n\tpublic notEqual(date: Date | number | string): this {\n\t\tconst resolved = new Date(date);\n\t\treturn Number.isNaN(resolved.getTime()) //\n\t\t\t? this.valid\n\t\t\t: this.addConstraint(dateNotEqual(resolved));\n\t}\n\n\tpublic get valid(): this {\n\t\treturn this.addConstraint(dateValid);\n\t}\n\n\tpublic get invalid(): this {\n\t\treturn this.addConstraint(dateInvalid);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn value instanceof Date //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ValidationError('s.date', 'Expected a Date', value));\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { ValidationError } from './ValidationError';\n\nexport class ExpectedValidationError extends ValidationError {\n\tpublic readonly expected: T;\n\n\tpublic constructor(validator: string, message: string, given: unknown, expected: T) {\n\t\tsuper(validator, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic override toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalidator: this.validator,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst validator = options.stylize(this.validator, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ExpectedValidationError: ${validator}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst expected = inspect(this.expected, newOptions).replace(/\\n/g, padding);\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ExpectedValidationError', 'special')} > ${validator}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected:', 'string')}${padding}${expected}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { ExpectedValidationError } from '../lib/errors/ExpectedValidationError';\nimport { Result } from '../lib/Result';\nimport type { Constructor } from '../lib/util-types';\nimport { BaseValidator } from './imports';\n\nexport class InstanceValidator extends BaseValidator {\n\tpublic readonly expected: Constructor;\n\n\tpublic constructor(expected: Constructor, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.expected = expected;\n\t}\n\n\tprotected handle(value: unknown): Result>> {\n\t\treturn value instanceof this.expected //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ExpectedValidationError('s.instance(V)', 'Expected', value, this.expected));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.expected, this.constraints]);\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { ExpectedValidationError } from '../lib/errors/ExpectedValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class LiteralValidator extends BaseValidator {\n\tpublic readonly expected: T;\n\n\tpublic constructor(literal: T, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.expected = literal;\n\t}\n\n\tprotected handle(value: unknown): Result> {\n\t\treturn Object.is(value, this.expected) //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ExpectedValidationError('s.literal(V)', 'Expected values to be equals', value, this.expected));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.expected, this.constraints]);\n\t}\n}\n","import { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NeverValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn Result.err(new ValidationError('s.never', 'Expected a value to not be passed', value));\n\t}\n}\n","import { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NullishValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn value === undefined || value === null //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ValidationError('s.nullish', 'Expected undefined or null', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type NumberConstraintName = `s.number.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'equal(NaN)'\n\t| 'notEqual'\n\t| 'notEqual(NaN)'\n\t| 'int'\n\t| 'safeInt'\n\t| 'finite'\n\t| 'divisibleBy'}`;\n\nfunction numberComparator(comparator: Comparator, name: NumberConstraintName, expected: string, number: number): IConstraint {\n\treturn {\n\t\trun(input: number) {\n\t\t\treturn comparator(input, number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid number value', input, expected));\n\t\t}\n\t};\n}\n\nexport function numberLessThan(value: number): IConstraint {\n\tconst expected = `expected < ${value}`;\n\treturn numberComparator(lessThan, 's.number.lessThan', expected, value);\n}\n\nexport function numberLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected <= ${value}`;\n\treturn numberComparator(lessThanOrEqual, 's.number.lessThanOrEqual', expected, value);\n}\n\nexport function numberGreaterThan(value: number): IConstraint {\n\tconst expected = `expected > ${value}`;\n\treturn numberComparator(greaterThan, 's.number.greaterThan', expected, value);\n}\n\nexport function numberGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected >= ${value}`;\n\treturn numberComparator(greaterThanOrEqual, 's.number.greaterThanOrEqual', expected, value);\n}\n\nexport function numberEqual(value: number): IConstraint {\n\tconst expected = `expected === ${value}`;\n\treturn numberComparator(equal, 's.number.equal', expected, value);\n}\n\nexport function numberNotEqual(value: number): IConstraint {\n\tconst expected = `expected !== ${value}`;\n\treturn numberComparator(notEqual, 's.number.notEqual', expected, value);\n}\n\nexport const numberInt: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isInteger(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(\n\t\t\t\t\tnew ExpectedConstraintError('s.number.int', 'Given value is not an integer', input, 'Number.isInteger(expected) to be true')\n\t\t\t );\n\t}\n};\n\nexport const numberSafeInt: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isSafeInteger(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(\n\t\t\t\t\tnew ExpectedConstraintError(\n\t\t\t\t\t\t's.number.safeInt',\n\t\t\t\t\t\t'Given value is not a safe integer',\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\t'Number.isSafeInteger(expected) to be true'\n\t\t\t\t\t)\n\t\t\t );\n\t}\n};\n\nexport const numberFinite: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isFinite(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.number.finite', 'Given value is not finite', input, 'Number.isFinite(expected) to be true'));\n\t}\n};\n\nexport const numberNaN: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isNaN(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.number.equal(NaN)', 'Invalid number value', input, 'expected === NaN'));\n\t}\n};\n\nexport const numberNotNaN: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isNaN(input) //\n\t\t\t? Result.err(new ExpectedConstraintError('s.number.notEqual(NaN)', 'Invalid number value', input, 'expected !== NaN'))\n\t\t\t: Result.ok(input);\n\t}\n};\n\nexport function numberDivisibleBy(divider: number): IConstraint {\n\tconst expected = `expected % ${divider} === 0`;\n\treturn {\n\t\trun(input: number) {\n\t\t\treturn input % divider === 0 //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.number.divisibleBy', 'Number is not divisible', input, expected));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tnumberDivisibleBy,\n\tnumberEqual,\n\tnumberFinite,\n\tnumberGreaterThan,\n\tnumberGreaterThanOrEqual,\n\tnumberInt,\n\tnumberLessThan,\n\tnumberLessThanOrEqual,\n\tnumberNaN,\n\tnumberNotEqual,\n\tnumberNotNaN,\n\tnumberSafeInt\n} from '../constraints/NumberConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NumberValidator extends BaseValidator {\n\tpublic lessThan(number: number): this {\n\t\treturn this.addConstraint(numberLessThan(number) as IConstraint);\n\t}\n\n\tpublic lessThanOrEqual(number: number): this {\n\t\treturn this.addConstraint(numberLessThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic greaterThan(number: number): this {\n\t\treturn this.addConstraint(numberGreaterThan(number) as IConstraint);\n\t}\n\n\tpublic greaterThanOrEqual(number: number): this {\n\t\treturn this.addConstraint(numberGreaterThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic equal(number: N): NumberValidator {\n\t\treturn Number.isNaN(number) //\n\t\t\t? (this.addConstraint(numberNaN as IConstraint) as unknown as NumberValidator)\n\t\t\t: (this.addConstraint(numberEqual(number) as IConstraint) as unknown as NumberValidator);\n\t}\n\n\tpublic notEqual(number: number): this {\n\t\treturn Number.isNaN(number) //\n\t\t\t? this.addConstraint(numberNotNaN as IConstraint)\n\t\t\t: this.addConstraint(numberNotEqual(number) as IConstraint);\n\t}\n\n\tpublic get int(): this {\n\t\treturn this.addConstraint(numberInt as IConstraint);\n\t}\n\n\tpublic get safeInt(): this {\n\t\treturn this.addConstraint(numberSafeInt as IConstraint);\n\t}\n\n\tpublic get finite(): this {\n\t\treturn this.addConstraint(numberFinite as IConstraint);\n\t}\n\n\tpublic get positive(): this {\n\t\treturn this.greaterThanOrEqual(0);\n\t}\n\n\tpublic get negative(): this {\n\t\treturn this.lessThan(0);\n\t}\n\n\tpublic divisibleBy(divider: number): this {\n\t\treturn this.addConstraint(numberDivisibleBy(divider) as IConstraint);\n\t}\n\n\tpublic get abs(): this {\n\t\treturn this.transform(Math.abs as (value: number) => T);\n\t}\n\n\tpublic get sign(): this {\n\t\treturn this.transform(Math.sign as (value: number) => T);\n\t}\n\n\tpublic get trunc(): this {\n\t\treturn this.transform(Math.trunc as (value: number) => T);\n\t}\n\n\tpublic get floor(): this {\n\t\treturn this.transform(Math.floor as (value: number) => T);\n\t}\n\n\tpublic get fround(): this {\n\t\treturn this.transform(Math.fround as (value: number) => T);\n\t}\n\n\tpublic get round(): this {\n\t\treturn this.transform(Math.round as (value: number) => T);\n\t}\n\n\tpublic get ceil(): this {\n\t\treturn this.transform(Math.ceil as (value: number) => T);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'number' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.number', 'Expected a number primitive', value));\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class MissingPropertyError extends BaseError {\n\tpublic readonly property: PropertyKey;\n\n\tpublic constructor(property: PropertyKey) {\n\t\tsuper('A required property is missing');\n\t\tthis.property = property;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tproperty: this.property\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst property = options.stylize(this.property.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[MissingPropertyError: ${property}]`, 'special');\n\t\t}\n\n\t\tconst header = `${options.stylize('MissingPropertyError', 'special')} > ${property}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\treturn `${header}\\n ${message}`;\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class UnknownPropertyError extends BaseError {\n\tpublic readonly property: PropertyKey;\n\tpublic readonly value: unknown;\n\n\tpublic constructor(property: PropertyKey, value: unknown) {\n\t\tsuper('Received unexpected property');\n\n\t\tthis.property = property;\n\t\tthis.value = value;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tproperty: this.property,\n\t\t\tvalue: this.value\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst property = options.stylize(this.property.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[UnknownPropertyError: ${property}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.value, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('UnknownPropertyError', 'special')} > ${property}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${givenBlock}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { Result } from '../lib/Result';\nimport type { ValidatorError } from './BaseValidator';\nimport { BaseValidator } from './imports';\nimport { getValue } from './util/getValue';\n\nexport class DefaultValidator extends BaseValidator {\n\tprivate readonly validator: BaseValidator;\n\tprivate defaultValue: T | (() => T);\n\n\tpublic constructor(validator: BaseValidator, value: T | (() => T), constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t\tthis.defaultValue = value;\n\t}\n\n\tpublic override default(value: Exclude | (() => Exclude)): DefaultValidator> {\n\t\tconst clone = this.clone() as unknown as DefaultValidator>;\n\t\tclone.defaultValue = value;\n\t\treturn clone;\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'undefined' //\n\t\t\t? Result.ok(getValue(this.defaultValue))\n\t\t\t: this.validator['handle'](value); // eslint-disable-line @typescript-eslint/dot-notation\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.defaultValue, this.constraints]);\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class CombinedError extends BaseError {\n\tpublic readonly errors: readonly BaseError[];\n\n\tpublic constructor(errors: readonly BaseError[]) {\n\t\tsuper('Received one or more errors');\n\n\t\tthis.errors = errors;\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize('[CombinedError]', 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\n\t\tconst header = `${options.stylize('CombinedError', 'special')} (${options.stylize(this.errors.length.toString(), 'number')})`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst errors = this.errors\n\t\t\t.map((error, i) => {\n\t\t\t\tconst index = options.stylize((i + 1).toString(), 'number');\n\t\t\t\tconst body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\\n/g, padding);\n\n\t\t\t\treturn ` ${index} ${body}`;\n\t\t\t})\n\t\t\t.join('\\n\\n');\n\t\treturn `${header}\\n ${message}\\n\\n${errors}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedError } from '../lib/errors/CombinedError';\nimport type { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator, LiteralValidator, NullishValidator } from './imports';\n\nexport class UnionValidator extends BaseValidator {\n\tprivate validators: readonly BaseValidator[];\n\n\tpublic constructor(validators: readonly BaseValidator[], constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validators = validators;\n\t}\n\n\tpublic override get optional(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new LiteralValidator(undefined)], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already optional, return a clone:\n\t\t\tif (validator.expected === undefined) return this.clone();\n\n\t\t\t// If it's nullable, convert the nullable validator into a nullish validator to optimize `null | undefined`:\n\t\t\tif (validator.expected === null) {\n\t\t\t\treturn new UnionValidator(\n\t\t\t\t\t[new NullishValidator(), ...this.validators.slice(1)],\n\t\t\t\t\tthis.constraints\n\t\t\t\t) as UnionValidator;\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish (which validates optional), return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new LiteralValidator(undefined), ...this.validators]);\n\t}\n\n\tpublic get required(): UnionValidator> {\n\t\ttype RequiredValidator = UnionValidator>;\n\n\t\tif (this.validators.length === 0) return this.clone() as unknown as RequiredValidator;\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\tif (validator.expected === undefined) return new UnionValidator(this.validators.slice(1), this.constraints) as RequiredValidator;\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\treturn new UnionValidator([new LiteralValidator(null), ...this.validators.slice(1)], this.constraints) as RequiredValidator;\n\t\t}\n\n\t\treturn this.clone() as unknown as RequiredValidator;\n\t}\n\n\tpublic override get nullable(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new LiteralValidator(null)], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already nullable, return a clone:\n\t\t\tif (validator.expected === null) return this.clone();\n\n\t\t\t// If it's optional, convert the optional validator into a nullish validator to optimize `null | undefined`:\n\t\t\tif (validator.expected === undefined) {\n\t\t\t\treturn new UnionValidator(\n\t\t\t\t\t[new NullishValidator(), ...this.validators.slice(1)],\n\t\t\t\t\tthis.constraints\n\t\t\t\t) as UnionValidator;\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish (which validates nullable), return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new LiteralValidator(null), ...this.validators]);\n\t}\n\n\tpublic override get nullish(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new NullishValidator()], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already nullable or optional, promote the union to nullish:\n\t\t\tif (validator.expected === null || validator.expected === undefined) {\n\t\t\t\treturn new UnionValidator([new NullishValidator(), ...this.validators.slice(1)], this.constraints);\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish, return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new NullishValidator(), ...this.validators]);\n\t}\n\n\tpublic override or(...predicates: readonly BaseValidator[]): UnionValidator {\n\t\treturn new UnionValidator([...this.validators, ...predicates]);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validators, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\tconst errors: BaseError[] = [];\n\n\t\tfor (const validator of this.validators) {\n\t\t\tconst result = validator.run(value);\n\t\t\tif (result.isOk()) return result as Result;\n\t\t\terrors.push(result.error!);\n\t\t}\n\n\t\treturn Result.err(new CombinedError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { MissingPropertyError } from '../lib/errors/MissingPropertyError';\nimport { UnknownPropertyError } from '../lib/errors/UnknownPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport type { MappedObjectValidator, UndefinedToOptional } from '../lib/util-types';\nimport { BaseValidator } from './BaseValidator';\nimport { DefaultValidator } from './DefaultValidator';\nimport { LiteralValidator } from './LiteralValidator';\nimport { NullishValidator } from './NullishValidator';\nimport { UnionValidator } from './UnionValidator';\n\nexport class ObjectValidator> extends BaseValidator {\n\tpublic readonly shape: MappedObjectValidator;\n\tpublic readonly strategy: ObjectValidatorStrategy;\n\tprivate readonly keys: readonly (keyof I)[] = [];\n\tprivate readonly handleStrategy: (value: object) => Result;\n\n\tprivate readonly requiredKeys = new Map>();\n\tprivate readonly possiblyUndefinedKeys = new Map>();\n\tprivate readonly possiblyUndefinedKeysWithDefaults = new Map>();\n\n\tpublic constructor(\n\t\tshape: MappedObjectValidator,\n\t\tstrategy: ObjectValidatorStrategy = ObjectValidatorStrategy.Ignore,\n\t\tconstraints: readonly IConstraint[] = []\n\t) {\n\t\tsuper(constraints);\n\t\tthis.shape = shape;\n\t\tthis.strategy = strategy;\n\n\t\tswitch (this.strategy) {\n\t\t\tcase ObjectValidatorStrategy.Ignore:\n\t\t\t\tthis.handleStrategy = (value) => this.handleIgnoreStrategy(value);\n\t\t\t\tbreak;\n\t\t\tcase ObjectValidatorStrategy.Strict: {\n\t\t\t\tthis.handleStrategy = (value) => this.handleStrictStrategy(value);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase ObjectValidatorStrategy.Passthrough:\n\t\t\t\tthis.handleStrategy = (value) => this.handlePassthroughStrategy(value);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst shapeEntries = Object.entries(shape) as [keyof I, BaseValidator][];\n\t\tthis.keys = shapeEntries.map(([key]) => key);\n\n\t\tfor (const [key, validator] of shapeEntries) {\n\t\t\tif (validator instanceof UnionValidator) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\t\t\tconst [possiblyLiteralOrNullishPredicate] = validator['validators'];\n\n\t\t\t\tif (possiblyLiteralOrNullishPredicate instanceof NullishValidator) {\n\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t} else if (possiblyLiteralOrNullishPredicate instanceof LiteralValidator) {\n\t\t\t\t\tif (possiblyLiteralOrNullishPredicate.expected === undefined) {\n\t\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t\t}\n\t\t\t\t} else if (validator instanceof DefaultValidator) {\n\t\t\t\t\tthis.possiblyUndefinedKeysWithDefaults.set(key, validator);\n\t\t\t\t} else {\n\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t}\n\t\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t} else if (validator instanceof LiteralValidator) {\n\t\t\t\tif (validator.expected === undefined) {\n\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t} else {\n\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t}\n\t\t\t} else if (validator instanceof DefaultValidator) {\n\t\t\t\tthis.possiblyUndefinedKeysWithDefaults.set(key, validator);\n\t\t\t} else {\n\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic get strict(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Strict, this.constraints]);\n\t}\n\n\tpublic get ignore(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Ignore, this.constraints]);\n\t}\n\n\tpublic get passthrough(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Passthrough, this.constraints]);\n\t}\n\n\tpublic get partial(): ObjectValidator<{ [Key in keyof I]?: I[Key] }> {\n\t\tconst shape = Object.fromEntries(this.keys.map((key) => [key, this.shape[key as unknown as keyof typeof this.shape].optional]));\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic get required(): ObjectValidator<{ [Key in keyof I]-?: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tthis.keys.map((key) => {\n\t\t\t\tlet validator = this.shape[key as unknown as keyof typeof this.shape];\n\t\t\t\tif (validator instanceof UnionValidator) validator = validator.required;\n\t\t\t\treturn [key, validator];\n\t\t\t})\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic extend(schema: ObjectValidator | MappedObjectValidator): ObjectValidator {\n\t\tconst shape = { ...this.shape, ...(schema instanceof ObjectValidator ? schema.shape : schema) };\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic pick(keys: readonly K[]): ObjectValidator<{ [Key in keyof Pick]: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tkeys.filter((key) => this.keys.includes(key)).map((key) => [key, this.shape[key as unknown as keyof typeof this.shape]])\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic omit(keys: readonly K[]): ObjectValidator<{ [Key in keyof Omit]: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tthis.keys.filter((key) => !keys.includes(key as any)).map((key) => [key, this.shape[key as unknown as keyof typeof this.shape]])\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tprotected override handle(value: unknown): Result {\n\t\tconst typeOfValue = typeof value;\n\t\tif (typeOfValue !== 'object') {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', `Expected the value to be an object, but received ${typeOfValue} instead`, value));\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', 'Expected the value to not be null', value));\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', 'Expected the value to not be an array', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value as I);\n\t\t}\n\n\t\tfor (const predicate of Object.values(this.shape) as BaseValidator[]) {\n\t\t\tpredicate.setParent(this.parent ?? value!);\n\t\t}\n\n\t\treturn this.handleStrategy(value as object);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, this.strategy, this.constraints]);\n\t}\n\n\tprivate handleIgnoreStrategy(value: object): Result {\n\t\tconst errors: [PropertyKey, BaseError][] = [];\n\t\tconst finalObject = {} as I;\n\t\tconst inputEntries = new Map(Object.entries(value) as [keyof I, unknown][]);\n\n\t\tconst runPredicate = (key: keyof I, predicate: BaseValidator) => {\n\t\t\tconst result = predicate.run(value[key as keyof object]);\n\n\t\t\tif (result.isOk()) {\n\t\t\t\tfinalObject[key] = result.value as I[keyof I];\n\t\t\t} else {\n\t\t\t\tconst error = result.error!;\n\t\t\t\terrors.push([key, error]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [key, predicate] of this.requiredKeys) {\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t} else {\n\t\t\t\terrors.push([key, new MissingPropertyError(key)]);\n\t\t\t}\n\t\t}\n\n\t\t// Run possibly undefined keys that also have defaults even if there are no more keys to process (this is necessary so we fill in those defaults)\n\t\tfor (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) {\n\t\t\tinputEntries.delete(key);\n\t\t\trunPredicate(key, validator);\n\t\t}\n\n\t\t// Early exit if there are no more properties to validate in the object and there are errors to report\n\t\tif (inputEntries.size === 0) {\n\t\t\treturn errors.length === 0 //\n\t\t\t\t? Result.ok(finalObject)\n\t\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t\t}\n\n\t\t// In the event the remaining keys to check are less than the number of possible undefined keys, we check those\n\t\t// as it could yield a faster execution\n\t\tconst checkInputEntriesInsteadOfSchemaKeys = this.possiblyUndefinedKeys.size > inputEntries.size;\n\n\t\tif (checkInputEntriesInsteadOfSchemaKeys) {\n\t\t\tfor (const [key] of inputEntries) {\n\t\t\t\tconst predicate = this.possiblyUndefinedKeys.get(key);\n\n\t\t\t\tif (predicate) {\n\t\t\t\t\trunPredicate(key, predicate);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const [key, predicate] of this.possiblyUndefinedKeys) {\n\t\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\t\trunPredicate(key, predicate);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(finalObject)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n\n\tprivate handleStrictStrategy(value: object): Result {\n\t\tconst errors: [PropertyKey, BaseError][] = [];\n\t\tconst finalResult = {} as I;\n\t\tconst inputEntries = new Map(Object.entries(value) as [keyof I, unknown][]);\n\n\t\tconst runPredicate = (key: keyof I, predicate: BaseValidator) => {\n\t\t\tconst result = predicate.run(value[key as keyof object]);\n\n\t\t\tif (result.isOk()) {\n\t\t\t\tfinalResult[key] = result.value as I[keyof I];\n\t\t\t} else {\n\t\t\t\tconst error = result.error!;\n\t\t\t\terrors.push([key, error]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [key, predicate] of this.requiredKeys) {\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t} else {\n\t\t\t\terrors.push([key, new MissingPropertyError(key)]);\n\t\t\t}\n\t\t}\n\n\t\t// Run possibly undefined keys that also have defaults even if there are no more keys to process (this is necessary so we fill in those defaults)\n\t\tfor (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) {\n\t\t\tinputEntries.delete(key);\n\t\t\trunPredicate(key, validator);\n\t\t}\n\n\t\tfor (const [key, predicate] of this.possiblyUndefinedKeys) {\n\t\t\t// All of these validators are assumed to be possibly undefined, so if we have gone through the entire object and there's still validators,\n\t\t\t// safe to assume we're done here\n\t\t\tif (inputEntries.size === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t}\n\t\t}\n\n\t\tif (inputEntries.size !== 0) {\n\t\t\tfor (const [key, value] of inputEntries.entries()) {\n\t\t\t\terrors.push([key, new UnknownPropertyError(key, value)]);\n\t\t\t}\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(finalResult)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n\n\tprivate handlePassthroughStrategy(value: object): Result {\n\t\tconst result = this.handleIgnoreStrategy(value);\n\t\treturn result.isErr() ? result : Result.ok({ ...value, ...result.value } as I);\n\t}\n}\n\nexport const enum ObjectValidatorStrategy {\n\tIgnore,\n\tStrict,\n\tPassthrough\n}\n","import type { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class PassthroughValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn Result.ok(value as T);\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class RecordValidator extends BaseValidator> {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result, ValidationError | CombinedPropertyError> {\n\t\tif (typeof value !== 'object') {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected an object', value));\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected the value to not be null', value));\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected the value to not be an array', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value as Record);\n\t\t}\n\n\t\tconst errors: [string, BaseError][] = [];\n\t\tconst transformed: Record = {};\n\n\t\tfor (const [key, val] of Object.entries(value!)) {\n\t\t\tconst result = this.validator.run(val);\n\t\t\tif (result.isOk()) transformed[key] = result.value;\n\t\t\telse errors.push([key, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedError } from '../lib/errors/CombinedError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class SetValidator extends BaseValidator> {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result, ValidationError | CombinedError> {\n\t\tif (!(values instanceof Set)) {\n\t\t\treturn Result.err(new ValidationError('s.set(T)', 'Expected a set', values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values);\n\t\t}\n\n\t\tconst errors: BaseError[] = [];\n\t\tconst transformed = new Set();\n\n\t\tfor (const value of values) {\n\t\t\tconst result = this.validator.run(value);\n\t\t\tif (result.isOk()) transformed.add(result.value);\n\t\t\telse errors.push(result.error!);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedError(errors));\n\t}\n}\n","/**\n * [RFC-5322](https://datatracker.ietf.org/doc/html/rfc5322)\n * compliant {@link RegExp} to validate an email address\n *\n * @see https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression/201378#201378\n */\nconst accountRegex =\n\t/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")$/;\n\n/**\n * Validates an email address string based on various checks:\n * - It must be a non nullish and non empty string\n * - It must include at least an `@` symbol`\n * - The account name may not exceed 64 characters\n * - The domain name may not exceed 255 characters\n * - The domain must include at least one `.` symbol\n * - Each part of the domain, split by `.` must not exceed 63 characters\n * - The email address must be [RFC-5322](https://datatracker.ietf.org/doc/html/rfc5322) compliant\n * @param email The email to validate\n * @returns `true` if the email is valid, `false` otherwise\n *\n * @remark Based on the following sources:\n * - `email-validator` by [manisharaan](https://github.com/manishsaraan) ([code](https://github.com/manishsaraan/email-validator/blob/master/index.js))\n * - [Comparing E-mail Address Validating Regular Expressions](http://fightingforalostcause.net/misc/2006/compare-email-regex.php)\n * - [Validating Email Addresses by Derrick Pallas](http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx)\n * - [StackOverflow answer by bortzmeyer](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378)\n * - [The wikipedia page on Email addresses](https://en.wikipedia.org/wiki/Email_address)\n */\nexport function validateEmail(email: string): boolean {\n\t// 1. Non-nullish and non-empty string check.\n\t//\n\t// If a nullish or empty email was provided then do an early exit\n\tif (!email) return false;\n\n\t// Find the location of the @ symbol:\n\tconst atIndex = email.indexOf('@');\n\n\t// 2. @ presence check.\n\t//\n\t// If the email does not have the @ symbol, it's automatically invalid:\n\tif (atIndex === -1) return false;\n\n\t// 3. maximum length check.\n\t//\n\t// From @, if exceeds 64 characters, then the\n\t// position of the @ symbol is 64 or greater. In this case, the email is\n\t// invalid:\n\tif (atIndex > 64) return false;\n\n\tconst domainIndex = atIndex + 1;\n\n\t// 7.1. Duplicated @ symbol check.\n\t//\n\t// If there's a second @ symbol, the email is automatically invalid:\n\tif (email.includes('@', domainIndex)) return false;\n\n\t// 4. maximum length check.\n\t//\n\t// From @, if exceeds 255 characters, then it\n\t// means that the amount of characters between the start of and the\n\t// end of the string is separated by 255 or more characters.\n\tif (email.length - domainIndex > 255) return false;\n\n\t// Find the location of the . symbol in :\n\tlet dotIndex = email.indexOf('.', domainIndex);\n\n\t// 5. dot (.) symbol check.\n\t//\n\t// From @, if does not contain a dot (.) symbol,\n\t// then it means the domain is invalid.\n\tif (dotIndex === -1) return false;\n\n\t// 6. parts length.\n\t//\n\t// Assign a temporary variable to store the start of the last read domain\n\t// part, this would be at the start of .\n\t//\n\t// For a part to be correct, it must have at most, 63 characters.\n\t// We repeat this step for every sub-section of contained within\n\t// dot (.) symbols.\n\t//\n\t// The following step is a more optimized version of the following code:\n\t//\n\t// ```javascript\n\t// domain.split('.').some((part) => part.length > 63);\n\t// ```\n\tlet lastDotIndex = domainIndex;\n\tdo {\n\t\tif (dotIndex - lastDotIndex > 63) return false;\n\n\t\tlastDotIndex = dotIndex + 1;\n\t} while ((dotIndex = email.indexOf('.', lastDotIndex)) !== -1);\n\n\t// The loop iterates from the first to the n - 1 part, this line checks for\n\t// the last (n) part:\n\tif (email.length - lastDotIndex > 63) return false;\n\n\t// 7.2. Character checks.\n\t//\n\t// From @:\n\t// - Extract the part by slicing the input from start to the @\n\t// character. Validate afterwards.\n\t// - Extract the part by slicing the input from the start of\n\t// . Validate afterwards.\n\t//\n\t// Note: we inline the variables so isn't created unless the\n\t// check passes.\n\treturn accountRegex.test(email.slice(0, atIndex)) && validateEmailDomain(email.slice(domainIndex));\n}\n\nfunction validateEmailDomain(domain: string): boolean {\n\ttry {\n\t\treturn new URL(`http://${domain}`).hostname === domain;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","/**\n * Code ported from https://github.com/nodejs/node/blob/5fad0b93667ffc6e4def52996b9529ac99b26319/lib/internal/net.js\n */\n\n// IPv4 Segment\nconst v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';\nconst v4Str = `(${v4Seg}[.]){3}${v4Seg}`;\nconst IPv4Reg = new RegExp(`^${v4Str}$`);\n\n// IPv6 Segment\nconst v6Seg = '(?:[0-9a-fA-F]{1,4})';\nconst IPv6Reg = new RegExp(\n\t'^(' +\n\t\t`(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +\n\t\t`(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +\n\t\t`(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +\n\t\t`(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +\n\t\t`(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +\n\t\t`(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +\n\t\t`(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +\n\t\t`(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +\n\t\t')(%[0-9a-zA-Z-.:]{1,})?$'\n);\n\nexport function isIPv4(s: string): boolean {\n\treturn IPv4Reg.test(s);\n}\n\nexport function isIPv6(s: string): boolean {\n\treturn IPv6Reg.test(s);\n}\n\nexport function isIP(s: string): number {\n\tif (isIPv4(s)) return 4;\n\tif (isIPv6(s)) return 6;\n\treturn 0;\n}\n","export const phoneNumberRegex = /^((?:\\+|0{0,2})\\d{1,2}\\s?)?\\(?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$/;\n\nexport function validatePhoneNumber(input: string) {\n\treturn phoneNumberRegex.test(input);\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { BaseConstraintError, type ConstraintErrorNames } from './BaseConstraintError';\n\nexport class MultiplePossibilitiesConstraintError extends BaseConstraintError {\n\tpublic readonly expected: readonly string[];\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: readonly string[]) {\n\t\tsuper(constraint, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tconstraint: this.constraint,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst constraint = options.stylize(this.constraint, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[MultiplePossibilitiesConstraintError: ${constraint}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst verticalLine = options.stylize('|', 'undefined');\n\t\tconst padding = `\\n ${verticalLine} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('MultiplePossibilitiesConstraintError', 'special')} > ${constraint}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\n\t\tconst expectedPadding = `\\n ${verticalLine} - `;\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected any of the following:', 'string')}${expectedPadding}${this.expected\n\t\t\t.map((possible) => options.stylize(possible, 'boolean'))\n\t\t\t.join(expectedPadding)}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","export function combinedErrorFn

(...fns: ErrorFn[]): ErrorFn {\n\tswitch (fns.length) {\n\t\tcase 0:\n\t\t\treturn () => null;\n\t\tcase 1:\n\t\t\treturn fns[0];\n\t\tcase 2: {\n\t\t\tconst [fn0, fn1] = fns;\n\t\t\treturn (...params) => fn0(...params) || fn1(...params);\n\t\t}\n\t\tdefault: {\n\t\t\treturn (...params) => {\n\t\t\t\tfor (const fn of fns) {\n\t\t\t\t\tconst result = fn(...params);\n\t\t\t\t\tif (result) return result;\n\t\t\t\t}\n\n\t\t\t\treturn null;\n\t\t\t};\n\t\t}\n\t}\n}\n\nexport type ErrorFn

= (...params: P) => E | null;\n","import { MultiplePossibilitiesConstraintError } from '../../lib/errors/MultiplePossibilitiesConstraintError';\nimport { combinedErrorFn, ErrorFn } from './common/combinedResultFn';\n\nexport type StringProtocol = `${string}:`;\n\nexport type StringDomain = `${string}.${string}`;\n\nexport interface UrlOptions {\n\tallowedProtocols?: StringProtocol[];\n\tallowedDomains?: StringDomain[];\n}\n\nexport function createUrlValidators(options?: UrlOptions) {\n\tconst fns: ErrorFn<[input: string, url: URL], MultiplePossibilitiesConstraintError>[] = [];\n\n\tif (options?.allowedProtocols?.length) fns.push(allowedProtocolsFn(options.allowedProtocols));\n\tif (options?.allowedDomains?.length) fns.push(allowedDomainsFn(options.allowedDomains));\n\n\treturn combinedErrorFn(...fns);\n}\n\nfunction allowedProtocolsFn(allowedProtocols: StringProtocol[]) {\n\treturn (input: string, url: URL) =>\n\t\tallowedProtocols.includes(url.protocol as StringProtocol)\n\t\t\t? null\n\t\t\t: new MultiplePossibilitiesConstraintError('s.string.url', 'Invalid URL protocol', input, allowedProtocols);\n}\n\nfunction allowedDomainsFn(allowedDomains: StringDomain[]) {\n\treturn (input: string, url: URL) =>\n\t\tallowedDomains.includes(url.hostname as StringDomain)\n\t\t\t? null\n\t\t\t: new MultiplePossibilitiesConstraintError('s.string.url', 'Invalid URL domain', input, allowedDomains);\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { validateEmail } from './util/emailValidator';\nimport { isIP, isIPv4, isIPv6 } from './util/net';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\nimport { validatePhoneNumber } from './util/phoneValidator';\nimport { createUrlValidators } from './util/urlValidators';\n\nexport type StringConstraintName =\n\t| `s.string.${\n\t\t\t| `length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual'}`\n\t\t\t| 'regex'\n\t\t\t| 'url'\n\t\t\t| 'uuid'\n\t\t\t| 'email'\n\t\t\t| `ip${'v4' | 'v6' | ''}`\n\t\t\t| 'date'\n\t\t\t| 'phone'}`;\n\nexport type StringProtocol = `${string}:`;\n\nexport type StringDomain = `${string}.${string}`;\n\nexport interface UrlOptions {\n\tallowedProtocols?: StringProtocol[];\n\tallowedDomains?: StringDomain[];\n}\n\nexport type UUIDVersion = 1 | 3 | 4 | 5;\n\nexport interface StringUuidOptions {\n\tversion?: UUIDVersion | `${UUIDVersion}-${UUIDVersion}` | null;\n\tnullable?: boolean;\n}\n\nfunction stringLengthComparator(comparator: Comparator, name: StringConstraintName, expected: string, length: number): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid string length', input, expected));\n\t\t}\n\t};\n}\n\nexport function stringLengthLessThan(length: number): IConstraint {\n\tconst expected = `expected.length < ${length}`;\n\treturn stringLengthComparator(lessThan, 's.string.lengthLessThan', expected, length);\n}\n\nexport function stringLengthLessThanOrEqual(length: number): IConstraint {\n\tconst expected = `expected.length <= ${length}`;\n\treturn stringLengthComparator(lessThanOrEqual, 's.string.lengthLessThanOrEqual', expected, length);\n}\n\nexport function stringLengthGreaterThan(length: number): IConstraint {\n\tconst expected = `expected.length > ${length}`;\n\treturn stringLengthComparator(greaterThan, 's.string.lengthGreaterThan', expected, length);\n}\n\nexport function stringLengthGreaterThanOrEqual(length: number): IConstraint {\n\tconst expected = `expected.length >= ${length}`;\n\treturn stringLengthComparator(greaterThanOrEqual, 's.string.lengthGreaterThanOrEqual', expected, length);\n}\n\nexport function stringLengthEqual(length: number): IConstraint {\n\tconst expected = `expected.length === ${length}`;\n\treturn stringLengthComparator(equal, 's.string.lengthEqual', expected, length);\n}\n\nexport function stringLengthNotEqual(length: number): IConstraint {\n\tconst expected = `expected.length !== ${length}`;\n\treturn stringLengthComparator(notEqual, 's.string.lengthNotEqual', expected, length);\n}\n\nexport function stringEmail(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validateEmail(input)\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.string.email', 'Invalid email address', input, 'expected to be an email address'));\n\t\t}\n\t};\n}\n\nfunction stringRegexValidator(type: StringConstraintName, expected: string, regex: RegExp): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn regex.test(input) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(type, 'Invalid string format', input, expected));\n\t\t}\n\t};\n}\n\nexport function stringUrl(options?: UrlOptions): IConstraint {\n\tconst validatorFn = createUrlValidators(options);\n\treturn {\n\t\trun(input: string) {\n\t\t\tlet url: URL;\n\t\t\ttry {\n\t\t\t\turl = new URL(input);\n\t\t\t} catch {\n\t\t\t\treturn Result.err(new ExpectedConstraintError('s.string.url', 'Invalid URL', input, 'expected to match an URL'));\n\t\t\t}\n\n\t\t\tconst validatorFnResult = validatorFn(input, url);\n\t\t\tif (validatorFnResult === null) return Result.ok(input);\n\t\t\treturn Result.err(validatorFnResult);\n\t\t}\n\t};\n}\n\nexport function stringIp(version?: 4 | 6): IConstraint {\n\tconst ipVersion = version ? (`v${version}` as const) : '';\n\tconst validatorFn = version === 4 ? isIPv4 : version === 6 ? isIPv6 : isIP;\n\n\tconst name = `s.string.ip${ipVersion}` as const;\n\tconst message = `Invalid IP${ipVersion} address`;\n\tconst expected = `expected to be an IP${ipVersion} address`;\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validatorFn(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, message, input, expected));\n\t\t}\n\t};\n}\n\nexport function stringRegex(regex: RegExp) {\n\treturn stringRegexValidator('s.string.regex', `expected ${regex}.test(expected) to be true`, regex);\n}\n\nexport function stringUuid({ version = 4, nullable = false }: StringUuidOptions = {}) {\n\tversion ??= '1-5';\n\tconst regex = new RegExp(\n\t\t`^(?:[0-9A-F]{8}-[0-9A-F]{4}-[${version}][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}${\n\t\t\tnullable ? '|00000000-0000-0000-0000-000000000000' : ''\n\t\t})$`,\n\t\t'i'\n\t);\n\tconst expected = `expected to match UUID${typeof version === 'number' ? `v${version}` : ` in range of ${version}`}`;\n\treturn stringRegexValidator('s.string.uuid', expected, regex);\n}\n\nexport function stringDate(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\tconst time = Date.parse(input);\n\n\t\t\treturn Number.isNaN(time)\n\t\t\t\t? Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError(\n\t\t\t\t\t\t\t's.string.date',\n\t\t\t\t\t\t\t'Invalid date string',\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t'expected to be a valid date string (in the ISO 8601 or ECMA-262 format)'\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Result.ok(input);\n\t\t}\n\t};\n}\n\nexport function stringPhone(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validatePhoneNumber(input)\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.string.phone', 'Invalid phone number', input, 'expected to be a phone number'));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tstringDate,\n\tstringEmail,\n\tstringIp,\n\tstringLengthEqual,\n\tstringLengthGreaterThan,\n\tstringLengthGreaterThanOrEqual,\n\tstringLengthLessThan,\n\tstringLengthLessThanOrEqual,\n\tstringLengthNotEqual,\n\tstringPhone,\n\tstringRegex,\n\tstringUrl,\n\tstringUuid,\n\tStringUuidOptions,\n\ttype UrlOptions\n} from '../constraints/StringConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class StringValidator extends BaseValidator {\n\tpublic lengthLessThan(length: number): this {\n\t\treturn this.addConstraint(stringLengthLessThan(length) as IConstraint);\n\t}\n\n\tpublic lengthLessThanOrEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthLessThanOrEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthGreaterThan(length: number): this {\n\t\treturn this.addConstraint(stringLengthGreaterThan(length) as IConstraint);\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthGreaterThanOrEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthNotEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthNotEqual(length) as IConstraint);\n\t}\n\n\tpublic get email(): this {\n\t\treturn this.addConstraint(stringEmail() as IConstraint);\n\t}\n\n\tpublic url(options?: UrlOptions): this {\n\t\treturn this.addConstraint(stringUrl(options) as IConstraint);\n\t}\n\n\tpublic uuid(options?: StringUuidOptions): this {\n\t\treturn this.addConstraint(stringUuid(options) as IConstraint);\n\t}\n\n\tpublic regex(regex: RegExp): this {\n\t\treturn this.addConstraint(stringRegex(regex) as IConstraint);\n\t}\n\n\tpublic get date() {\n\t\treturn this.addConstraint(stringDate() as IConstraint);\n\t}\n\n\tpublic get ipv4(): this {\n\t\treturn this.ip(4);\n\t}\n\n\tpublic get ipv6(): this {\n\t\treturn this.ip(6);\n\t}\n\n\tpublic ip(version?: 4 | 6): this {\n\t\treturn this.addConstraint(stringIp(version) as IConstraint);\n\t}\n\n\tpublic phone(): this {\n\t\treturn this.addConstraint(stringPhone() as IConstraint);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'string' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.string', 'Expected a string primitive', value));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class TupleValidator extends BaseValidator<[...T]> {\n\tprivate readonly validators: BaseValidator<[...T]>[] = [];\n\n\tpublic constructor(validators: BaseValidator<[...T]>[], constraints: readonly IConstraint<[...T]>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validators = validators;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validators, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result<[...T], ValidationError | CombinedPropertyError> {\n\t\tif (!Array.isArray(values)) {\n\t\t\treturn Result.err(new ValidationError('s.tuple(T)', 'Expected an array', values));\n\t\t}\n\n\t\tif (values.length !== this.validators.length) {\n\t\t\treturn Result.err(new ValidationError('s.tuple(T)', `Expected an array of length ${this.validators.length}`, values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values as [...T]);\n\t\t}\n\n\t\tconst errors: [number, BaseError][] = [];\n\t\tconst transformed: T = [] as unknown as T;\n\n\t\tfor (let i = 0; i < values.length; i++) {\n\t\t\tconst result = this.validators[i].run(values[i]);\n\t\t\tif (result.isOk()) transformed.push(result.value);\n\t\t\telse errors.push([i, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class MapValidator extends BaseValidator> {\n\tprivate readonly keyValidator: BaseValidator;\n\tprivate readonly valueValidator: BaseValidator;\n\n\tpublic constructor(keyValidator: BaseValidator, valueValidator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.keyValidator = keyValidator;\n\t\tthis.valueValidator = valueValidator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.keyValidator, this.valueValidator, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result, ValidationError | CombinedPropertyError> {\n\t\tif (!(value instanceof Map)) {\n\t\t\treturn Result.err(new ValidationError('s.map(K, V)', 'Expected a map', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value);\n\t\t}\n\n\t\tconst errors: [string, BaseError][] = [];\n\t\tconst transformed = new Map();\n\n\t\tfor (const [key, val] of value.entries()) {\n\t\t\tconst keyResult = this.keyValidator.run(key);\n\t\t\tconst valueResult = this.valueValidator.run(val);\n\t\t\tconst { length } = errors;\n\t\t\tif (keyResult.isErr()) errors.push([key, keyResult.error]);\n\t\t\tif (valueResult.isErr()) errors.push([key, valueResult.error]);\n\t\t\tif (errors.length === length) transformed.set(keyResult.value!, valueResult.value!);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { Result } from '../lib/Result';\nimport type { IConstraint, Unwrap } from '../type-exports';\nimport { BaseValidator, ValidatorError } from './imports';\n\nexport class LazyValidator, R = Unwrap> extends BaseValidator {\n\tprivate readonly validator: (value: unknown) => T;\n\n\tpublic constructor(validator: (value: unknown) => T, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result {\n\t\treturn this.validator(values).run(values) as Result;\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class UnknownEnumValueError extends BaseError {\n\tpublic readonly value: string | number;\n\tpublic readonly enumKeys: string[];\n\tpublic readonly enumMappings: Map;\n\n\tpublic constructor(value: string | number, keys: string[], enumMappings: Map) {\n\t\tsuper('Expected the value to be one of the following enum values:');\n\n\t\tthis.value = value;\n\t\tthis.enumKeys = keys;\n\t\tthis.enumMappings = enumMappings;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalue: this.value,\n\t\t\tenumKeys: this.enumKeys,\n\t\t\tenumMappings: [...this.enumMappings.entries()]\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst value = options.stylize(this.value.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[UnknownEnumValueError: ${value}]`, 'special');\n\t\t}\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst pairs = this.enumKeys\n\t\t\t.map((key) => {\n\t\t\t\tconst enumValue = this.enumMappings.get(key)!;\n\t\t\t\treturn `${options.stylize(key, 'string')} or ${options.stylize(\n\t\t\t\t\tenumValue.toString(),\n\t\t\t\t\ttypeof enumValue === 'number' ? 'number' : 'string'\n\t\t\t\t)}`;\n\t\t\t})\n\t\t\t.join(padding);\n\n\t\tconst header = `${options.stylize('UnknownEnumValueError', 'special')} > ${value}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst pairsBlock = `${padding}${pairs}`;\n\t\treturn `${header}\\n ${message}\\n${pairsBlock}`;\n\t}\n}\n","import { UnknownEnumValueError } from '../lib/errors/UnknownEnumValueError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NativeEnumValidator extends BaseValidator {\n\tpublic readonly enumShape: T;\n\tpublic readonly hasNumericElements: boolean = false;\n\tprivate readonly enumKeys: string[];\n\tprivate readonly enumMapping = new Map();\n\n\tpublic constructor(enumShape: T) {\n\t\tsuper();\n\t\tthis.enumShape = enumShape;\n\n\t\tthis.enumKeys = Object.keys(enumShape).filter((key) => {\n\t\t\treturn typeof enumShape[enumShape[key]] !== 'number';\n\t\t});\n\n\t\tfor (const key of this.enumKeys) {\n\t\t\tconst enumValue = enumShape[key] as T[keyof T];\n\n\t\t\tthis.enumMapping.set(key, enumValue);\n\t\t\tthis.enumMapping.set(enumValue, enumValue);\n\n\t\t\tif (typeof enumValue === 'number') {\n\t\t\t\tthis.hasNumericElements = true;\n\t\t\t\tthis.enumMapping.set(`${enumValue}`, enumValue);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected override handle(value: unknown): Result {\n\t\tconst typeOfValue = typeof value;\n\n\t\tif (typeOfValue === 'number') {\n\t\t\tif (!this.hasNumericElements) {\n\t\t\t\treturn Result.err(new ValidationError('s.nativeEnum(T)', 'Expected the value to be a string', value));\n\t\t\t}\n\t\t} else if (typeOfValue !== 'string') {\n\t\t\t// typeOfValue !== 'number' is implied here\n\t\t\treturn Result.err(new ValidationError('s.nativeEnum(T)', 'Expected the value to be a string or number', value));\n\t\t}\n\n\t\tconst casted = value as string | number;\n\n\t\tconst possibleEnumValue = this.enumMapping.get(casted);\n\n\t\treturn typeof possibleEnumValue === 'undefined'\n\t\t\t? Result.err(new UnknownEnumValueError(casted, this.enumKeys, this.enumMapping))\n\t\t\t: Result.ok(possibleEnumValue);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.enumShape]);\n\t}\n}\n\nexport interface NativeEnumLike {\n\t[key: string]: string | number;\n\t[key: number]: string;\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\nimport type { TypedArray } from './util/typedArray';\n\nexport type TypedArrayConstraintName = `s.typedArray(T).${'byteLength' | 'length'}${\n\t| 'LessThan'\n\t| 'LessThanOrEqual'\n\t| 'GreaterThan'\n\t| 'GreaterThanOrEqual'\n\t| 'Equal'\n\t| 'NotEqual'\n\t| 'Range'\n\t| 'RangeInclusive'\n\t| 'RangeExclusive'}`;\n\nfunction typedArrayByteLengthComparator(\n\tcomparator: Comparator,\n\tname: TypedArrayConstraintName,\n\texpected: string,\n\tlength: number\n): IConstraint {\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn comparator(input.byteLength, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Typed Array byte length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.byteLength < ${value}`;\n\treturn typedArrayByteLengthComparator(lessThan, 's.typedArray(T).byteLengthLessThan', expected, value);\n}\n\nexport function typedArrayByteLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength <= ${value}`;\n\treturn typedArrayByteLengthComparator(lessThanOrEqual, 's.typedArray(T).byteLengthLessThanOrEqual', expected, value);\n}\n\nexport function typedArrayByteLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.byteLength > ${value}`;\n\treturn typedArrayByteLengthComparator(greaterThan, 's.typedArray(T).byteLengthGreaterThan', expected, value);\n}\n\nexport function typedArrayByteLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength >= ${value}`;\n\treturn typedArrayByteLengthComparator(greaterThanOrEqual, 's.typedArray(T).byteLengthGreaterThanOrEqual', expected, value);\n}\n\nexport function typedArrayByteLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength === ${value}`;\n\treturn typedArrayByteLengthComparator(equal, 's.typedArray(T).byteLengthEqual', expected, value);\n}\n\nexport function typedArrayByteLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength !== ${value}`;\n\treturn typedArrayByteLengthComparator(notEqual, 's.typedArray(T).byteLengthNotEqual', expected, value);\n}\n\nexport function typedArrayByteLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.byteLength >= ${start} && expected.byteLength < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength >= start && input.byteLength < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).byteLengthRange', 'Invalid Typed Array byte length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthRangeInclusive(start: number, end: number) {\n\tconst expected = `expected.byteLength >= ${start} && expected.byteLength <= ${end}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength >= start && input.byteLength <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError('s.typedArray(T).byteLengthRangeInclusive', 'Invalid Typed Array byte length', input, expected)\n\t\t\t\t );\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.byteLength > ${startAfter} && expected.byteLength < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength > startAfter && input.byteLength < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError('s.typedArray(T).byteLengthRangeExclusive', 'Invalid Typed Array byte length', input, expected)\n\t\t\t\t );\n\t\t}\n\t};\n}\n\nfunction typedArrayLengthComparator(\n\tcomparator: Comparator,\n\tname: TypedArrayConstraintName,\n\texpected: string,\n\tlength: number\n): IConstraint {\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.length < ${value}`;\n\treturn typedArrayLengthComparator(lessThan, 's.typedArray(T).lengthLessThan', expected, value);\n}\n\nexport function typedArrayLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length <= ${value}`;\n\treturn typedArrayLengthComparator(lessThanOrEqual, 's.typedArray(T).lengthLessThanOrEqual', expected, value);\n}\n\nexport function typedArrayLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.length > ${value}`;\n\treturn typedArrayLengthComparator(greaterThan, 's.typedArray(T).lengthGreaterThan', expected, value);\n}\n\nexport function typedArrayLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length >= ${value}`;\n\treturn typedArrayLengthComparator(greaterThanOrEqual, 's.typedArray(T).lengthGreaterThanOrEqual', expected, value);\n}\n\nexport function typedArrayLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.length === ${value}`;\n\treturn typedArrayLengthComparator(equal, 's.typedArray(T).lengthEqual', expected, value);\n}\n\nexport function typedArrayLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.length !== ${value}`;\n\treturn typedArrayLengthComparator(notEqual, 's.typedArray(T).lengthNotEqual', expected, value);\n}\n\nexport function typedArrayLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length >= start && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRange', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthRangeInclusive(start: number, end: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length <= ${end}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length >= start && input.length <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRangeInclusive', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length > startAfter && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRangeExclusive', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n","const vowels = ['a', 'e', 'i', 'o', 'u'];\n\nexport const aOrAn = (word: string) => {\n\treturn `${vowels.includes(word[0].toLowerCase()) ? 'an' : 'a'} ${word}`;\n};\n","export type TypedArray =\n\t| Int8Array\n\t| Uint8Array\n\t| Uint8ClampedArray\n\t| Int16Array\n\t| Uint16Array\n\t| Int32Array\n\t| Uint32Array\n\t| Float32Array\n\t| Float64Array\n\t| BigInt64Array\n\t| BigUint64Array;\n\nexport const TypedArrays = {\n\tInt8Array: (x: unknown): x is Int8Array => x instanceof Int8Array,\n\tUint8Array: (x: unknown): x is Uint8Array => x instanceof Uint8Array,\n\tUint8ClampedArray: (x: unknown): x is Uint8ClampedArray => x instanceof Uint8ClampedArray,\n\tInt16Array: (x: unknown): x is Int16Array => x instanceof Int16Array,\n\tUint16Array: (x: unknown): x is Uint16Array => x instanceof Uint16Array,\n\tInt32Array: (x: unknown): x is Int32Array => x instanceof Int32Array,\n\tUint32Array: (x: unknown): x is Uint32Array => x instanceof Uint32Array,\n\tFloat32Array: (x: unknown): x is Float32Array => x instanceof Float32Array,\n\tFloat64Array: (x: unknown): x is Float64Array => x instanceof Float64Array,\n\tBigInt64Array: (x: unknown): x is BigInt64Array => x instanceof BigInt64Array,\n\tBigUint64Array: (x: unknown): x is BigUint64Array => x instanceof BigUint64Array,\n\tTypedArray: (x: unknown): x is TypedArray => ArrayBuffer.isView(x) && !(x instanceof DataView)\n} as const;\n\nexport type TypedArrayName = keyof typeof TypedArrays;\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\ttypedArrayByteLengthEqual,\n\ttypedArrayByteLengthGreaterThan,\n\ttypedArrayByteLengthGreaterThanOrEqual,\n\ttypedArrayByteLengthLessThan,\n\ttypedArrayByteLengthLessThanOrEqual,\n\ttypedArrayByteLengthNotEqual,\n\ttypedArrayByteLengthRange,\n\ttypedArrayByteLengthRangeExclusive,\n\ttypedArrayByteLengthRangeInclusive,\n\ttypedArrayLengthEqual,\n\ttypedArrayLengthGreaterThan,\n\ttypedArrayLengthGreaterThanOrEqual,\n\ttypedArrayLengthLessThan,\n\ttypedArrayLengthLessThanOrEqual,\n\ttypedArrayLengthNotEqual,\n\ttypedArrayLengthRange,\n\ttypedArrayLengthRangeExclusive,\n\ttypedArrayLengthRangeInclusive\n} from '../constraints/TypedArrayLengthConstraints';\nimport { aOrAn } from '../constraints/util/common/vowels';\nimport { TypedArray, TypedArrayName, TypedArrays } from '../constraints/util/typedArray';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class TypedArrayValidator extends BaseValidator {\n\tprivate readonly type: TypedArrayName;\n\n\tpublic constructor(type: TypedArrayName, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.type = type;\n\t}\n\n\tpublic byteLengthLessThan(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthLessThan(length));\n\t}\n\n\tpublic byteLengthLessThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthLessThanOrEqual(length));\n\t}\n\n\tpublic byteLengthGreaterThan(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthGreaterThan(length));\n\t}\n\n\tpublic byteLengthGreaterThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthGreaterThanOrEqual(length));\n\t}\n\n\tpublic byteLengthEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthEqual(length));\n\t}\n\n\tpublic byteLengthNotEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthNotEqual(length));\n\t}\n\n\tpublic byteLengthRange(start: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRange(start, endBefore));\n\t}\n\n\tpublic byteLengthRangeInclusive(startAt: number, endAt: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRangeInclusive(startAt, endAt) as IConstraint);\n\t}\n\n\tpublic byteLengthRangeExclusive(startAfter: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRangeExclusive(startAfter, endBefore));\n\t}\n\n\tpublic lengthLessThan(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthLessThan(length));\n\t}\n\n\tpublic lengthLessThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthLessThanOrEqual(length));\n\t}\n\n\tpublic lengthGreaterThan(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthGreaterThan(length));\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthGreaterThanOrEqual(length));\n\t}\n\n\tpublic lengthEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthEqual(length));\n\t}\n\n\tpublic lengthNotEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthNotEqual(length));\n\t}\n\n\tpublic lengthRange(start: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayLengthRange(start, endBefore));\n\t}\n\n\tpublic lengthRangeInclusive(startAt: number, endAt: number) {\n\t\treturn this.addConstraint(typedArrayLengthRangeInclusive(startAt, endAt));\n\t}\n\n\tpublic lengthRangeExclusive(startAfter: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayLengthRangeExclusive(startAfter, endBefore));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.type, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn TypedArrays[this.type](value)\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.typedArray', `Expected ${aOrAn(this.type)}`, value));\n\t}\n}\n","import type { TypedArray, TypedArrayName } from '../constraints/util/typedArray';\nimport type { Unwrap, UnwrapTuple } from '../lib/util-types';\nimport {\n\tArrayValidator,\n\tBaseValidator,\n\tBigIntValidator,\n\tBooleanValidator,\n\tDateValidator,\n\tInstanceValidator,\n\tLiteralValidator,\n\tMapValidator,\n\tNeverValidator,\n\tNullishValidator,\n\tNumberValidator,\n\tObjectValidator,\n\tPassthroughValidator,\n\tRecordValidator,\n\tSetValidator,\n\tStringValidator,\n\tTupleValidator,\n\tUnionValidator\n} from '../validators/imports';\nimport { LazyValidator } from '../validators/LazyValidator';\nimport { NativeEnumLike, NativeEnumValidator } from '../validators/NativeEnumValidator';\nimport { TypedArrayValidator } from '../validators/TypedArrayValidator';\nimport type { Constructor, MappedObjectValidator } from './util-types';\n\nexport class Shapes {\n\tpublic get string() {\n\t\treturn new StringValidator();\n\t}\n\n\tpublic get number() {\n\t\treturn new NumberValidator();\n\t}\n\n\tpublic get bigint() {\n\t\treturn new BigIntValidator();\n\t}\n\n\tpublic get boolean() {\n\t\treturn new BooleanValidator();\n\t}\n\n\tpublic get date() {\n\t\treturn new DateValidator();\n\t}\n\n\tpublic object(shape: MappedObjectValidator) {\n\t\treturn new ObjectValidator(shape);\n\t}\n\n\tpublic get undefined() {\n\t\treturn this.literal(undefined);\n\t}\n\n\tpublic get null() {\n\t\treturn this.literal(null);\n\t}\n\n\tpublic get nullish() {\n\t\treturn new NullishValidator();\n\t}\n\n\tpublic get any() {\n\t\treturn new PassthroughValidator();\n\t}\n\n\tpublic get unknown() {\n\t\treturn new PassthroughValidator();\n\t}\n\n\tpublic get never() {\n\t\treturn new NeverValidator();\n\t}\n\n\tpublic enum(...values: readonly T[]) {\n\t\treturn this.union(...values.map((value) => this.literal(value)));\n\t}\n\n\tpublic nativeEnum(enumShape: T): NativeEnumValidator {\n\t\treturn new NativeEnumValidator(enumShape);\n\t}\n\n\tpublic literal(value: T): BaseValidator {\n\t\tif (value instanceof Date) return this.date.equal(value) as unknown as BaseValidator;\n\t\treturn new LiteralValidator(value);\n\t}\n\n\tpublic instance(expected: Constructor): InstanceValidator {\n\t\treturn new InstanceValidator(expected);\n\t}\n\n\tpublic union[]]>(...validators: [...T]): UnionValidator> {\n\t\treturn new UnionValidator(validators);\n\t}\n\n\tpublic array(validator: BaseValidator): ArrayValidator;\n\tpublic array(validator: BaseValidator): ArrayValidator;\n\tpublic array(validator: BaseValidator) {\n\t\treturn new ArrayValidator(validator);\n\t}\n\n\tpublic typedArray(type: TypedArrayName = 'TypedArray') {\n\t\treturn new TypedArrayValidator(type);\n\t}\n\n\tpublic get int8Array() {\n\t\treturn this.typedArray('Int8Array');\n\t}\n\n\tpublic get uint8Array() {\n\t\treturn this.typedArray('Uint8Array');\n\t}\n\n\tpublic get uint8ClampedArray() {\n\t\treturn this.typedArray('Uint8ClampedArray');\n\t}\n\n\tpublic get int16Array() {\n\t\treturn this.typedArray('Int16Array');\n\t}\n\n\tpublic get uint16Array() {\n\t\treturn this.typedArray('Uint16Array');\n\t}\n\n\tpublic get int32Array() {\n\t\treturn this.typedArray('Int32Array');\n\t}\n\n\tpublic get uint32Array() {\n\t\treturn this.typedArray('Uint32Array');\n\t}\n\n\tpublic get float32Array() {\n\t\treturn this.typedArray('Float32Array');\n\t}\n\n\tpublic get float64Array() {\n\t\treturn this.typedArray('Float64Array');\n\t}\n\n\tpublic get bigInt64Array() {\n\t\treturn this.typedArray('BigInt64Array');\n\t}\n\n\tpublic get bigUint64Array() {\n\t\treturn this.typedArray('BigUint64Array');\n\t}\n\n\tpublic tuple[]]>(validators: [...T]): TupleValidator> {\n\t\treturn new TupleValidator(validators);\n\t}\n\n\tpublic set(validator: BaseValidator) {\n\t\treturn new SetValidator(validator);\n\t}\n\n\tpublic record(validator: BaseValidator) {\n\t\treturn new RecordValidator(validator);\n\t}\n\n\tpublic map(keyValidator: BaseValidator, valueValidator: BaseValidator) {\n\t\treturn new MapValidator(keyValidator, valueValidator);\n\t}\n\n\tpublic lazy>(validator: (value: unknown) => T) {\n\t\treturn new LazyValidator(validator);\n\t}\n}\n","import { Shapes } from './lib/Shapes';\n\nexport const s = new Shapes();\n\nexport * from './lib/configs';\nexport * from './lib/errors/BaseError';\nexport * from './lib/errors/CombinedError';\nexport * from './lib/errors/CombinedPropertyError';\nexport * from './lib/errors/ExpectedConstraintError';\nexport * from './lib/errors/ExpectedValidationError';\nexport * from './lib/errors/MissingPropertyError';\nexport * from './lib/errors/MultiplePossibilitiesConstraintError';\nexport * from './lib/errors/UnknownEnumValueError';\nexport * from './lib/errors/UnknownPropertyError';\nexport * from './lib/errors/ValidationError';\nexport * from './lib/Result';\nexport * from './type-exports';\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/dist/index.js b/node_modules/@sapphire/shapeshift/dist/index.js new file mode 100644 index 0000000..8e3bb97 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/dist/index.js @@ -0,0 +1,2232 @@ +'use strict'; + +var get = require('lodash/get.js'); +var util = require('util'); +var fastDeepEqual = require('fast-deep-equal/es6/index.js'); +var uniqWith = require('lodash/uniqWith.js'); + +var __defProp = Object.defineProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + +// src/lib/configs.ts +var validationEnabled = true; +function setGlobalValidationEnabled(enabled) { + validationEnabled = enabled; +} +__name(setGlobalValidationEnabled, "setGlobalValidationEnabled"); +function getGlobalValidationEnabled() { + return validationEnabled; +} +__name(getGlobalValidationEnabled, "getGlobalValidationEnabled"); + +// src/lib/Result.ts +var Result = class { + constructor(success, value, error) { + this.success = success; + if (success) { + this.value = value; + } else { + this.error = error; + } + } + isOk() { + return this.success; + } + isErr() { + return !this.success; + } + unwrap() { + if (this.isOk()) + return this.value; + throw this.error; + } + static ok(value) { + return new Result(true, value); + } + static err(error) { + return new Result(false, void 0, error); + } +}; +__name(Result, "Result"); + +// src/validators/util/getValue.ts +function getValue(valueOrFn) { + return typeof valueOrFn === "function" ? valueOrFn() : valueOrFn; +} +__name(getValue, "getValue"); + +// src/lib/errors/BaseError.ts +var customInspectSymbol = Symbol.for("nodejs.util.inspect.custom"); +var customInspectSymbolStackLess = Symbol.for("nodejs.util.inspect.custom.stack-less"); +var BaseError = class extends Error { + [customInspectSymbol](depth, options) { + return `${this[customInspectSymbolStackLess](depth, options)} +${this.stack.slice(this.stack.indexOf("\n"))}`; + } +}; +__name(BaseError, "BaseError"); + +// src/lib/errors/BaseConstraintError.ts +var BaseConstraintError = class extends BaseError { + constructor(constraint, message, given) { + super(message); + this.constraint = constraint; + this.given = given; + } +}; +__name(BaseConstraintError, "BaseConstraintError"); + +// src/lib/errors/ExpectedConstraintError.ts +var ExpectedConstraintError = class extends BaseConstraintError { + constructor(constraint, message, given, expected) { + super(constraint, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + constraint: this.constraint, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const constraint = options.stylize(this.constraint, "string"); + if (depth < 0) { + return options.stylize(`[ExpectedConstraintError: ${constraint}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = util.inspect(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ExpectedConstraintError", "special")} > ${constraint}`; + const message = options.stylize(this.message, "regexp"); + const expectedBlock = ` + ${options.stylize("Expected: ", "string")}${options.stylize(this.expected, "boolean")}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } +}; +__name(ExpectedConstraintError, "ExpectedConstraintError"); + +// src/constraints/ObjectConstrains.ts +function whenConstraint(key, options, validator) { + return { + run(input, parent) { + if (!parent) { + return Result.err(new ExpectedConstraintError("s.object(T.when)", "Validator has no parent", parent, "Validator to have a parent")); + } + const isKeyArray = Array.isArray(key); + const value = isKeyArray ? key.map((k) => get(parent, k)) : get(parent, key); + const predicate = resolveBooleanIs(options, value, isKeyArray) ? options.then : options.otherwise; + if (predicate) { + return predicate(validator).run(input); + } + return Result.ok(input); + } + }; +} +__name(whenConstraint, "whenConstraint"); +function resolveBooleanIs(options, value, isKeyArray) { + if (options.is === void 0) { + return isKeyArray ? !value.some((val) => !val) : Boolean(value); + } + if (typeof options.is === "function") { + return options.is(value); + } + return value === options.is; +} +__name(resolveBooleanIs, "resolveBooleanIs"); + +// src/validators/BaseValidator.ts +var BaseValidator = class { + constructor(constraints = []) { + this.constraints = []; + this.isValidationEnabled = null; + this.constraints = constraints; + } + setParent(parent) { + this.parent = parent; + return this; + } + get optional() { + return new UnionValidator([new LiteralValidator(void 0), this.clone()]); + } + get nullable() { + return new UnionValidator([new LiteralValidator(null), this.clone()]); + } + get nullish() { + return new UnionValidator([new NullishValidator(), this.clone()]); + } + get array() { + return new ArrayValidator(this.clone()); + } + get set() { + return new SetValidator(this.clone()); + } + or(...predicates) { + return new UnionValidator([this.clone(), ...predicates]); + } + transform(cb) { + return this.addConstraint({ run: (input) => Result.ok(cb(input)) }); + } + reshape(cb) { + return this.addConstraint({ run: cb }); + } + default(value) { + return new DefaultValidator(this.clone(), value); + } + when(key, options) { + return this.addConstraint(whenConstraint(key, options, this)); + } + run(value) { + let result = this.handle(value); + if (result.isErr()) + return result; + for (const constraint of this.constraints) { + result = constraint.run(result.value, this.parent); + if (result.isErr()) + break; + } + return result; + } + parse(value) { + if (!this.shouldRunConstraints) { + return this.handle(value).unwrap(); + } + return this.constraints.reduce((v, constraint) => constraint.run(v).unwrap(), this.handle(value).unwrap()); + } + is(value) { + return this.run(value).isOk(); + } + setValidationEnabled(isValidationEnabled) { + const clone = this.clone(); + clone.isValidationEnabled = isValidationEnabled; + return clone; + } + getValidationEnabled() { + return getValue(this.isValidationEnabled); + } + get shouldRunConstraints() { + return getValue(this.isValidationEnabled) ?? getGlobalValidationEnabled(); + } + clone() { + const clone = Reflect.construct(this.constructor, [this.constraints]); + clone.isValidationEnabled = this.isValidationEnabled; + return clone; + } + addConstraint(constraint) { + const clone = this.clone(); + clone.constraints = clone.constraints.concat(constraint); + return clone; + } +}; +__name(BaseValidator, "BaseValidator"); +function isUnique(input) { + if (input.length < 2) + return true; + const uniqueArray2 = uniqWith(input, fastDeepEqual); + return uniqueArray2.length === input.length; +} +__name(isUnique, "isUnique"); + +// src/constraints/util/operators.ts +function lessThan(a, b) { + return a < b; +} +__name(lessThan, "lessThan"); +function lessThanOrEqual(a, b) { + return a <= b; +} +__name(lessThanOrEqual, "lessThanOrEqual"); +function greaterThan(a, b) { + return a > b; +} +__name(greaterThan, "greaterThan"); +function greaterThanOrEqual(a, b) { + return a >= b; +} +__name(greaterThanOrEqual, "greaterThanOrEqual"); +function equal(a, b) { + return a === b; +} +__name(equal, "equal"); +function notEqual(a, b) { + return a !== b; +} +__name(notEqual, "notEqual"); + +// src/constraints/ArrayConstraints.ts +function arrayLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Array length", input, expected)); + } + }; +} +__name(arrayLengthComparator, "arrayLengthComparator"); +function arrayLengthLessThan(value) { + const expected = `expected.length < ${value}`; + return arrayLengthComparator(lessThan, "s.array(T).lengthLessThan", expected, value); +} +__name(arrayLengthLessThan, "arrayLengthLessThan"); +function arrayLengthLessThanOrEqual(value) { + const expected = `expected.length <= ${value}`; + return arrayLengthComparator(lessThanOrEqual, "s.array(T).lengthLessThanOrEqual", expected, value); +} +__name(arrayLengthLessThanOrEqual, "arrayLengthLessThanOrEqual"); +function arrayLengthGreaterThan(value) { + const expected = `expected.length > ${value}`; + return arrayLengthComparator(greaterThan, "s.array(T).lengthGreaterThan", expected, value); +} +__name(arrayLengthGreaterThan, "arrayLengthGreaterThan"); +function arrayLengthGreaterThanOrEqual(value) { + const expected = `expected.length >= ${value}`; + return arrayLengthComparator(greaterThanOrEqual, "s.array(T).lengthGreaterThanOrEqual", expected, value); +} +__name(arrayLengthGreaterThanOrEqual, "arrayLengthGreaterThanOrEqual"); +function arrayLengthEqual(value) { + const expected = `expected.length === ${value}`; + return arrayLengthComparator(equal, "s.array(T).lengthEqual", expected, value); +} +__name(arrayLengthEqual, "arrayLengthEqual"); +function arrayLengthNotEqual(value) { + const expected = `expected.length !== ${value}`; + return arrayLengthComparator(notEqual, "s.array(T).lengthNotEqual", expected, value); +} +__name(arrayLengthNotEqual, "arrayLengthNotEqual"); +function arrayLengthRange(start, endBefore) { + const expected = `expected.length >= ${start} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length >= start && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRange", "Invalid Array length", input, expected)); + } + }; +} +__name(arrayLengthRange, "arrayLengthRange"); +function arrayLengthRangeInclusive(start, end) { + const expected = `expected.length >= ${start} && expected.length <= ${end}`; + return { + run(input) { + return input.length >= start && input.length <= end ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRangeInclusive", "Invalid Array length", input, expected)); + } + }; +} +__name(arrayLengthRangeInclusive, "arrayLengthRangeInclusive"); +function arrayLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length > startAfter && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRangeExclusive", "Invalid Array length", input, expected)); + } + }; +} +__name(arrayLengthRangeExclusive, "arrayLengthRangeExclusive"); +var uniqueArray = { + run(input) { + return isUnique(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).unique", "Array values are not unique", input, "Expected all values to be unique")); + } +}; + +// src/lib/errors/CombinedPropertyError.ts +var CombinedPropertyError = class extends BaseError { + constructor(errors) { + super("Received one or more errors"); + this.errors = errors; + } + [customInspectSymbolStackLess](depth, options) { + if (depth < 0) { + return options.stylize("[CombinedPropertyError]", "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const header = `${options.stylize("CombinedPropertyError", "special")} (${options.stylize(this.errors.length.toString(), "number")})`; + const message = options.stylize(this.message, "regexp"); + const errors = this.errors.map(([key, error]) => { + const property = CombinedPropertyError.formatProperty(key, options); + const body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\n/g, padding); + return ` input${property}${padding}${body}`; + }).join("\n\n"); + return `${header} + ${message} + +${errors}`; + } + static formatProperty(key, options) { + if (typeof key === "string") + return options.stylize(`.${key}`, "symbol"); + if (typeof key === "number") + return `[${options.stylize(key.toString(), "number")}]`; + return `[${options.stylize("Symbol", "symbol")}(${key.description})]`; + } +}; +__name(CombinedPropertyError, "CombinedPropertyError"); +var ValidationError = class extends BaseError { + constructor(validator, message, given) { + super(message); + this.validator = validator; + this.given = given; + } + toJSON() { + return { + name: this.name, + validator: this.validator, + given: this.given + }; + } + [customInspectSymbolStackLess](depth, options) { + const validator = options.stylize(this.validator, "string"); + if (depth < 0) { + return options.stylize(`[ValidationError: ${validator}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = util.inspect(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ValidationError", "special")} > ${validator}`; + const message = options.stylize(this.message, "regexp"); + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${givenBlock}`; + } +}; +__name(ValidationError, "ValidationError"); + +// src/validators/ArrayValidator.ts +var ArrayValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + lengthLessThan(length) { + return this.addConstraint(arrayLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(arrayLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(arrayLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(arrayLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(arrayLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(arrayLengthNotEqual(length)); + } + lengthRange(start, endBefore) { + return this.addConstraint(arrayLengthRange(start, endBefore)); + } + lengthRangeInclusive(startAt, endAt) { + return this.addConstraint(arrayLengthRangeInclusive(startAt, endAt)); + } + lengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(arrayLengthRangeExclusive(startAfter, endBefore)); + } + get unique() { + return this.addConstraint(uniqueArray); + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + if (!Array.isArray(values)) { + return Result.err(new ValidationError("s.array(T)", "Expected an array", values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = []; + for (let i = 0; i < values.length; i++) { + const result = this.validator.run(values[i]); + if (result.isOk()) + transformed.push(result.value); + else + errors.push([i, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } +}; +__name(ArrayValidator, "ArrayValidator"); + +// src/constraints/BigIntConstraints.ts +function bigintComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input, number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid bigint value", input, expected)); + } + }; +} +__name(bigintComparator, "bigintComparator"); +function bigintLessThan(value) { + const expected = `expected < ${value}n`; + return bigintComparator(lessThan, "s.bigint.lessThan", expected, value); +} +__name(bigintLessThan, "bigintLessThan"); +function bigintLessThanOrEqual(value) { + const expected = `expected <= ${value}n`; + return bigintComparator(lessThanOrEqual, "s.bigint.lessThanOrEqual", expected, value); +} +__name(bigintLessThanOrEqual, "bigintLessThanOrEqual"); +function bigintGreaterThan(value) { + const expected = `expected > ${value}n`; + return bigintComparator(greaterThan, "s.bigint.greaterThan", expected, value); +} +__name(bigintGreaterThan, "bigintGreaterThan"); +function bigintGreaterThanOrEqual(value) { + const expected = `expected >= ${value}n`; + return bigintComparator(greaterThanOrEqual, "s.bigint.greaterThanOrEqual", expected, value); +} +__name(bigintGreaterThanOrEqual, "bigintGreaterThanOrEqual"); +function bigintEqual(value) { + const expected = `expected === ${value}n`; + return bigintComparator(equal, "s.bigint.equal", expected, value); +} +__name(bigintEqual, "bigintEqual"); +function bigintNotEqual(value) { + const expected = `expected !== ${value}n`; + return bigintComparator(notEqual, "s.bigint.notEqual", expected, value); +} +__name(bigintNotEqual, "bigintNotEqual"); +function bigintDivisibleBy(divider) { + const expected = `expected % ${divider}n === 0n`; + return { + run(input) { + return input % divider === 0n ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.bigint.divisibleBy", "BigInt is not divisible", input, expected)); + } + }; +} +__name(bigintDivisibleBy, "bigintDivisibleBy"); + +// src/validators/BigIntValidator.ts +var BigIntValidator = class extends BaseValidator { + lessThan(number) { + return this.addConstraint(bigintLessThan(number)); + } + lessThanOrEqual(number) { + return this.addConstraint(bigintLessThanOrEqual(number)); + } + greaterThan(number) { + return this.addConstraint(bigintGreaterThan(number)); + } + greaterThanOrEqual(number) { + return this.addConstraint(bigintGreaterThanOrEqual(number)); + } + equal(number) { + return this.addConstraint(bigintEqual(number)); + } + notEqual(number) { + return this.addConstraint(bigintNotEqual(number)); + } + get positive() { + return this.greaterThanOrEqual(0n); + } + get negative() { + return this.lessThan(0n); + } + divisibleBy(number) { + return this.addConstraint(bigintDivisibleBy(number)); + } + get abs() { + return this.transform((value) => value < 0 ? -value : value); + } + intN(bits) { + return this.transform((value) => BigInt.asIntN(bits, value)); + } + uintN(bits) { + return this.transform((value) => BigInt.asUintN(bits, value)); + } + handle(value) { + return typeof value === "bigint" ? Result.ok(value) : Result.err(new ValidationError("s.bigint", "Expected a bigint primitive", value)); + } +}; +__name(BigIntValidator, "BigIntValidator"); + +// src/constraints/BooleanConstraints.ts +var booleanTrue = { + run(input) { + return input ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.boolean.true", "Invalid boolean value", input, "true")); + } +}; +var booleanFalse = { + run(input) { + return input ? Result.err(new ExpectedConstraintError("s.boolean.false", "Invalid boolean value", input, "false")) : Result.ok(input); + } +}; + +// src/validators/BooleanValidator.ts +var BooleanValidator = class extends BaseValidator { + get true() { + return this.addConstraint(booleanTrue); + } + get false() { + return this.addConstraint(booleanFalse); + } + equal(value) { + return value ? this.true : this.false; + } + notEqual(value) { + return value ? this.false : this.true; + } + handle(value) { + return typeof value === "boolean" ? Result.ok(value) : Result.err(new ValidationError("s.boolean", "Expected a boolean primitive", value)); + } +}; +__name(BooleanValidator, "BooleanValidator"); + +// src/constraints/DateConstraints.ts +function dateComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input.getTime(), number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Date value", input, expected)); + } + }; +} +__name(dateComparator, "dateComparator"); +function dateLessThan(value) { + const expected = `expected < ${value.toISOString()}`; + return dateComparator(lessThan, "s.date.lessThan", expected, value.getTime()); +} +__name(dateLessThan, "dateLessThan"); +function dateLessThanOrEqual(value) { + const expected = `expected <= ${value.toISOString()}`; + return dateComparator(lessThanOrEqual, "s.date.lessThanOrEqual", expected, value.getTime()); +} +__name(dateLessThanOrEqual, "dateLessThanOrEqual"); +function dateGreaterThan(value) { + const expected = `expected > ${value.toISOString()}`; + return dateComparator(greaterThan, "s.date.greaterThan", expected, value.getTime()); +} +__name(dateGreaterThan, "dateGreaterThan"); +function dateGreaterThanOrEqual(value) { + const expected = `expected >= ${value.toISOString()}`; + return dateComparator(greaterThanOrEqual, "s.date.greaterThanOrEqual", expected, value.getTime()); +} +__name(dateGreaterThanOrEqual, "dateGreaterThanOrEqual"); +function dateEqual(value) { + const expected = `expected === ${value.toISOString()}`; + return dateComparator(equal, "s.date.equal", expected, value.getTime()); +} +__name(dateEqual, "dateEqual"); +function dateNotEqual(value) { + const expected = `expected !== ${value.toISOString()}`; + return dateComparator(notEqual, "s.date.notEqual", expected, value.getTime()); +} +__name(dateNotEqual, "dateNotEqual"); +var dateInvalid = { + run(input) { + return Number.isNaN(input.getTime()) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.date.invalid", "Invalid Date value", input, "expected === NaN")); + } +}; +var dateValid = { + run(input) { + return Number.isNaN(input.getTime()) ? Result.err(new ExpectedConstraintError("s.date.valid", "Invalid Date value", input, "expected !== NaN")) : Result.ok(input); + } +}; + +// src/validators/DateValidator.ts +var DateValidator = class extends BaseValidator { + lessThan(date) { + return this.addConstraint(dateLessThan(new Date(date))); + } + lessThanOrEqual(date) { + return this.addConstraint(dateLessThanOrEqual(new Date(date))); + } + greaterThan(date) { + return this.addConstraint(dateGreaterThan(new Date(date))); + } + greaterThanOrEqual(date) { + return this.addConstraint(dateGreaterThanOrEqual(new Date(date))); + } + equal(date) { + const resolved = new Date(date); + return Number.isNaN(resolved.getTime()) ? this.invalid : this.addConstraint(dateEqual(resolved)); + } + notEqual(date) { + const resolved = new Date(date); + return Number.isNaN(resolved.getTime()) ? this.valid : this.addConstraint(dateNotEqual(resolved)); + } + get valid() { + return this.addConstraint(dateValid); + } + get invalid() { + return this.addConstraint(dateInvalid); + } + handle(value) { + return value instanceof Date ? Result.ok(value) : Result.err(new ValidationError("s.date", "Expected a Date", value)); + } +}; +__name(DateValidator, "DateValidator"); +var ExpectedValidationError = class extends ValidationError { + constructor(validator, message, given, expected) { + super(validator, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + validator: this.validator, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const validator = options.stylize(this.validator, "string"); + if (depth < 0) { + return options.stylize(`[ExpectedValidationError: ${validator}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const expected = util.inspect(this.expected, newOptions).replace(/\n/g, padding); + const given = util.inspect(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ExpectedValidationError", "special")} > ${validator}`; + const message = options.stylize(this.message, "regexp"); + const expectedBlock = ` + ${options.stylize("Expected:", "string")}${padding}${expected}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } +}; +__name(ExpectedValidationError, "ExpectedValidationError"); + +// src/validators/InstanceValidator.ts +var InstanceValidator = class extends BaseValidator { + constructor(expected, constraints = []) { + super(constraints); + this.expected = expected; + } + handle(value) { + return value instanceof this.expected ? Result.ok(value) : Result.err(new ExpectedValidationError("s.instance(V)", "Expected", value, this.expected)); + } + clone() { + return Reflect.construct(this.constructor, [this.expected, this.constraints]); + } +}; +__name(InstanceValidator, "InstanceValidator"); + +// src/validators/LiteralValidator.ts +var LiteralValidator = class extends BaseValidator { + constructor(literal, constraints = []) { + super(constraints); + this.expected = literal; + } + handle(value) { + return Object.is(value, this.expected) ? Result.ok(value) : Result.err(new ExpectedValidationError("s.literal(V)", "Expected values to be equals", value, this.expected)); + } + clone() { + return Reflect.construct(this.constructor, [this.expected, this.constraints]); + } +}; +__name(LiteralValidator, "LiteralValidator"); + +// src/validators/NeverValidator.ts +var NeverValidator = class extends BaseValidator { + handle(value) { + return Result.err(new ValidationError("s.never", "Expected a value to not be passed", value)); + } +}; +__name(NeverValidator, "NeverValidator"); + +// src/validators/NullishValidator.ts +var NullishValidator = class extends BaseValidator { + handle(value) { + return value === void 0 || value === null ? Result.ok(value) : Result.err(new ValidationError("s.nullish", "Expected undefined or null", value)); + } +}; +__name(NullishValidator, "NullishValidator"); + +// src/constraints/NumberConstraints.ts +function numberComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input, number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid number value", input, expected)); + } + }; +} +__name(numberComparator, "numberComparator"); +function numberLessThan(value) { + const expected = `expected < ${value}`; + return numberComparator(lessThan, "s.number.lessThan", expected, value); +} +__name(numberLessThan, "numberLessThan"); +function numberLessThanOrEqual(value) { + const expected = `expected <= ${value}`; + return numberComparator(lessThanOrEqual, "s.number.lessThanOrEqual", expected, value); +} +__name(numberLessThanOrEqual, "numberLessThanOrEqual"); +function numberGreaterThan(value) { + const expected = `expected > ${value}`; + return numberComparator(greaterThan, "s.number.greaterThan", expected, value); +} +__name(numberGreaterThan, "numberGreaterThan"); +function numberGreaterThanOrEqual(value) { + const expected = `expected >= ${value}`; + return numberComparator(greaterThanOrEqual, "s.number.greaterThanOrEqual", expected, value); +} +__name(numberGreaterThanOrEqual, "numberGreaterThanOrEqual"); +function numberEqual(value) { + const expected = `expected === ${value}`; + return numberComparator(equal, "s.number.equal", expected, value); +} +__name(numberEqual, "numberEqual"); +function numberNotEqual(value) { + const expected = `expected !== ${value}`; + return numberComparator(notEqual, "s.number.notEqual", expected, value); +} +__name(numberNotEqual, "numberNotEqual"); +var numberInt = { + run(input) { + return Number.isInteger(input) ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.number.int", "Given value is not an integer", input, "Number.isInteger(expected) to be true") + ); + } +}; +var numberSafeInt = { + run(input) { + return Number.isSafeInteger(input) ? Result.ok(input) : Result.err( + new ExpectedConstraintError( + "s.number.safeInt", + "Given value is not a safe integer", + input, + "Number.isSafeInteger(expected) to be true" + ) + ); + } +}; +var numberFinite = { + run(input) { + return Number.isFinite(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.finite", "Given value is not finite", input, "Number.isFinite(expected) to be true")); + } +}; +var numberNaN = { + run(input) { + return Number.isNaN(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.equal(NaN)", "Invalid number value", input, "expected === NaN")); + } +}; +var numberNotNaN = { + run(input) { + return Number.isNaN(input) ? Result.err(new ExpectedConstraintError("s.number.notEqual(NaN)", "Invalid number value", input, "expected !== NaN")) : Result.ok(input); + } +}; +function numberDivisibleBy(divider) { + const expected = `expected % ${divider} === 0`; + return { + run(input) { + return input % divider === 0 ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.divisibleBy", "Number is not divisible", input, expected)); + } + }; +} +__name(numberDivisibleBy, "numberDivisibleBy"); + +// src/validators/NumberValidator.ts +var NumberValidator = class extends BaseValidator { + lessThan(number) { + return this.addConstraint(numberLessThan(number)); + } + lessThanOrEqual(number) { + return this.addConstraint(numberLessThanOrEqual(number)); + } + greaterThan(number) { + return this.addConstraint(numberGreaterThan(number)); + } + greaterThanOrEqual(number) { + return this.addConstraint(numberGreaterThanOrEqual(number)); + } + equal(number) { + return Number.isNaN(number) ? this.addConstraint(numberNaN) : this.addConstraint(numberEqual(number)); + } + notEqual(number) { + return Number.isNaN(number) ? this.addConstraint(numberNotNaN) : this.addConstraint(numberNotEqual(number)); + } + get int() { + return this.addConstraint(numberInt); + } + get safeInt() { + return this.addConstraint(numberSafeInt); + } + get finite() { + return this.addConstraint(numberFinite); + } + get positive() { + return this.greaterThanOrEqual(0); + } + get negative() { + return this.lessThan(0); + } + divisibleBy(divider) { + return this.addConstraint(numberDivisibleBy(divider)); + } + get abs() { + return this.transform(Math.abs); + } + get sign() { + return this.transform(Math.sign); + } + get trunc() { + return this.transform(Math.trunc); + } + get floor() { + return this.transform(Math.floor); + } + get fround() { + return this.transform(Math.fround); + } + get round() { + return this.transform(Math.round); + } + get ceil() { + return this.transform(Math.ceil); + } + handle(value) { + return typeof value === "number" ? Result.ok(value) : Result.err(new ValidationError("s.number", "Expected a number primitive", value)); + } +}; +__name(NumberValidator, "NumberValidator"); + +// src/lib/errors/MissingPropertyError.ts +var MissingPropertyError = class extends BaseError { + constructor(property) { + super("A required property is missing"); + this.property = property; + } + toJSON() { + return { + name: this.name, + property: this.property + }; + } + [customInspectSymbolStackLess](depth, options) { + const property = options.stylize(this.property.toString(), "string"); + if (depth < 0) { + return options.stylize(`[MissingPropertyError: ${property}]`, "special"); + } + const header = `${options.stylize("MissingPropertyError", "special")} > ${property}`; + const message = options.stylize(this.message, "regexp"); + return `${header} + ${message}`; + } +}; +__name(MissingPropertyError, "MissingPropertyError"); +var UnknownPropertyError = class extends BaseError { + constructor(property, value) { + super("Received unexpected property"); + this.property = property; + this.value = value; + } + toJSON() { + return { + name: this.name, + property: this.property, + value: this.value + }; + } + [customInspectSymbolStackLess](depth, options) { + const property = options.stylize(this.property.toString(), "string"); + if (depth < 0) { + return options.stylize(`[UnknownPropertyError: ${property}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = util.inspect(this.value, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("UnknownPropertyError", "special")} > ${property}`; + const message = options.stylize(this.message, "regexp"); + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${givenBlock}`; + } +}; +__name(UnknownPropertyError, "UnknownPropertyError"); + +// src/validators/DefaultValidator.ts +var DefaultValidator = class extends BaseValidator { + constructor(validator, value, constraints = []) { + super(constraints); + this.validator = validator; + this.defaultValue = value; + } + default(value) { + const clone = this.clone(); + clone.defaultValue = value; + return clone; + } + handle(value) { + return typeof value === "undefined" ? Result.ok(getValue(this.defaultValue)) : this.validator["handle"](value); + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.defaultValue, this.constraints]); + } +}; +__name(DefaultValidator, "DefaultValidator"); + +// src/lib/errors/CombinedError.ts +var CombinedError = class extends BaseError { + constructor(errors) { + super("Received one or more errors"); + this.errors = errors; + } + [customInspectSymbolStackLess](depth, options) { + if (depth < 0) { + return options.stylize("[CombinedError]", "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const header = `${options.stylize("CombinedError", "special")} (${options.stylize(this.errors.length.toString(), "number")})`; + const message = options.stylize(this.message, "regexp"); + const errors = this.errors.map((error, i) => { + const index = options.stylize((i + 1).toString(), "number"); + const body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\n/g, padding); + return ` ${index} ${body}`; + }).join("\n\n"); + return `${header} + ${message} + +${errors}`; + } +}; +__name(CombinedError, "CombinedError"); + +// src/validators/UnionValidator.ts +var UnionValidator = class extends BaseValidator { + constructor(validators, constraints = []) { + super(constraints); + this.validators = validators; + } + get optional() { + if (this.validators.length === 0) + return new UnionValidator([new LiteralValidator(void 0)], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) + return this.clone(); + if (validator.expected === null) { + return new UnionValidator( + [new NullishValidator(), ...this.validators.slice(1)], + this.constraints + ); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new LiteralValidator(void 0), ...this.validators]); + } + get required() { + if (this.validators.length === 0) + return this.clone(); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) + return new UnionValidator(this.validators.slice(1), this.constraints); + } else if (validator instanceof NullishValidator) { + return new UnionValidator([new LiteralValidator(null), ...this.validators.slice(1)], this.constraints); + } + return this.clone(); + } + get nullable() { + if (this.validators.length === 0) + return new UnionValidator([new LiteralValidator(null)], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === null) + return this.clone(); + if (validator.expected === void 0) { + return new UnionValidator( + [new NullishValidator(), ...this.validators.slice(1)], + this.constraints + ); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new LiteralValidator(null), ...this.validators]); + } + get nullish() { + if (this.validators.length === 0) + return new UnionValidator([new NullishValidator()], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === null || validator.expected === void 0) { + return new UnionValidator([new NullishValidator(), ...this.validators.slice(1)], this.constraints); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new NullishValidator(), ...this.validators]); + } + or(...predicates) { + return new UnionValidator([...this.validators, ...predicates]); + } + clone() { + return Reflect.construct(this.constructor, [this.validators, this.constraints]); + } + handle(value) { + const errors = []; + for (const validator of this.validators) { + const result = validator.run(value); + if (result.isOk()) + return result; + errors.push(result.error); + } + return Result.err(new CombinedError(errors)); + } +}; +__name(UnionValidator, "UnionValidator"); + +// src/validators/ObjectValidator.ts +var ObjectValidator = class extends BaseValidator { + constructor(shape, strategy = ObjectValidatorStrategy.Ignore, constraints = []) { + super(constraints); + this.keys = []; + this.requiredKeys = /* @__PURE__ */ new Map(); + this.possiblyUndefinedKeys = /* @__PURE__ */ new Map(); + this.possiblyUndefinedKeysWithDefaults = /* @__PURE__ */ new Map(); + this.shape = shape; + this.strategy = strategy; + switch (this.strategy) { + case ObjectValidatorStrategy.Ignore: + this.handleStrategy = (value) => this.handleIgnoreStrategy(value); + break; + case ObjectValidatorStrategy.Strict: { + this.handleStrategy = (value) => this.handleStrictStrategy(value); + break; + } + case ObjectValidatorStrategy.Passthrough: + this.handleStrategy = (value) => this.handlePassthroughStrategy(value); + break; + } + const shapeEntries = Object.entries(shape); + this.keys = shapeEntries.map(([key]) => key); + for (const [key, validator] of shapeEntries) { + if (validator instanceof UnionValidator) { + const [possiblyLiteralOrNullishPredicate] = validator["validators"]; + if (possiblyLiteralOrNullishPredicate instanceof NullishValidator) { + this.possiblyUndefinedKeys.set(key, validator); + } else if (possiblyLiteralOrNullishPredicate instanceof LiteralValidator) { + if (possiblyLiteralOrNullishPredicate.expected === void 0) { + this.possiblyUndefinedKeys.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof DefaultValidator) { + this.possiblyUndefinedKeysWithDefaults.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof NullishValidator) { + this.possiblyUndefinedKeys.set(key, validator); + } else if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) { + this.possiblyUndefinedKeys.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof DefaultValidator) { + this.possiblyUndefinedKeysWithDefaults.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } + } + get strict() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Strict, this.constraints]); + } + get ignore() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Ignore, this.constraints]); + } + get passthrough() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Passthrough, this.constraints]); + } + get partial() { + const shape = Object.fromEntries(this.keys.map((key) => [key, this.shape[key].optional])); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + get required() { + const shape = Object.fromEntries( + this.keys.map((key) => { + let validator = this.shape[key]; + if (validator instanceof UnionValidator) + validator = validator.required; + return [key, validator]; + }) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + extend(schema) { + const shape = { ...this.shape, ...schema instanceof ObjectValidator ? schema.shape : schema }; + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + pick(keys) { + const shape = Object.fromEntries( + keys.filter((key) => this.keys.includes(key)).map((key) => [key, this.shape[key]]) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + omit(keys) { + const shape = Object.fromEntries( + this.keys.filter((key) => !keys.includes(key)).map((key) => [key, this.shape[key]]) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + handle(value) { + const typeOfValue = typeof value; + if (typeOfValue !== "object") { + return Result.err(new ValidationError("s.object(T)", `Expected the value to be an object, but received ${typeOfValue} instead`, value)); + } + if (value === null) { + return Result.err(new ValidationError("s.object(T)", "Expected the value to not be null", value)); + } + if (Array.isArray(value)) { + return Result.err(new ValidationError("s.object(T)", "Expected the value to not be an array", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + for (const predicate of Object.values(this.shape)) { + predicate.setParent(this.parent ?? value); + } + return this.handleStrategy(value); + } + clone() { + return Reflect.construct(this.constructor, [this.shape, this.strategy, this.constraints]); + } + handleIgnoreStrategy(value) { + const errors = []; + const finalObject = {}; + const inputEntries = new Map(Object.entries(value)); + const runPredicate = /* @__PURE__ */ __name((key, predicate) => { + const result = predicate.run(value[key]); + if (result.isOk()) { + finalObject[key] = result.value; + } else { + const error = result.error; + errors.push([key, error]); + } + }, "runPredicate"); + for (const [key, predicate] of this.requiredKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } else { + errors.push([key, new MissingPropertyError(key)]); + } + } + for (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) { + inputEntries.delete(key); + runPredicate(key, validator); + } + if (inputEntries.size === 0) { + return errors.length === 0 ? Result.ok(finalObject) : Result.err(new CombinedPropertyError(errors)); + } + const checkInputEntriesInsteadOfSchemaKeys = this.possiblyUndefinedKeys.size > inputEntries.size; + if (checkInputEntriesInsteadOfSchemaKeys) { + for (const [key] of inputEntries) { + const predicate = this.possiblyUndefinedKeys.get(key); + if (predicate) { + runPredicate(key, predicate); + } + } + } else { + for (const [key, predicate] of this.possiblyUndefinedKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } + } + } + return errors.length === 0 ? Result.ok(finalObject) : Result.err(new CombinedPropertyError(errors)); + } + handleStrictStrategy(value) { + const errors = []; + const finalResult = {}; + const inputEntries = new Map(Object.entries(value)); + const runPredicate = /* @__PURE__ */ __name((key, predicate) => { + const result = predicate.run(value[key]); + if (result.isOk()) { + finalResult[key] = result.value; + } else { + const error = result.error; + errors.push([key, error]); + } + }, "runPredicate"); + for (const [key, predicate] of this.requiredKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } else { + errors.push([key, new MissingPropertyError(key)]); + } + } + for (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) { + inputEntries.delete(key); + runPredicate(key, validator); + } + for (const [key, predicate] of this.possiblyUndefinedKeys) { + if (inputEntries.size === 0) { + break; + } + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } + } + if (inputEntries.size !== 0) { + for (const [key, value2] of inputEntries.entries()) { + errors.push([key, new UnknownPropertyError(key, value2)]); + } + } + return errors.length === 0 ? Result.ok(finalResult) : Result.err(new CombinedPropertyError(errors)); + } + handlePassthroughStrategy(value) { + const result = this.handleIgnoreStrategy(value); + return result.isErr() ? result : Result.ok({ ...value, ...result.value }); + } +}; +__name(ObjectValidator, "ObjectValidator"); +var ObjectValidatorStrategy = /* @__PURE__ */ ((ObjectValidatorStrategy2) => { + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Ignore"] = 0] = "Ignore"; + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Strict"] = 1] = "Strict"; + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Passthrough"] = 2] = "Passthrough"; + return ObjectValidatorStrategy2; +})(ObjectValidatorStrategy || {}); + +// src/validators/PassthroughValidator.ts +var PassthroughValidator = class extends BaseValidator { + handle(value) { + return Result.ok(value); + } +}; +__name(PassthroughValidator, "PassthroughValidator"); + +// src/validators/RecordValidator.ts +var RecordValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(value) { + if (typeof value !== "object") { + return Result.err(new ValidationError("s.record(T)", "Expected an object", value)); + } + if (value === null) { + return Result.err(new ValidationError("s.record(T)", "Expected the value to not be null", value)); + } + if (Array.isArray(value)) { + return Result.err(new ValidationError("s.record(T)", "Expected the value to not be an array", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + const errors = []; + const transformed = {}; + for (const [key, val] of Object.entries(value)) { + const result = this.validator.run(val); + if (result.isOk()) + transformed[key] = result.value; + else + errors.push([key, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } +}; +__name(RecordValidator, "RecordValidator"); + +// src/validators/SetValidator.ts +var SetValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + if (!(values instanceof Set)) { + return Result.err(new ValidationError("s.set(T)", "Expected a set", values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = /* @__PURE__ */ new Set(); + for (const value of values) { + const result = this.validator.run(value); + if (result.isOk()) + transformed.add(result.value); + else + errors.push(result.error); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedError(errors)); + } +}; +__name(SetValidator, "SetValidator"); + +// src/constraints/util/emailValidator.ts +var accountRegex = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")$/; +function validateEmail(email) { + if (!email) + return false; + const atIndex = email.indexOf("@"); + if (atIndex === -1) + return false; + if (atIndex > 64) + return false; + const domainIndex = atIndex + 1; + if (email.includes("@", domainIndex)) + return false; + if (email.length - domainIndex > 255) + return false; + let dotIndex = email.indexOf(".", domainIndex); + if (dotIndex === -1) + return false; + let lastDotIndex = domainIndex; + do { + if (dotIndex - lastDotIndex > 63) + return false; + lastDotIndex = dotIndex + 1; + } while ((dotIndex = email.indexOf(".", lastDotIndex)) !== -1); + if (email.length - lastDotIndex > 63) + return false; + return accountRegex.test(email.slice(0, atIndex)) && validateEmailDomain(email.slice(domainIndex)); +} +__name(validateEmail, "validateEmail"); +function validateEmailDomain(domain) { + try { + return new URL(`http://${domain}`).hostname === domain; + } catch { + return false; + } +} +__name(validateEmailDomain, "validateEmailDomain"); + +// src/constraints/util/net.ts +var v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; +var v4Str = `(${v4Seg}[.]){3}${v4Seg}`; +var IPv4Reg = new RegExp(`^${v4Str}$`); +var v6Seg = "(?:[0-9a-fA-F]{1,4})"; +var IPv6Reg = new RegExp( + `^((?:${v6Seg}:){7}(?:${v6Seg}|:)|(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$` +); +function isIPv4(s2) { + return IPv4Reg.test(s2); +} +__name(isIPv4, "isIPv4"); +function isIPv6(s2) { + return IPv6Reg.test(s2); +} +__name(isIPv6, "isIPv6"); +function isIP(s2) { + if (isIPv4(s2)) + return 4; + if (isIPv6(s2)) + return 6; + return 0; +} +__name(isIP, "isIP"); + +// src/constraints/util/phoneValidator.ts +var phoneNumberRegex = /^((?:\+|0{0,2})\d{1,2}\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/; +function validatePhoneNumber(input) { + return phoneNumberRegex.test(input); +} +__name(validatePhoneNumber, "validatePhoneNumber"); +var MultiplePossibilitiesConstraintError = class extends BaseConstraintError { + constructor(constraint, message, given, expected) { + super(constraint, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + constraint: this.constraint, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const constraint = options.stylize(this.constraint, "string"); + if (depth < 0) { + return options.stylize(`[MultiplePossibilitiesConstraintError: ${constraint}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const verticalLine = options.stylize("|", "undefined"); + const padding = ` + ${verticalLine} `; + const given = util.inspect(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("MultiplePossibilitiesConstraintError", "special")} > ${constraint}`; + const message = options.stylize(this.message, "regexp"); + const expectedPadding = ` + ${verticalLine} - `; + const expectedBlock = ` + ${options.stylize("Expected any of the following:", "string")}${expectedPadding}${this.expected.map((possible) => options.stylize(possible, "boolean")).join(expectedPadding)}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } +}; +__name(MultiplePossibilitiesConstraintError, "MultiplePossibilitiesConstraintError"); + +// src/constraints/util/common/combinedResultFn.ts +function combinedErrorFn(...fns) { + switch (fns.length) { + case 0: + return () => null; + case 1: + return fns[0]; + case 2: { + const [fn0, fn1] = fns; + return (...params) => fn0(...params) || fn1(...params); + } + default: { + return (...params) => { + for (const fn of fns) { + const result = fn(...params); + if (result) + return result; + } + return null; + }; + } + } +} +__name(combinedErrorFn, "combinedErrorFn"); + +// src/constraints/util/urlValidators.ts +function createUrlValidators(options) { + const fns = []; + if (options?.allowedProtocols?.length) + fns.push(allowedProtocolsFn(options.allowedProtocols)); + if (options?.allowedDomains?.length) + fns.push(allowedDomainsFn(options.allowedDomains)); + return combinedErrorFn(...fns); +} +__name(createUrlValidators, "createUrlValidators"); +function allowedProtocolsFn(allowedProtocols) { + return (input, url) => allowedProtocols.includes(url.protocol) ? null : new MultiplePossibilitiesConstraintError("s.string.url", "Invalid URL protocol", input, allowedProtocols); +} +__name(allowedProtocolsFn, "allowedProtocolsFn"); +function allowedDomainsFn(allowedDomains) { + return (input, url) => allowedDomains.includes(url.hostname) ? null : new MultiplePossibilitiesConstraintError("s.string.url", "Invalid URL domain", input, allowedDomains); +} +__name(allowedDomainsFn, "allowedDomainsFn"); + +// src/constraints/StringConstraints.ts +function stringLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid string length", input, expected)); + } + }; +} +__name(stringLengthComparator, "stringLengthComparator"); +function stringLengthLessThan(length) { + const expected = `expected.length < ${length}`; + return stringLengthComparator(lessThan, "s.string.lengthLessThan", expected, length); +} +__name(stringLengthLessThan, "stringLengthLessThan"); +function stringLengthLessThanOrEqual(length) { + const expected = `expected.length <= ${length}`; + return stringLengthComparator(lessThanOrEqual, "s.string.lengthLessThanOrEqual", expected, length); +} +__name(stringLengthLessThanOrEqual, "stringLengthLessThanOrEqual"); +function stringLengthGreaterThan(length) { + const expected = `expected.length > ${length}`; + return stringLengthComparator(greaterThan, "s.string.lengthGreaterThan", expected, length); +} +__name(stringLengthGreaterThan, "stringLengthGreaterThan"); +function stringLengthGreaterThanOrEqual(length) { + const expected = `expected.length >= ${length}`; + return stringLengthComparator(greaterThanOrEqual, "s.string.lengthGreaterThanOrEqual", expected, length); +} +__name(stringLengthGreaterThanOrEqual, "stringLengthGreaterThanOrEqual"); +function stringLengthEqual(length) { + const expected = `expected.length === ${length}`; + return stringLengthComparator(equal, "s.string.lengthEqual", expected, length); +} +__name(stringLengthEqual, "stringLengthEqual"); +function stringLengthNotEqual(length) { + const expected = `expected.length !== ${length}`; + return stringLengthComparator(notEqual, "s.string.lengthNotEqual", expected, length); +} +__name(stringLengthNotEqual, "stringLengthNotEqual"); +function stringEmail() { + return { + run(input) { + return validateEmail(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.string.email", "Invalid email address", input, "expected to be an email address")); + } + }; +} +__name(stringEmail, "stringEmail"); +function stringRegexValidator(type, expected, regex) { + return { + run(input) { + return regex.test(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(type, "Invalid string format", input, expected)); + } + }; +} +__name(stringRegexValidator, "stringRegexValidator"); +function stringUrl(options) { + const validatorFn = createUrlValidators(options); + return { + run(input) { + let url; + try { + url = new URL(input); + } catch { + return Result.err(new ExpectedConstraintError("s.string.url", "Invalid URL", input, "expected to match an URL")); + } + const validatorFnResult = validatorFn(input, url); + if (validatorFnResult === null) + return Result.ok(input); + return Result.err(validatorFnResult); + } + }; +} +__name(stringUrl, "stringUrl"); +function stringIp(version) { + const ipVersion = version ? `v${version}` : ""; + const validatorFn = version === 4 ? isIPv4 : version === 6 ? isIPv6 : isIP; + const name = `s.string.ip${ipVersion}`; + const message = `Invalid IP${ipVersion} address`; + const expected = `expected to be an IP${ipVersion} address`; + return { + run(input) { + return validatorFn(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, message, input, expected)); + } + }; +} +__name(stringIp, "stringIp"); +function stringRegex(regex) { + return stringRegexValidator("s.string.regex", `expected ${regex}.test(expected) to be true`, regex); +} +__name(stringRegex, "stringRegex"); +function stringUuid({ version = 4, nullable = false } = {}) { + version ?? (version = "1-5"); + const regex = new RegExp( + `^(?:[0-9A-F]{8}-[0-9A-F]{4}-[${version}][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}${nullable ? "|00000000-0000-0000-0000-000000000000" : ""})$`, + "i" + ); + const expected = `expected to match UUID${typeof version === "number" ? `v${version}` : ` in range of ${version}`}`; + return stringRegexValidator("s.string.uuid", expected, regex); +} +__name(stringUuid, "stringUuid"); +function stringDate() { + return { + run(input) { + const time = Date.parse(input); + return Number.isNaN(time) ? Result.err( + new ExpectedConstraintError( + "s.string.date", + "Invalid date string", + input, + "expected to be a valid date string (in the ISO 8601 or ECMA-262 format)" + ) + ) : Result.ok(input); + } + }; +} +__name(stringDate, "stringDate"); +function stringPhone() { + return { + run(input) { + return validatePhoneNumber(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.string.phone", "Invalid phone number", input, "expected to be a phone number")); + } + }; +} +__name(stringPhone, "stringPhone"); + +// src/validators/StringValidator.ts +var StringValidator = class extends BaseValidator { + lengthLessThan(length) { + return this.addConstraint(stringLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(stringLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(stringLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(stringLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(stringLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(stringLengthNotEqual(length)); + } + get email() { + return this.addConstraint(stringEmail()); + } + url(options) { + return this.addConstraint(stringUrl(options)); + } + uuid(options) { + return this.addConstraint(stringUuid(options)); + } + regex(regex) { + return this.addConstraint(stringRegex(regex)); + } + get date() { + return this.addConstraint(stringDate()); + } + get ipv4() { + return this.ip(4); + } + get ipv6() { + return this.ip(6); + } + ip(version) { + return this.addConstraint(stringIp(version)); + } + phone() { + return this.addConstraint(stringPhone()); + } + handle(value) { + return typeof value === "string" ? Result.ok(value) : Result.err(new ValidationError("s.string", "Expected a string primitive", value)); + } +}; +__name(StringValidator, "StringValidator"); + +// src/validators/TupleValidator.ts +var TupleValidator = class extends BaseValidator { + constructor(validators, constraints = []) { + super(constraints); + this.validators = []; + this.validators = validators; + } + clone() { + return Reflect.construct(this.constructor, [this.validators, this.constraints]); + } + handle(values) { + if (!Array.isArray(values)) { + return Result.err(new ValidationError("s.tuple(T)", "Expected an array", values)); + } + if (values.length !== this.validators.length) { + return Result.err(new ValidationError("s.tuple(T)", `Expected an array of length ${this.validators.length}`, values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = []; + for (let i = 0; i < values.length; i++) { + const result = this.validators[i].run(values[i]); + if (result.isOk()) + transformed.push(result.value); + else + errors.push([i, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } +}; +__name(TupleValidator, "TupleValidator"); + +// src/validators/MapValidator.ts +var MapValidator = class extends BaseValidator { + constructor(keyValidator, valueValidator, constraints = []) { + super(constraints); + this.keyValidator = keyValidator; + this.valueValidator = valueValidator; + } + clone() { + return Reflect.construct(this.constructor, [this.keyValidator, this.valueValidator, this.constraints]); + } + handle(value) { + if (!(value instanceof Map)) { + return Result.err(new ValidationError("s.map(K, V)", "Expected a map", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + const errors = []; + const transformed = /* @__PURE__ */ new Map(); + for (const [key, val] of value.entries()) { + const keyResult = this.keyValidator.run(key); + const valueResult = this.valueValidator.run(val); + const { length } = errors; + if (keyResult.isErr()) + errors.push([key, keyResult.error]); + if (valueResult.isErr()) + errors.push([key, valueResult.error]); + if (errors.length === length) + transformed.set(keyResult.value, valueResult.value); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } +}; +__name(MapValidator, "MapValidator"); + +// src/validators/LazyValidator.ts +var LazyValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + return this.validator(values).run(values); + } +}; +__name(LazyValidator, "LazyValidator"); + +// src/lib/errors/UnknownEnumValueError.ts +var UnknownEnumValueError = class extends BaseError { + constructor(value, keys, enumMappings) { + super("Expected the value to be one of the following enum values:"); + this.value = value; + this.enumKeys = keys; + this.enumMappings = enumMappings; + } + toJSON() { + return { + name: this.name, + value: this.value, + enumKeys: this.enumKeys, + enumMappings: [...this.enumMappings.entries()] + }; + } + [customInspectSymbolStackLess](depth, options) { + const value = options.stylize(this.value.toString(), "string"); + if (depth < 0) { + return options.stylize(`[UnknownEnumValueError: ${value}]`, "special"); + } + const padding = ` + ${options.stylize("|", "undefined")} `; + const pairs = this.enumKeys.map((key) => { + const enumValue = this.enumMappings.get(key); + return `${options.stylize(key, "string")} or ${options.stylize( + enumValue.toString(), + typeof enumValue === "number" ? "number" : "string" + )}`; + }).join(padding); + const header = `${options.stylize("UnknownEnumValueError", "special")} > ${value}`; + const message = options.stylize(this.message, "regexp"); + const pairsBlock = `${padding}${pairs}`; + return `${header} + ${message} +${pairsBlock}`; + } +}; +__name(UnknownEnumValueError, "UnknownEnumValueError"); + +// src/validators/NativeEnumValidator.ts +var NativeEnumValidator = class extends BaseValidator { + constructor(enumShape) { + super(); + this.hasNumericElements = false; + this.enumMapping = /* @__PURE__ */ new Map(); + this.enumShape = enumShape; + this.enumKeys = Object.keys(enumShape).filter((key) => { + return typeof enumShape[enumShape[key]] !== "number"; + }); + for (const key of this.enumKeys) { + const enumValue = enumShape[key]; + this.enumMapping.set(key, enumValue); + this.enumMapping.set(enumValue, enumValue); + if (typeof enumValue === "number") { + this.hasNumericElements = true; + this.enumMapping.set(`${enumValue}`, enumValue); + } + } + } + handle(value) { + const typeOfValue = typeof value; + if (typeOfValue === "number") { + if (!this.hasNumericElements) { + return Result.err(new ValidationError("s.nativeEnum(T)", "Expected the value to be a string", value)); + } + } else if (typeOfValue !== "string") { + return Result.err(new ValidationError("s.nativeEnum(T)", "Expected the value to be a string or number", value)); + } + const casted = value; + const possibleEnumValue = this.enumMapping.get(casted); + return typeof possibleEnumValue === "undefined" ? Result.err(new UnknownEnumValueError(casted, this.enumKeys, this.enumMapping)) : Result.ok(possibleEnumValue); + } + clone() { + return Reflect.construct(this.constructor, [this.enumShape]); + } +}; +__name(NativeEnumValidator, "NativeEnumValidator"); + +// src/constraints/TypedArrayLengthConstraints.ts +function typedArrayByteLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.byteLength, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Typed Array byte length", input, expected)); + } + }; +} +__name(typedArrayByteLengthComparator, "typedArrayByteLengthComparator"); +function typedArrayByteLengthLessThan(value) { + const expected = `expected.byteLength < ${value}`; + return typedArrayByteLengthComparator(lessThan, "s.typedArray(T).byteLengthLessThan", expected, value); +} +__name(typedArrayByteLengthLessThan, "typedArrayByteLengthLessThan"); +function typedArrayByteLengthLessThanOrEqual(value) { + const expected = `expected.byteLength <= ${value}`; + return typedArrayByteLengthComparator(lessThanOrEqual, "s.typedArray(T).byteLengthLessThanOrEqual", expected, value); +} +__name(typedArrayByteLengthLessThanOrEqual, "typedArrayByteLengthLessThanOrEqual"); +function typedArrayByteLengthGreaterThan(value) { + const expected = `expected.byteLength > ${value}`; + return typedArrayByteLengthComparator(greaterThan, "s.typedArray(T).byteLengthGreaterThan", expected, value); +} +__name(typedArrayByteLengthGreaterThan, "typedArrayByteLengthGreaterThan"); +function typedArrayByteLengthGreaterThanOrEqual(value) { + const expected = `expected.byteLength >= ${value}`; + return typedArrayByteLengthComparator(greaterThanOrEqual, "s.typedArray(T).byteLengthGreaterThanOrEqual", expected, value); +} +__name(typedArrayByteLengthGreaterThanOrEqual, "typedArrayByteLengthGreaterThanOrEqual"); +function typedArrayByteLengthEqual(value) { + const expected = `expected.byteLength === ${value}`; + return typedArrayByteLengthComparator(equal, "s.typedArray(T).byteLengthEqual", expected, value); +} +__name(typedArrayByteLengthEqual, "typedArrayByteLengthEqual"); +function typedArrayByteLengthNotEqual(value) { + const expected = `expected.byteLength !== ${value}`; + return typedArrayByteLengthComparator(notEqual, "s.typedArray(T).byteLengthNotEqual", expected, value); +} +__name(typedArrayByteLengthNotEqual, "typedArrayByteLengthNotEqual"); +function typedArrayByteLengthRange(start, endBefore) { + const expected = `expected.byteLength >= ${start} && expected.byteLength < ${endBefore}`; + return { + run(input) { + return input.byteLength >= start && input.byteLength < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).byteLengthRange", "Invalid Typed Array byte length", input, expected)); + } + }; +} +__name(typedArrayByteLengthRange, "typedArrayByteLengthRange"); +function typedArrayByteLengthRangeInclusive(start, end) { + const expected = `expected.byteLength >= ${start} && expected.byteLength <= ${end}`; + return { + run(input) { + return input.byteLength >= start && input.byteLength <= end ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.typedArray(T).byteLengthRangeInclusive", "Invalid Typed Array byte length", input, expected) + ); + } + }; +} +__name(typedArrayByteLengthRangeInclusive, "typedArrayByteLengthRangeInclusive"); +function typedArrayByteLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.byteLength > ${startAfter} && expected.byteLength < ${endBefore}`; + return { + run(input) { + return input.byteLength > startAfter && input.byteLength < endBefore ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.typedArray(T).byteLengthRangeExclusive", "Invalid Typed Array byte length", input, expected) + ); + } + }; +} +__name(typedArrayByteLengthRangeExclusive, "typedArrayByteLengthRangeExclusive"); +function typedArrayLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Typed Array length", input, expected)); + } + }; +} +__name(typedArrayLengthComparator, "typedArrayLengthComparator"); +function typedArrayLengthLessThan(value) { + const expected = `expected.length < ${value}`; + return typedArrayLengthComparator(lessThan, "s.typedArray(T).lengthLessThan", expected, value); +} +__name(typedArrayLengthLessThan, "typedArrayLengthLessThan"); +function typedArrayLengthLessThanOrEqual(value) { + const expected = `expected.length <= ${value}`; + return typedArrayLengthComparator(lessThanOrEqual, "s.typedArray(T).lengthLessThanOrEqual", expected, value); +} +__name(typedArrayLengthLessThanOrEqual, "typedArrayLengthLessThanOrEqual"); +function typedArrayLengthGreaterThan(value) { + const expected = `expected.length > ${value}`; + return typedArrayLengthComparator(greaterThan, "s.typedArray(T).lengthGreaterThan", expected, value); +} +__name(typedArrayLengthGreaterThan, "typedArrayLengthGreaterThan"); +function typedArrayLengthGreaterThanOrEqual(value) { + const expected = `expected.length >= ${value}`; + return typedArrayLengthComparator(greaterThanOrEqual, "s.typedArray(T).lengthGreaterThanOrEqual", expected, value); +} +__name(typedArrayLengthGreaterThanOrEqual, "typedArrayLengthGreaterThanOrEqual"); +function typedArrayLengthEqual(value) { + const expected = `expected.length === ${value}`; + return typedArrayLengthComparator(equal, "s.typedArray(T).lengthEqual", expected, value); +} +__name(typedArrayLengthEqual, "typedArrayLengthEqual"); +function typedArrayLengthNotEqual(value) { + const expected = `expected.length !== ${value}`; + return typedArrayLengthComparator(notEqual, "s.typedArray(T).lengthNotEqual", expected, value); +} +__name(typedArrayLengthNotEqual, "typedArrayLengthNotEqual"); +function typedArrayLengthRange(start, endBefore) { + const expected = `expected.length >= ${start} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length >= start && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRange", "Invalid Typed Array length", input, expected)); + } + }; +} +__name(typedArrayLengthRange, "typedArrayLengthRange"); +function typedArrayLengthRangeInclusive(start, end) { + const expected = `expected.length >= ${start} && expected.length <= ${end}`; + return { + run(input) { + return input.length >= start && input.length <= end ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRangeInclusive", "Invalid Typed Array length", input, expected)); + } + }; +} +__name(typedArrayLengthRangeInclusive, "typedArrayLengthRangeInclusive"); +function typedArrayLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length > startAfter && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRangeExclusive", "Invalid Typed Array length", input, expected)); + } + }; +} +__name(typedArrayLengthRangeExclusive, "typedArrayLengthRangeExclusive"); + +// src/constraints/util/common/vowels.ts +var vowels = ["a", "e", "i", "o", "u"]; +var aOrAn = /* @__PURE__ */ __name((word) => { + return `${vowels.includes(word[0].toLowerCase()) ? "an" : "a"} ${word}`; +}, "aOrAn"); + +// src/constraints/util/typedArray.ts +var TypedArrays = { + Int8Array: (x) => x instanceof Int8Array, + Uint8Array: (x) => x instanceof Uint8Array, + Uint8ClampedArray: (x) => x instanceof Uint8ClampedArray, + Int16Array: (x) => x instanceof Int16Array, + Uint16Array: (x) => x instanceof Uint16Array, + Int32Array: (x) => x instanceof Int32Array, + Uint32Array: (x) => x instanceof Uint32Array, + Float32Array: (x) => x instanceof Float32Array, + Float64Array: (x) => x instanceof Float64Array, + BigInt64Array: (x) => x instanceof BigInt64Array, + BigUint64Array: (x) => x instanceof BigUint64Array, + TypedArray: (x) => ArrayBuffer.isView(x) && !(x instanceof DataView) +}; + +// src/validators/TypedArrayValidator.ts +var TypedArrayValidator = class extends BaseValidator { + constructor(type, constraints = []) { + super(constraints); + this.type = type; + } + byteLengthLessThan(length) { + return this.addConstraint(typedArrayByteLengthLessThan(length)); + } + byteLengthLessThanOrEqual(length) { + return this.addConstraint(typedArrayByteLengthLessThanOrEqual(length)); + } + byteLengthGreaterThan(length) { + return this.addConstraint(typedArrayByteLengthGreaterThan(length)); + } + byteLengthGreaterThanOrEqual(length) { + return this.addConstraint(typedArrayByteLengthGreaterThanOrEqual(length)); + } + byteLengthEqual(length) { + return this.addConstraint(typedArrayByteLengthEqual(length)); + } + byteLengthNotEqual(length) { + return this.addConstraint(typedArrayByteLengthNotEqual(length)); + } + byteLengthRange(start, endBefore) { + return this.addConstraint(typedArrayByteLengthRange(start, endBefore)); + } + byteLengthRangeInclusive(startAt, endAt) { + return this.addConstraint(typedArrayByteLengthRangeInclusive(startAt, endAt)); + } + byteLengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(typedArrayByteLengthRangeExclusive(startAfter, endBefore)); + } + lengthLessThan(length) { + return this.addConstraint(typedArrayLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(typedArrayLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(typedArrayLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(typedArrayLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(typedArrayLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(typedArrayLengthNotEqual(length)); + } + lengthRange(start, endBefore) { + return this.addConstraint(typedArrayLengthRange(start, endBefore)); + } + lengthRangeInclusive(startAt, endAt) { + return this.addConstraint(typedArrayLengthRangeInclusive(startAt, endAt)); + } + lengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(typedArrayLengthRangeExclusive(startAfter, endBefore)); + } + clone() { + return Reflect.construct(this.constructor, [this.type, this.constraints]); + } + handle(value) { + return TypedArrays[this.type](value) ? Result.ok(value) : Result.err(new ValidationError("s.typedArray", `Expected ${aOrAn(this.type)}`, value)); + } +}; +__name(TypedArrayValidator, "TypedArrayValidator"); + +// src/lib/Shapes.ts +var Shapes = class { + get string() { + return new StringValidator(); + } + get number() { + return new NumberValidator(); + } + get bigint() { + return new BigIntValidator(); + } + get boolean() { + return new BooleanValidator(); + } + get date() { + return new DateValidator(); + } + object(shape) { + return new ObjectValidator(shape); + } + get undefined() { + return this.literal(void 0); + } + get null() { + return this.literal(null); + } + get nullish() { + return new NullishValidator(); + } + get any() { + return new PassthroughValidator(); + } + get unknown() { + return new PassthroughValidator(); + } + get never() { + return new NeverValidator(); + } + enum(...values) { + return this.union(...values.map((value) => this.literal(value))); + } + nativeEnum(enumShape) { + return new NativeEnumValidator(enumShape); + } + literal(value) { + if (value instanceof Date) + return this.date.equal(value); + return new LiteralValidator(value); + } + instance(expected) { + return new InstanceValidator(expected); + } + union(...validators) { + return new UnionValidator(validators); + } + array(validator) { + return new ArrayValidator(validator); + } + typedArray(type = "TypedArray") { + return new TypedArrayValidator(type); + } + get int8Array() { + return this.typedArray("Int8Array"); + } + get uint8Array() { + return this.typedArray("Uint8Array"); + } + get uint8ClampedArray() { + return this.typedArray("Uint8ClampedArray"); + } + get int16Array() { + return this.typedArray("Int16Array"); + } + get uint16Array() { + return this.typedArray("Uint16Array"); + } + get int32Array() { + return this.typedArray("Int32Array"); + } + get uint32Array() { + return this.typedArray("Uint32Array"); + } + get float32Array() { + return this.typedArray("Float32Array"); + } + get float64Array() { + return this.typedArray("Float64Array"); + } + get bigInt64Array() { + return this.typedArray("BigInt64Array"); + } + get bigUint64Array() { + return this.typedArray("BigUint64Array"); + } + tuple(validators) { + return new TupleValidator(validators); + } + set(validator) { + return new SetValidator(validator); + } + record(validator) { + return new RecordValidator(validator); + } + map(keyValidator, valueValidator) { + return new MapValidator(keyValidator, valueValidator); + } + lazy(validator) { + return new LazyValidator(validator); + } +}; +__name(Shapes, "Shapes"); + +// src/index.ts +var s = new Shapes(); + +exports.BaseError = BaseError; +exports.CombinedError = CombinedError; +exports.CombinedPropertyError = CombinedPropertyError; +exports.ExpectedConstraintError = ExpectedConstraintError; +exports.ExpectedValidationError = ExpectedValidationError; +exports.MissingPropertyError = MissingPropertyError; +exports.MultiplePossibilitiesConstraintError = MultiplePossibilitiesConstraintError; +exports.Result = Result; +exports.UnknownEnumValueError = UnknownEnumValueError; +exports.UnknownPropertyError = UnknownPropertyError; +exports.ValidationError = ValidationError; +exports.customInspectSymbol = customInspectSymbol; +exports.customInspectSymbolStackLess = customInspectSymbolStackLess; +exports.getGlobalValidationEnabled = getGlobalValidationEnabled; +exports.s = s; +exports.setGlobalValidationEnabled = setGlobalValidationEnabled; +//# sourceMappingURL=out.js.map +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/dist/index.js.map b/node_modules/@sapphire/shapeshift/dist/index.js.map new file mode 100644 index 0000000..871f0d6 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/lib/configs.ts","../src/lib/Result.ts","../src/validators/util/getValue.ts","../src/constraints/ObjectConstrains.ts","../src/lib/errors/ExpectedConstraintError.ts","../src/lib/errors/BaseError.ts","../src/lib/errors/BaseConstraintError.ts","../src/validators/BaseValidator.ts","../src/constraints/util/isUnique.ts","../src/constraints/util/operators.ts","../src/constraints/ArrayConstraints.ts","../src/lib/errors/CombinedPropertyError.ts","../src/lib/errors/ValidationError.ts","../src/validators/ArrayValidator.ts","../src/constraints/BigIntConstraints.ts","../src/validators/BigIntValidator.ts","../src/constraints/BooleanConstraints.ts","../src/validators/BooleanValidator.ts","../src/constraints/DateConstraints.ts","../src/validators/DateValidator.ts","../src/lib/errors/ExpectedValidationError.ts","../src/validators/InstanceValidator.ts","../src/validators/LiteralValidator.ts","../src/validators/NeverValidator.ts","../src/validators/NullishValidator.ts","../src/constraints/NumberConstraints.ts","../src/validators/NumberValidator.ts","../src/lib/errors/MissingPropertyError.ts","../src/lib/errors/UnknownPropertyError.ts","../src/validators/DefaultValidator.ts","../src/lib/errors/CombinedError.ts","../src/validators/UnionValidator.ts","../src/validators/ObjectValidator.ts","../src/validators/PassthroughValidator.ts","../src/validators/RecordValidator.ts","../src/validators/SetValidator.ts","../src/constraints/util/emailValidator.ts","../src/constraints/util/net.ts","../src/constraints/util/phoneValidator.ts","../src/lib/errors/MultiplePossibilitiesConstraintError.ts","../src/constraints/util/common/combinedResultFn.ts","../src/constraints/util/urlValidators.ts","../src/constraints/StringConstraints.ts","../src/validators/StringValidator.ts","../src/validators/TupleValidator.ts","../src/validators/MapValidator.ts","../src/validators/LazyValidator.ts","../src/lib/errors/UnknownEnumValueError.ts","../src/validators/NativeEnumValidator.ts","../src/constraints/TypedArrayLengthConstraints.ts","../src/constraints/util/common/vowels.ts","../src/constraints/util/typedArray.ts","../src/validators/TypedArrayValidator.ts","../src/lib/Shapes.ts","../src/index.ts"],"names":["uniqueArray","inspect","value","ObjectValidatorStrategy","s"],"mappings":";;;;AAAA,IAAI,oBAAoB;AAMjB,SAAS,2BAA2B,SAAkB;AAC5D,sBAAoB;AACrB;AAFgB;AAOT,SAAS,6BAA6B;AAC5C,SAAO;AACR;AAFgB;;;ACbT,IAAM,SAAN,MAAyC;AAAA,EAKvC,YAAY,SAAkB,OAAW,OAAW;AAC3D,SAAK,UAAU;AACf,QAAI,SAAS;AACZ,WAAK,QAAQ;AAAA,IACd,OAAO;AACN,WAAK,QAAQ;AAAA,IACd;AAAA,EACD;AAAA,EAEO,OAA4C;AAClD,WAAO,KAAK;AAAA,EACb;AAAA,EAEO,QAA8C;AACpD,WAAO,CAAC,KAAK;AAAA,EACd;AAAA,EAEO,SAAY;AAClB,QAAI,KAAK,KAAK;AAAG,aAAO,KAAK;AAC7B,UAAM,KAAK;AAAA,EACZ;AAAA,EAEA,OAAc,GAA+B,OAAwB;AACpE,WAAO,IAAI,OAAa,MAAM,KAAK;AAAA,EACpC;AAAA,EAEA,OAAc,IAAgC,OAAwB;AACrE,WAAO,IAAI,OAAa,OAAO,QAAW,KAAK;AAAA,EAChD;AACD;AAlCa;;;ACGN,SAAS,SAAkD,WAAiB;AAClF,SAAO,OAAO,cAAc,aAAa,UAAU,IAAI;AACxD;AAFgB;;;ACHhB,OAAO,SAAS;;;ACAhB,SAAS,eAA4C;;;ACE9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AO,KAAK,WAA8B,mBAAmB;AAAA,EAC9D;AAAA,EAEA,IAAW,aAAa;AACvB,WAAO,KAAK,WAAuB,YAAY;AAAA,EAChD;AAAA,EAEA,IAAW,cAAc;AACxB,WAAO,KAAK,WAAwB,aAAa;AAAA,EAClD;AAAA,EAEA,IAAW,aAAa;AACvB,WAAO,KAAK,WAAuB,YAAY;AAAA,EAChD;AAAA,EAEA,IAAW,cAAc;AACxB,WAAO,KAAK,WAAwB,aAAa;AAAA,EAClD;AAAA,EAEA,IAAW,eAAe;AACzB,WAAO,KAAK,WAAyB,cAAc;AAAA,EACpD;AAAA,EAEA,IAAW,eAAe;AACzB,WAAO,KAAK,WAAyB,cAAc;AAAA,EACpD;AAAA,EAEA,IAAW,gBAAgB;AAC1B,WAAO,KAAK,WAA0B,eAAe;AAAA,EACtD;AAAA,EAEA,IAAW,iBAAiB;AAC3B,WAAO,KAAK,WAA2B,gBAAgB;AAAA,EACxD;AAAA,EAEO,MAA2C,YAAoD;AACrG,WAAO,IAAI,eAAe,UAAU;AAAA,EACrC;AAAA,EAEO,IAAO,WAA6B;AAC1C,WAAO,IAAI,aAAa,SAAS;AAAA,EAClC;AAAA,EAEO,OAAU,WAA6B;AAC7C,WAAO,IAAI,gBAAgB,SAAS;AAAA,EACrC;AAAA,EAEO,IAAU,cAAgC,gBAAkC;AAClF,WAAO,IAAI,aAAa,cAAc,cAAc;AAAA,EACrD;AAAA,EAEO,KAAuC,WAAkC;AAC/E,WAAO,IAAI,cAAc,SAAS;AAAA,EACnC;AACD;AA/Ia;;;ACzBN,IAAM,IAAI,IAAI,OAAO","sourcesContent":["let validationEnabled = true;\n\n/**\n * Sets whether validators should run on the input, or if the input should be passed through.\n * @param enabled Whether validation should be done on inputs\n */\nexport function setGlobalValidationEnabled(enabled: boolean) {\n\tvalidationEnabled = enabled;\n}\n\n/**\n * @returns Whether validation is enabled\n */\nexport function getGlobalValidationEnabled() {\n\treturn validationEnabled;\n}\n","export class Result {\n\tpublic readonly success: boolean;\n\tpublic readonly value?: T;\n\tpublic readonly error?: E;\n\n\tprivate constructor(success: boolean, value?: T, error?: E) {\n\t\tthis.success = success;\n\t\tif (success) {\n\t\t\tthis.value = value;\n\t\t} else {\n\t\t\tthis.error = error;\n\t\t}\n\t}\n\n\tpublic isOk(): this is { success: true; value: T } {\n\t\treturn this.success;\n\t}\n\n\tpublic isErr(): this is { success: false; error: E } {\n\t\treturn !this.success;\n\t}\n\n\tpublic unwrap(): T {\n\t\tif (this.isOk()) return this.value;\n\t\tthrow this.error as Error;\n\t}\n\n\tpublic static ok(value: T): Result {\n\t\treturn new Result(true, value);\n\t}\n\n\tpublic static err(error: E): Result {\n\t\treturn new Result(false, undefined, error);\n\t}\n}\n","// https://github.com/microsoft/TypeScript/issues/37663\ntype Fn = (...args: unknown[]) => unknown;\n\nexport function getValue : T>(valueOrFn: T): U {\n\treturn typeof valueOrFn === 'function' ? valueOrFn() : valueOrFn;\n}\n","import get from 'lodash/get.js';\nimport { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { BaseValidator } from '../type-exports';\nimport type { IConstraint } from './type-exports';\n\nexport type ObjectConstraintName = `s.object(T.when)`;\n\nexport type WhenKey = PropertyKey | PropertyKey[];\n\nexport interface WhenOptions, Key extends WhenKey> {\n\tis?: boolean | ((value: Key extends Array ? any[] : any) => boolean);\n\tthen: (predicate: T) => T;\n\totherwise?: (predicate: T) => T;\n}\n\nexport function whenConstraint, I, Key extends WhenKey>(\n\tkey: Key,\n\toptions: WhenOptions,\n\tvalidator: T\n): IConstraint {\n\treturn {\n\t\trun(input: I, parent?: any) {\n\t\t\tif (!parent) {\n\t\t\t\treturn Result.err(new ExpectedConstraintError('s.object(T.when)', 'Validator has no parent', parent, 'Validator to have a parent'));\n\t\t\t}\n\n\t\t\tconst isKeyArray = Array.isArray(key);\n\n\t\t\tconst value = isKeyArray ? key.map((k) => get(parent, k)) : get(parent, key);\n\n\t\t\tconst predicate = resolveBooleanIs(options, value, isKeyArray) ? options.then : options.otherwise;\n\n\t\t\tif (predicate) {\n\t\t\t\treturn predicate(validator).run(input) as Result>;\n\t\t\t}\n\n\t\t\treturn Result.ok(input);\n\t\t}\n\t};\n}\n\nfunction resolveBooleanIs, Key extends WhenKey>(options: WhenOptions, value: any, isKeyArray: boolean) {\n\tif (options.is === undefined) {\n\t\treturn isKeyArray ? !value.some((val: any) => !val) : Boolean(value);\n\t}\n\n\tif (typeof options.is === 'function') {\n\t\treturn options.is(value);\n\t}\n\n\treturn value === options.is;\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { BaseConstraintError, type ConstraintErrorNames } from './BaseConstraintError';\n\nexport class ExpectedConstraintError extends BaseConstraintError {\n\tpublic readonly expected: string;\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: string) {\n\t\tsuper(constraint, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tconstraint: this.constraint,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst constraint = options.stylize(this.constraint, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ExpectedConstraintError: ${constraint}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ExpectedConstraintError', 'special')} > ${constraint}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected: ', 'string')}${options.stylize(this.expected, 'boolean')}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\n\nexport const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');\nexport const customInspectSymbolStackLess = Symbol.for('nodejs.util.inspect.custom.stack-less');\n\nexport abstract class BaseError extends Error {\n\tprotected [customInspectSymbol](depth: number, options: InspectOptionsStylized) {\n\t\treturn `${this[customInspectSymbolStackLess](depth, options)}\\n${this.stack!.slice(this.stack!.indexOf('\\n'))}`;\n\t}\n\n\tprotected abstract [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;\n}\n","import type {\n\tArrayConstraintName,\n\tBigIntConstraintName,\n\tBooleanConstraintName,\n\tDateConstraintName,\n\tNumberConstraintName,\n\tObjectConstraintName,\n\tStringConstraintName,\n\tTypedArrayConstraintName\n} from '../../constraints/type-exports';\nimport { BaseError } from './BaseError';\n\nexport type ConstraintErrorNames =\n\t| TypedArrayConstraintName\n\t| ArrayConstraintName\n\t| BigIntConstraintName\n\t| BooleanConstraintName\n\t| DateConstraintName\n\t| NumberConstraintName\n\t| ObjectConstraintName\n\t| StringConstraintName;\n\nexport abstract class BaseConstraintError extends BaseError {\n\tpublic readonly constraint: ConstraintErrorNames;\n\tpublic readonly given: T;\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T) {\n\t\tsuper(message);\n\t\tthis.constraint = constraint;\n\t\tthis.given = given;\n\t}\n}\n","import { getGlobalValidationEnabled } from '../lib/configs';\nimport { Result } from '../lib/Result';\nimport { ArrayValidator, DefaultValidator, LiteralValidator, NullishValidator, SetValidator, UnionValidator } from './imports';\nimport { getValue } from './util/getValue';\nimport { whenConstraint, type WhenKey, type WhenOptions } from '../constraints/ObjectConstrains';\nimport type { CombinedError } from '../lib/errors/CombinedError';\nimport type { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport type { UnknownEnumValueError } from '../lib/errors/UnknownEnumValueError';\nimport type { ValidationError } from '../lib/errors/ValidationError';\nimport type { BaseConstraintError, InferResultType } from '../type-exports';\nimport type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\n\nexport abstract class BaseValidator {\n\tprotected parent?: object;\n\tprotected constraints: readonly IConstraint[] = [];\n\tprotected isValidationEnabled: boolean | (() => boolean) | null = null;\n\n\tpublic constructor(constraints: readonly IConstraint[] = []) {\n\t\tthis.constraints = constraints;\n\t}\n\n\tpublic setParent(parent: object): this {\n\t\tthis.parent = parent;\n\t\treturn this;\n\t}\n\n\tpublic get optional(): UnionValidator {\n\t\treturn new UnionValidator([new LiteralValidator(undefined), this.clone()]);\n\t}\n\n\tpublic get nullable(): UnionValidator {\n\t\treturn new UnionValidator([new LiteralValidator(null), this.clone()]);\n\t}\n\n\tpublic get nullish(): UnionValidator {\n\t\treturn new UnionValidator([new NullishValidator(), this.clone()]);\n\t}\n\n\tpublic get array(): ArrayValidator {\n\t\treturn new ArrayValidator(this.clone());\n\t}\n\n\tpublic get set(): SetValidator {\n\t\treturn new SetValidator(this.clone());\n\t}\n\n\tpublic or(...predicates: readonly BaseValidator[]): UnionValidator {\n\t\treturn new UnionValidator([this.clone(), ...predicates]);\n\t}\n\n\tpublic transform(cb: (value: T) => T): this;\n\tpublic transform(cb: (value: T) => O): BaseValidator;\n\tpublic transform(cb: (value: T) => O): BaseValidator {\n\t\treturn this.addConstraint({ run: (input) => Result.ok(cb(input) as unknown as T) }) as unknown as BaseValidator;\n\t}\n\n\tpublic reshape(cb: (input: T) => Result): this;\n\tpublic reshape, O = InferResultType>(cb: (input: T) => R): BaseValidator;\n\tpublic reshape, O = InferResultType>(cb: (input: T) => R): BaseValidator {\n\t\treturn this.addConstraint({ run: cb as unknown as (input: T) => Result> }) as unknown as BaseValidator;\n\t}\n\n\tpublic default(value: Exclude | (() => Exclude)): DefaultValidator> {\n\t\treturn new DefaultValidator(this.clone() as unknown as BaseValidator>, value);\n\t}\n\n\tpublic when = this>(key: Key, options: WhenOptions): this {\n\t\treturn this.addConstraint(whenConstraint(key, options, this as unknown as This));\n\t}\n\n\tpublic run(value: unknown): Result {\n\t\tlet result = this.handle(value) as Result;\n\t\tif (result.isErr()) return result;\n\n\t\tfor (const constraint of this.constraints) {\n\t\t\tresult = constraint.run(result.value as T, this.parent);\n\t\t\tif (result.isErr()) break;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic parse(value: unknown): R {\n\t\t// If validation is disabled (at the validator or global level), we only run the `handle` method, which will do some basic checks\n\t\t// (like that the input is a string for a string validator)\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn this.handle(value).unwrap() as R;\n\t\t}\n\n\t\treturn this.constraints.reduce((v, constraint) => constraint.run(v).unwrap(), this.handle(value).unwrap()) as R;\n\t}\n\n\tpublic is(value: unknown): value is R {\n\t\treturn this.run(value).isOk();\n\t}\n\n\t/**\n\t * Sets if the validator should also run constraints or just do basic checks.\n\t * @param isValidationEnabled Whether this validator should be enabled or disabled. You can pass boolean or a function returning boolean which will be called just before parsing.\n\t * Set to `null` to go off of the global configuration.\n\t */\n\tpublic setValidationEnabled(isValidationEnabled: boolean | (() => boolean) | null): this {\n\t\tconst clone = this.clone();\n\t\tclone.isValidationEnabled = isValidationEnabled;\n\t\treturn clone;\n\t}\n\n\tpublic getValidationEnabled() {\n\t\treturn getValue(this.isValidationEnabled);\n\t}\n\n\tprotected get shouldRunConstraints(): boolean {\n\t\treturn getValue(this.isValidationEnabled) ?? getGlobalValidationEnabled();\n\t}\n\n\tprotected clone(): this {\n\t\tconst clone: this = Reflect.construct(this.constructor, [this.constraints]);\n\t\tclone.isValidationEnabled = this.isValidationEnabled;\n\t\treturn clone;\n\t}\n\n\tprotected abstract handle(value: unknown): Result;\n\n\tprotected addConstraint(constraint: IConstraint): this {\n\t\tconst clone = this.clone();\n\t\tclone.constraints = clone.constraints.concat(constraint);\n\t\treturn clone;\n\t}\n}\n\nexport type ValidatorError = ValidationError | CombinedError | CombinedPropertyError | UnknownEnumValueError;\n","import fastDeepEqual from 'fast-deep-equal/es6/index.js';\nimport uniqWith from 'lodash/uniqWith.js';\n\nexport function isUnique(input: unknown[]) {\n\tif (input.length < 2) return true;\n\tconst uniqueArray = uniqWith(input, fastDeepEqual);\n\treturn uniqueArray.length === input.length;\n}\n","export function lessThan(a: number, b: number): boolean;\nexport function lessThan(a: bigint, b: bigint): boolean;\nexport function lessThan(a: number | bigint, b: number | bigint): boolean {\n\treturn a < b;\n}\n\nexport function lessThanOrEqual(a: number, b: number): boolean;\nexport function lessThanOrEqual(a: bigint, b: bigint): boolean;\nexport function lessThanOrEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a <= b;\n}\n\nexport function greaterThan(a: number, b: number): boolean;\nexport function greaterThan(a: bigint, b: bigint): boolean;\nexport function greaterThan(a: number | bigint, b: number | bigint): boolean {\n\treturn a > b;\n}\n\nexport function greaterThanOrEqual(a: number, b: number): boolean;\nexport function greaterThanOrEqual(a: bigint, b: bigint): boolean;\nexport function greaterThanOrEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a >= b;\n}\n\nexport function equal(a: number, b: number): boolean;\nexport function equal(a: bigint, b: bigint): boolean;\nexport function equal(a: number | bigint, b: number | bigint): boolean {\n\treturn a === b;\n}\n\nexport function notEqual(a: number, b: number): boolean;\nexport function notEqual(a: bigint, b: bigint): boolean;\nexport function notEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a !== b;\n}\n\nexport interface Comparator {\n\t(a: number, b: number): boolean;\n\t(a: bigint, b: bigint): boolean;\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { isUnique } from './util/isUnique';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type ArrayConstraintName = `s.array(T).${\n\t| 'unique'\n\t| `length${\n\t\t\t| 'LessThan'\n\t\t\t| 'LessThanOrEqual'\n\t\t\t| 'GreaterThan'\n\t\t\t| 'GreaterThanOrEqual'\n\t\t\t| 'Equal'\n\t\t\t| 'NotEqual'\n\t\t\t| 'Range'\n\t\t\t| 'RangeInclusive'\n\t\t\t| 'RangeExclusive'}`}`;\n\nfunction arrayLengthComparator(comparator: Comparator, name: ArrayConstraintName, expected: string, length: number): IConstraint {\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.length < ${value}`;\n\treturn arrayLengthComparator(lessThan, 's.array(T).lengthLessThan', expected, value);\n}\n\nexport function arrayLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length <= ${value}`;\n\treturn arrayLengthComparator(lessThanOrEqual, 's.array(T).lengthLessThanOrEqual', expected, value);\n}\n\nexport function arrayLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.length > ${value}`;\n\treturn arrayLengthComparator(greaterThan, 's.array(T).lengthGreaterThan', expected, value);\n}\n\nexport function arrayLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length >= ${value}`;\n\treturn arrayLengthComparator(greaterThanOrEqual, 's.array(T).lengthGreaterThanOrEqual', expected, value);\n}\n\nexport function arrayLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.length === ${value}`;\n\treturn arrayLengthComparator(equal, 's.array(T).lengthEqual', expected, value);\n}\n\nexport function arrayLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.length !== ${value}`;\n\treturn arrayLengthComparator(notEqual, 's.array(T).lengthNotEqual', expected, value);\n}\n\nexport function arrayLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length >= start && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRange', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthRangeInclusive(start: number, end: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length <= ${end}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length >= start && input.length <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRangeInclusive', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length > startAfter && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRangeExclusive', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport const uniqueArray: IConstraint = {\n\trun(input: unknown[]) {\n\t\treturn isUnique(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).unique', 'Array values are not unique', input, 'Expected all values to be unique'));\n\t}\n};\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class CombinedPropertyError extends BaseError {\n\tpublic readonly errors: [PropertyKey, BaseError][];\n\n\tpublic constructor(errors: [PropertyKey, BaseError][]) {\n\t\tsuper('Received one or more errors');\n\n\t\tthis.errors = errors;\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize('[CombinedPropertyError]', 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\n\t\tconst header = `${options.stylize('CombinedPropertyError', 'special')} (${options.stylize(this.errors.length.toString(), 'number')})`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst errors = this.errors\n\t\t\t.map(([key, error]) => {\n\t\t\t\tconst property = CombinedPropertyError.formatProperty(key, options);\n\t\t\t\tconst body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\\n/g, padding);\n\n\t\t\t\treturn ` input${property}${padding}${body}`;\n\t\t\t})\n\t\t\t.join('\\n\\n');\n\t\treturn `${header}\\n ${message}\\n\\n${errors}`;\n\t}\n\n\tprivate static formatProperty(key: PropertyKey, options: InspectOptionsStylized): string {\n\t\tif (typeof key === 'string') return options.stylize(`.${key}`, 'symbol');\n\t\tif (typeof key === 'number') return `[${options.stylize(key.toString(), 'number')}]`;\n\t\treturn `[${options.stylize('Symbol', 'symbol')}(${key.description})]`;\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class ValidationError extends BaseError {\n\tpublic readonly validator: string;\n\tpublic readonly given: unknown;\n\n\tpublic constructor(validator: string, message: string, given: unknown) {\n\t\tsuper(message);\n\n\t\tthis.validator = validator;\n\t\tthis.given = given;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalidator: this.validator,\n\t\t\tgiven: this.given\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst validator = options.stylize(this.validator, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ValidationError: ${validator}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ValidationError', 'special')} > ${validator}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${givenBlock}`;\n\t}\n}\n","import {\n\tarrayLengthEqual,\n\tarrayLengthGreaterThan,\n\tarrayLengthGreaterThanOrEqual,\n\tarrayLengthLessThan,\n\tarrayLengthLessThanOrEqual,\n\tarrayLengthNotEqual,\n\tarrayLengthRange,\n\tarrayLengthRangeExclusive,\n\tarrayLengthRangeInclusive,\n\tuniqueArray\n} from '../constraints/ArrayConstraints';\nimport type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport type { ExpandSmallerTuples, Tuple, UnshiftTuple } from '../lib/util-types';\nimport { BaseValidator } from './imports';\n\nexport class ArrayValidator extends BaseValidator {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tpublic lengthLessThan(length: N): ArrayValidator]>>> {\n\t\treturn this.addConstraint(arrayLengthLessThan(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthLessThanOrEqual(length: N): ArrayValidator]>> {\n\t\treturn this.addConstraint(arrayLengthLessThanOrEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthGreaterThan(length: N): ArrayValidator<[...Tuple, I, ...T]> {\n\t\treturn this.addConstraint(arrayLengthGreaterThan(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: N): ArrayValidator<[...Tuple, ...T]> {\n\t\treturn this.addConstraint(arrayLengthGreaterThanOrEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthEqual(length: N): ArrayValidator<[...Tuple]> {\n\t\treturn this.addConstraint(arrayLengthEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthNotEqual(length: number): ArrayValidator<[...T]> {\n\t\treturn this.addConstraint(arrayLengthNotEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthRange(\n\t\tstart: S,\n\t\tendBefore: E\n\t): ArrayValidator]>>, ExpandSmallerTuples]>>>> {\n\t\treturn this.addConstraint(arrayLengthRange(start, endBefore) as IConstraint) as any;\n\t}\n\n\tpublic lengthRangeInclusive(\n\t\tstartAt: S,\n\t\tendAt: E\n\t): ArrayValidator]>, ExpandSmallerTuples]>>>> {\n\t\treturn this.addConstraint(arrayLengthRangeInclusive(startAt, endAt) as IConstraint) as any;\n\t}\n\n\tpublic lengthRangeExclusive(\n\t\tstartAfter: S,\n\t\tendBefore: E\n\t): ArrayValidator]>>, ExpandSmallerTuples<[...Tuple]>>> {\n\t\treturn this.addConstraint(arrayLengthRangeExclusive(startAfter, endBefore) as IConstraint) as any;\n\t}\n\n\tpublic get unique(): this {\n\t\treturn this.addConstraint(uniqueArray as IConstraint);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result {\n\t\tif (!Array.isArray(values)) {\n\t\t\treturn Result.err(new ValidationError('s.array(T)', 'Expected an array', values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values as T);\n\t\t}\n\n\t\tconst errors: [number, BaseError][] = [];\n\t\tconst transformed: T = [] as unknown as T;\n\n\t\tfor (let i = 0; i < values.length; i++) {\n\t\t\tconst result = this.validator.run(values[i]);\n\t\t\tif (result.isOk()) transformed.push(result.value);\n\t\t\telse errors.push([i, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type BigIntConstraintName = `s.bigint.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'notEqual'\n\t| 'divisibleBy'}`;\n\nfunction bigintComparator(comparator: Comparator, name: BigIntConstraintName, expected: string, number: bigint): IConstraint {\n\treturn {\n\t\trun(input: bigint) {\n\t\t\treturn comparator(input, number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid bigint value', input, expected));\n\t\t}\n\t};\n}\n\nexport function bigintLessThan(value: bigint): IConstraint {\n\tconst expected = `expected < ${value}n`;\n\treturn bigintComparator(lessThan, 's.bigint.lessThan', expected, value);\n}\n\nexport function bigintLessThanOrEqual(value: bigint): IConstraint {\n\tconst expected = `expected <= ${value}n`;\n\treturn bigintComparator(lessThanOrEqual, 's.bigint.lessThanOrEqual', expected, value);\n}\n\nexport function bigintGreaterThan(value: bigint): IConstraint {\n\tconst expected = `expected > ${value}n`;\n\treturn bigintComparator(greaterThan, 's.bigint.greaterThan', expected, value);\n}\n\nexport function bigintGreaterThanOrEqual(value: bigint): IConstraint {\n\tconst expected = `expected >= ${value}n`;\n\treturn bigintComparator(greaterThanOrEqual, 's.bigint.greaterThanOrEqual', expected, value);\n}\n\nexport function bigintEqual(value: bigint): IConstraint {\n\tconst expected = `expected === ${value}n`;\n\treturn bigintComparator(equal, 's.bigint.equal', expected, value);\n}\n\nexport function bigintNotEqual(value: bigint): IConstraint {\n\tconst expected = `expected !== ${value}n`;\n\treturn bigintComparator(notEqual, 's.bigint.notEqual', expected, value);\n}\n\nexport function bigintDivisibleBy(divider: bigint): IConstraint {\n\tconst expected = `expected % ${divider}n === 0n`;\n\treturn {\n\t\trun(input: bigint) {\n\t\t\treturn input % divider === 0n //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.bigint.divisibleBy', 'BigInt is not divisible', input, expected));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tbigintDivisibleBy,\n\tbigintEqual,\n\tbigintGreaterThan,\n\tbigintGreaterThanOrEqual,\n\tbigintLessThan,\n\tbigintLessThanOrEqual,\n\tbigintNotEqual\n} from '../constraints/BigIntConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class BigIntValidator extends BaseValidator {\n\tpublic lessThan(number: bigint): this {\n\t\treturn this.addConstraint(bigintLessThan(number) as IConstraint);\n\t}\n\n\tpublic lessThanOrEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintLessThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic greaterThan(number: bigint): this {\n\t\treturn this.addConstraint(bigintGreaterThan(number) as IConstraint);\n\t}\n\n\tpublic greaterThanOrEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintGreaterThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic equal(number: N): BigIntValidator {\n\t\treturn this.addConstraint(bigintEqual(number) as IConstraint) as unknown as BigIntValidator;\n\t}\n\n\tpublic notEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintNotEqual(number) as IConstraint);\n\t}\n\n\tpublic get positive(): this {\n\t\treturn this.greaterThanOrEqual(0n);\n\t}\n\n\tpublic get negative(): this {\n\t\treturn this.lessThan(0n);\n\t}\n\n\tpublic divisibleBy(number: bigint): this {\n\t\treturn this.addConstraint(bigintDivisibleBy(number) as IConstraint);\n\t}\n\n\tpublic get abs(): this {\n\t\treturn this.transform((value) => (value < 0 ? -value : value) as T);\n\t}\n\n\tpublic intN(bits: number): this {\n\t\treturn this.transform((value) => BigInt.asIntN(bits, value) as T);\n\t}\n\n\tpublic uintN(bits: number): this {\n\t\treturn this.transform((value) => BigInt.asUintN(bits, value) as T);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'bigint' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.bigint', 'Expected a bigint primitive', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\n\nexport type BooleanConstraintName = `s.boolean.${boolean}`;\n\nexport const booleanTrue: IConstraint = {\n\trun(input: boolean) {\n\t\treturn input //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.boolean.true', 'Invalid boolean value', input, 'true'));\n\t}\n};\n\nexport const booleanFalse: IConstraint = {\n\trun(input: boolean) {\n\t\treturn input //\n\t\t\t? Result.err(new ExpectedConstraintError('s.boolean.false', 'Invalid boolean value', input, 'false'))\n\t\t\t: Result.ok(input);\n\t}\n};\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { booleanFalse, booleanTrue } from '../constraints/BooleanConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class BooleanValidator extends BaseValidator {\n\tpublic get true(): BooleanValidator {\n\t\treturn this.addConstraint(booleanTrue as IConstraint) as BooleanValidator;\n\t}\n\n\tpublic get false(): BooleanValidator {\n\t\treturn this.addConstraint(booleanFalse as IConstraint) as BooleanValidator;\n\t}\n\n\tpublic equal(value: R): BooleanValidator {\n\t\treturn (value ? this.true : this.false) as BooleanValidator;\n\t}\n\n\tpublic notEqual(value: R): BooleanValidator {\n\t\treturn (value ? this.false : this.true) as BooleanValidator;\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'boolean' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.boolean', 'Expected a boolean primitive', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type DateConstraintName = `s.date.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'notEqual'\n\t| 'valid'\n\t| 'invalid'}`;\n\nfunction dateComparator(comparator: Comparator, name: DateConstraintName, expected: string, number: number): IConstraint {\n\treturn {\n\t\trun(input: Date) {\n\t\t\treturn comparator(input.getTime(), number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Date value', input, expected));\n\t\t}\n\t};\n}\n\nexport function dateLessThan(value: Date): IConstraint {\n\tconst expected = `expected < ${value.toISOString()}`;\n\treturn dateComparator(lessThan, 's.date.lessThan', expected, value.getTime());\n}\n\nexport function dateLessThanOrEqual(value: Date): IConstraint {\n\tconst expected = `expected <= ${value.toISOString()}`;\n\treturn dateComparator(lessThanOrEqual, 's.date.lessThanOrEqual', expected, value.getTime());\n}\n\nexport function dateGreaterThan(value: Date): IConstraint {\n\tconst expected = `expected > ${value.toISOString()}`;\n\treturn dateComparator(greaterThan, 's.date.greaterThan', expected, value.getTime());\n}\n\nexport function dateGreaterThanOrEqual(value: Date): IConstraint {\n\tconst expected = `expected >= ${value.toISOString()}`;\n\treturn dateComparator(greaterThanOrEqual, 's.date.greaterThanOrEqual', expected, value.getTime());\n}\n\nexport function dateEqual(value: Date): IConstraint {\n\tconst expected = `expected === ${value.toISOString()}`;\n\treturn dateComparator(equal, 's.date.equal', expected, value.getTime());\n}\n\nexport function dateNotEqual(value: Date): IConstraint {\n\tconst expected = `expected !== ${value.toISOString()}`;\n\treturn dateComparator(notEqual, 's.date.notEqual', expected, value.getTime());\n}\n\nexport const dateInvalid: IConstraint = {\n\trun(input: Date) {\n\t\treturn Number.isNaN(input.getTime()) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.date.invalid', 'Invalid Date value', input, 'expected === NaN'));\n\t}\n};\n\nexport const dateValid: IConstraint = {\n\trun(input: Date) {\n\t\treturn Number.isNaN(input.getTime()) //\n\t\t\t? Result.err(new ExpectedConstraintError('s.date.valid', 'Invalid Date value', input, 'expected !== NaN'))\n\t\t\t: Result.ok(input);\n\t}\n};\n","import {\n\tdateEqual,\n\tdateGreaterThan,\n\tdateGreaterThanOrEqual,\n\tdateInvalid,\n\tdateLessThan,\n\tdateLessThanOrEqual,\n\tdateNotEqual,\n\tdateValid\n} from '../constraints/DateConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class DateValidator extends BaseValidator {\n\tpublic lessThan(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateLessThan(new Date(date)));\n\t}\n\n\tpublic lessThanOrEqual(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateLessThanOrEqual(new Date(date)));\n\t}\n\n\tpublic greaterThan(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateGreaterThan(new Date(date)));\n\t}\n\n\tpublic greaterThanOrEqual(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateGreaterThanOrEqual(new Date(date)));\n\t}\n\n\tpublic equal(date: Date | number | string): this {\n\t\tconst resolved = new Date(date);\n\t\treturn Number.isNaN(resolved.getTime()) //\n\t\t\t? this.invalid\n\t\t\t: this.addConstraint(dateEqual(resolved));\n\t}\n\n\tpublic notEqual(date: Date | number | string): this {\n\t\tconst resolved = new Date(date);\n\t\treturn Number.isNaN(resolved.getTime()) //\n\t\t\t? this.valid\n\t\t\t: this.addConstraint(dateNotEqual(resolved));\n\t}\n\n\tpublic get valid(): this {\n\t\treturn this.addConstraint(dateValid);\n\t}\n\n\tpublic get invalid(): this {\n\t\treturn this.addConstraint(dateInvalid);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn value instanceof Date //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ValidationError('s.date', 'Expected a Date', value));\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { ValidationError } from './ValidationError';\n\nexport class ExpectedValidationError extends ValidationError {\n\tpublic readonly expected: T;\n\n\tpublic constructor(validator: string, message: string, given: unknown, expected: T) {\n\t\tsuper(validator, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic override toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalidator: this.validator,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst validator = options.stylize(this.validator, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ExpectedValidationError: ${validator}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst expected = inspect(this.expected, newOptions).replace(/\\n/g, padding);\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ExpectedValidationError', 'special')} > ${validator}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected:', 'string')}${padding}${expected}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { ExpectedValidationError } from '../lib/errors/ExpectedValidationError';\nimport { Result } from '../lib/Result';\nimport type { Constructor } from '../lib/util-types';\nimport { BaseValidator } from './imports';\n\nexport class InstanceValidator extends BaseValidator {\n\tpublic readonly expected: Constructor;\n\n\tpublic constructor(expected: Constructor, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.expected = expected;\n\t}\n\n\tprotected handle(value: unknown): Result>> {\n\t\treturn value instanceof this.expected //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ExpectedValidationError('s.instance(V)', 'Expected', value, this.expected));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.expected, this.constraints]);\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { ExpectedValidationError } from '../lib/errors/ExpectedValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class LiteralValidator extends BaseValidator {\n\tpublic readonly expected: T;\n\n\tpublic constructor(literal: T, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.expected = literal;\n\t}\n\n\tprotected handle(value: unknown): Result> {\n\t\treturn Object.is(value, this.expected) //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ExpectedValidationError('s.literal(V)', 'Expected values to be equals', value, this.expected));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.expected, this.constraints]);\n\t}\n}\n","import { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NeverValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn Result.err(new ValidationError('s.never', 'Expected a value to not be passed', value));\n\t}\n}\n","import { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NullishValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn value === undefined || value === null //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ValidationError('s.nullish', 'Expected undefined or null', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type NumberConstraintName = `s.number.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'equal(NaN)'\n\t| 'notEqual'\n\t| 'notEqual(NaN)'\n\t| 'int'\n\t| 'safeInt'\n\t| 'finite'\n\t| 'divisibleBy'}`;\n\nfunction numberComparator(comparator: Comparator, name: NumberConstraintName, expected: string, number: number): IConstraint {\n\treturn {\n\t\trun(input: number) {\n\t\t\treturn comparator(input, number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid number value', input, expected));\n\t\t}\n\t};\n}\n\nexport function numberLessThan(value: number): IConstraint {\n\tconst expected = `expected < ${value}`;\n\treturn numberComparator(lessThan, 's.number.lessThan', expected, value);\n}\n\nexport function numberLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected <= ${value}`;\n\treturn numberComparator(lessThanOrEqual, 's.number.lessThanOrEqual', expected, value);\n}\n\nexport function numberGreaterThan(value: number): IConstraint {\n\tconst expected = `expected > ${value}`;\n\treturn numberComparator(greaterThan, 's.number.greaterThan', expected, value);\n}\n\nexport function numberGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected >= ${value}`;\n\treturn numberComparator(greaterThanOrEqual, 's.number.greaterThanOrEqual', expected, value);\n}\n\nexport function numberEqual(value: number): IConstraint {\n\tconst expected = `expected === ${value}`;\n\treturn numberComparator(equal, 's.number.equal', expected, value);\n}\n\nexport function numberNotEqual(value: number): IConstraint {\n\tconst expected = `expected !== ${value}`;\n\treturn numberComparator(notEqual, 's.number.notEqual', expected, value);\n}\n\nexport const numberInt: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isInteger(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(\n\t\t\t\t\tnew ExpectedConstraintError('s.number.int', 'Given value is not an integer', input, 'Number.isInteger(expected) to be true')\n\t\t\t );\n\t}\n};\n\nexport const numberSafeInt: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isSafeInteger(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(\n\t\t\t\t\tnew ExpectedConstraintError(\n\t\t\t\t\t\t's.number.safeInt',\n\t\t\t\t\t\t'Given value is not a safe integer',\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\t'Number.isSafeInteger(expected) to be true'\n\t\t\t\t\t)\n\t\t\t );\n\t}\n};\n\nexport const numberFinite: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isFinite(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.number.finite', 'Given value is not finite', input, 'Number.isFinite(expected) to be true'));\n\t}\n};\n\nexport const numberNaN: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isNaN(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.number.equal(NaN)', 'Invalid number value', input, 'expected === NaN'));\n\t}\n};\n\nexport const numberNotNaN: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isNaN(input) //\n\t\t\t? Result.err(new ExpectedConstraintError('s.number.notEqual(NaN)', 'Invalid number value', input, 'expected !== NaN'))\n\t\t\t: Result.ok(input);\n\t}\n};\n\nexport function numberDivisibleBy(divider: number): IConstraint {\n\tconst expected = `expected % ${divider} === 0`;\n\treturn {\n\t\trun(input: number) {\n\t\t\treturn input % divider === 0 //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.number.divisibleBy', 'Number is not divisible', input, expected));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tnumberDivisibleBy,\n\tnumberEqual,\n\tnumberFinite,\n\tnumberGreaterThan,\n\tnumberGreaterThanOrEqual,\n\tnumberInt,\n\tnumberLessThan,\n\tnumberLessThanOrEqual,\n\tnumberNaN,\n\tnumberNotEqual,\n\tnumberNotNaN,\n\tnumberSafeInt\n} from '../constraints/NumberConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NumberValidator extends BaseValidator {\n\tpublic lessThan(number: number): this {\n\t\treturn this.addConstraint(numberLessThan(number) as IConstraint);\n\t}\n\n\tpublic lessThanOrEqual(number: number): this {\n\t\treturn this.addConstraint(numberLessThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic greaterThan(number: number): this {\n\t\treturn this.addConstraint(numberGreaterThan(number) as IConstraint);\n\t}\n\n\tpublic greaterThanOrEqual(number: number): this {\n\t\treturn this.addConstraint(numberGreaterThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic equal(number: N): NumberValidator {\n\t\treturn Number.isNaN(number) //\n\t\t\t? (this.addConstraint(numberNaN as IConstraint) as unknown as NumberValidator)\n\t\t\t: (this.addConstraint(numberEqual(number) as IConstraint) as unknown as NumberValidator);\n\t}\n\n\tpublic notEqual(number: number): this {\n\t\treturn Number.isNaN(number) //\n\t\t\t? this.addConstraint(numberNotNaN as IConstraint)\n\t\t\t: this.addConstraint(numberNotEqual(number) as IConstraint);\n\t}\n\n\tpublic get int(): this {\n\t\treturn this.addConstraint(numberInt as IConstraint);\n\t}\n\n\tpublic get safeInt(): this {\n\t\treturn this.addConstraint(numberSafeInt as IConstraint);\n\t}\n\n\tpublic get finite(): this {\n\t\treturn this.addConstraint(numberFinite as IConstraint);\n\t}\n\n\tpublic get positive(): this {\n\t\treturn this.greaterThanOrEqual(0);\n\t}\n\n\tpublic get negative(): this {\n\t\treturn this.lessThan(0);\n\t}\n\n\tpublic divisibleBy(divider: number): this {\n\t\treturn this.addConstraint(numberDivisibleBy(divider) as IConstraint);\n\t}\n\n\tpublic get abs(): this {\n\t\treturn this.transform(Math.abs as (value: number) => T);\n\t}\n\n\tpublic get sign(): this {\n\t\treturn this.transform(Math.sign as (value: number) => T);\n\t}\n\n\tpublic get trunc(): this {\n\t\treturn this.transform(Math.trunc as (value: number) => T);\n\t}\n\n\tpublic get floor(): this {\n\t\treturn this.transform(Math.floor as (value: number) => T);\n\t}\n\n\tpublic get fround(): this {\n\t\treturn this.transform(Math.fround as (value: number) => T);\n\t}\n\n\tpublic get round(): this {\n\t\treturn this.transform(Math.round as (value: number) => T);\n\t}\n\n\tpublic get ceil(): this {\n\t\treturn this.transform(Math.ceil as (value: number) => T);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'number' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.number', 'Expected a number primitive', value));\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class MissingPropertyError extends BaseError {\n\tpublic readonly property: PropertyKey;\n\n\tpublic constructor(property: PropertyKey) {\n\t\tsuper('A required property is missing');\n\t\tthis.property = property;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tproperty: this.property\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst property = options.stylize(this.property.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[MissingPropertyError: ${property}]`, 'special');\n\t\t}\n\n\t\tconst header = `${options.stylize('MissingPropertyError', 'special')} > ${property}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\treturn `${header}\\n ${message}`;\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class UnknownPropertyError extends BaseError {\n\tpublic readonly property: PropertyKey;\n\tpublic readonly value: unknown;\n\n\tpublic constructor(property: PropertyKey, value: unknown) {\n\t\tsuper('Received unexpected property');\n\n\t\tthis.property = property;\n\t\tthis.value = value;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tproperty: this.property,\n\t\t\tvalue: this.value\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst property = options.stylize(this.property.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[UnknownPropertyError: ${property}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.value, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('UnknownPropertyError', 'special')} > ${property}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${givenBlock}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { Result } from '../lib/Result';\nimport type { ValidatorError } from './BaseValidator';\nimport { BaseValidator } from './imports';\nimport { getValue } from './util/getValue';\n\nexport class DefaultValidator extends BaseValidator {\n\tprivate readonly validator: BaseValidator;\n\tprivate defaultValue: T | (() => T);\n\n\tpublic constructor(validator: BaseValidator, value: T | (() => T), constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t\tthis.defaultValue = value;\n\t}\n\n\tpublic override default(value: Exclude | (() => Exclude)): DefaultValidator> {\n\t\tconst clone = this.clone() as unknown as DefaultValidator>;\n\t\tclone.defaultValue = value;\n\t\treturn clone;\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'undefined' //\n\t\t\t? Result.ok(getValue(this.defaultValue))\n\t\t\t: this.validator['handle'](value); // eslint-disable-line @typescript-eslint/dot-notation\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.defaultValue, this.constraints]);\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class CombinedError extends BaseError {\n\tpublic readonly errors: readonly BaseError[];\n\n\tpublic constructor(errors: readonly BaseError[]) {\n\t\tsuper('Received one or more errors');\n\n\t\tthis.errors = errors;\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize('[CombinedError]', 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\n\t\tconst header = `${options.stylize('CombinedError', 'special')} (${options.stylize(this.errors.length.toString(), 'number')})`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst errors = this.errors\n\t\t\t.map((error, i) => {\n\t\t\t\tconst index = options.stylize((i + 1).toString(), 'number');\n\t\t\t\tconst body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\\n/g, padding);\n\n\t\t\t\treturn ` ${index} ${body}`;\n\t\t\t})\n\t\t\t.join('\\n\\n');\n\t\treturn `${header}\\n ${message}\\n\\n${errors}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedError } from '../lib/errors/CombinedError';\nimport type { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator, LiteralValidator, NullishValidator } from './imports';\n\nexport class UnionValidator extends BaseValidator {\n\tprivate validators: readonly BaseValidator[];\n\n\tpublic constructor(validators: readonly BaseValidator[], constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validators = validators;\n\t}\n\n\tpublic override get optional(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new LiteralValidator(undefined)], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already optional, return a clone:\n\t\t\tif (validator.expected === undefined) return this.clone();\n\n\t\t\t// If it's nullable, convert the nullable validator into a nullish validator to optimize `null | undefined`:\n\t\t\tif (validator.expected === null) {\n\t\t\t\treturn new UnionValidator(\n\t\t\t\t\t[new NullishValidator(), ...this.validators.slice(1)],\n\t\t\t\t\tthis.constraints\n\t\t\t\t) as UnionValidator;\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish (which validates optional), return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new LiteralValidator(undefined), ...this.validators]);\n\t}\n\n\tpublic get required(): UnionValidator> {\n\t\ttype RequiredValidator = UnionValidator>;\n\n\t\tif (this.validators.length === 0) return this.clone() as unknown as RequiredValidator;\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\tif (validator.expected === undefined) return new UnionValidator(this.validators.slice(1), this.constraints) as RequiredValidator;\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\treturn new UnionValidator([new LiteralValidator(null), ...this.validators.slice(1)], this.constraints) as RequiredValidator;\n\t\t}\n\n\t\treturn this.clone() as unknown as RequiredValidator;\n\t}\n\n\tpublic override get nullable(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new LiteralValidator(null)], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already nullable, return a clone:\n\t\t\tif (validator.expected === null) return this.clone();\n\n\t\t\t// If it's optional, convert the optional validator into a nullish validator to optimize `null | undefined`:\n\t\t\tif (validator.expected === undefined) {\n\t\t\t\treturn new UnionValidator(\n\t\t\t\t\t[new NullishValidator(), ...this.validators.slice(1)],\n\t\t\t\t\tthis.constraints\n\t\t\t\t) as UnionValidator;\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish (which validates nullable), return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new LiteralValidator(null), ...this.validators]);\n\t}\n\n\tpublic override get nullish(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new NullishValidator()], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already nullable or optional, promote the union to nullish:\n\t\t\tif (validator.expected === null || validator.expected === undefined) {\n\t\t\t\treturn new UnionValidator([new NullishValidator(), ...this.validators.slice(1)], this.constraints);\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish, return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new NullishValidator(), ...this.validators]);\n\t}\n\n\tpublic override or(...predicates: readonly BaseValidator[]): UnionValidator {\n\t\treturn new UnionValidator([...this.validators, ...predicates]);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validators, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\tconst errors: BaseError[] = [];\n\n\t\tfor (const validator of this.validators) {\n\t\t\tconst result = validator.run(value);\n\t\t\tif (result.isOk()) return result as Result;\n\t\t\terrors.push(result.error!);\n\t\t}\n\n\t\treturn Result.err(new CombinedError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { MissingPropertyError } from '../lib/errors/MissingPropertyError';\nimport { UnknownPropertyError } from '../lib/errors/UnknownPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport type { MappedObjectValidator, UndefinedToOptional } from '../lib/util-types';\nimport { BaseValidator } from './BaseValidator';\nimport { DefaultValidator } from './DefaultValidator';\nimport { LiteralValidator } from './LiteralValidator';\nimport { NullishValidator } from './NullishValidator';\nimport { UnionValidator } from './UnionValidator';\n\nexport class ObjectValidator> extends BaseValidator {\n\tpublic readonly shape: MappedObjectValidator;\n\tpublic readonly strategy: ObjectValidatorStrategy;\n\tprivate readonly keys: readonly (keyof I)[] = [];\n\tprivate readonly handleStrategy: (value: object) => Result;\n\n\tprivate readonly requiredKeys = new Map>();\n\tprivate readonly possiblyUndefinedKeys = new Map>();\n\tprivate readonly possiblyUndefinedKeysWithDefaults = new Map>();\n\n\tpublic constructor(\n\t\tshape: MappedObjectValidator,\n\t\tstrategy: ObjectValidatorStrategy = ObjectValidatorStrategy.Ignore,\n\t\tconstraints: readonly IConstraint[] = []\n\t) {\n\t\tsuper(constraints);\n\t\tthis.shape = shape;\n\t\tthis.strategy = strategy;\n\n\t\tswitch (this.strategy) {\n\t\t\tcase ObjectValidatorStrategy.Ignore:\n\t\t\t\tthis.handleStrategy = (value) => this.handleIgnoreStrategy(value);\n\t\t\t\tbreak;\n\t\t\tcase ObjectValidatorStrategy.Strict: {\n\t\t\t\tthis.handleStrategy = (value) => this.handleStrictStrategy(value);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase ObjectValidatorStrategy.Passthrough:\n\t\t\t\tthis.handleStrategy = (value) => this.handlePassthroughStrategy(value);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst shapeEntries = Object.entries(shape) as [keyof I, BaseValidator][];\n\t\tthis.keys = shapeEntries.map(([key]) => key);\n\n\t\tfor (const [key, validator] of shapeEntries) {\n\t\t\tif (validator instanceof UnionValidator) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\t\t\tconst [possiblyLiteralOrNullishPredicate] = validator['validators'];\n\n\t\t\t\tif (possiblyLiteralOrNullishPredicate instanceof NullishValidator) {\n\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t} else if (possiblyLiteralOrNullishPredicate instanceof LiteralValidator) {\n\t\t\t\t\tif (possiblyLiteralOrNullishPredicate.expected === undefined) {\n\t\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t\t}\n\t\t\t\t} else if (validator instanceof DefaultValidator) {\n\t\t\t\t\tthis.possiblyUndefinedKeysWithDefaults.set(key, validator);\n\t\t\t\t} else {\n\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t}\n\t\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t} else if (validator instanceof LiteralValidator) {\n\t\t\t\tif (validator.expected === undefined) {\n\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t} else {\n\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t}\n\t\t\t} else if (validator instanceof DefaultValidator) {\n\t\t\t\tthis.possiblyUndefinedKeysWithDefaults.set(key, validator);\n\t\t\t} else {\n\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic get strict(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Strict, this.constraints]);\n\t}\n\n\tpublic get ignore(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Ignore, this.constraints]);\n\t}\n\n\tpublic get passthrough(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Passthrough, this.constraints]);\n\t}\n\n\tpublic get partial(): ObjectValidator<{ [Key in keyof I]?: I[Key] }> {\n\t\tconst shape = Object.fromEntries(this.keys.map((key) => [key, this.shape[key as unknown as keyof typeof this.shape].optional]));\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic get required(): ObjectValidator<{ [Key in keyof I]-?: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tthis.keys.map((key) => {\n\t\t\t\tlet validator = this.shape[key as unknown as keyof typeof this.shape];\n\t\t\t\tif (validator instanceof UnionValidator) validator = validator.required;\n\t\t\t\treturn [key, validator];\n\t\t\t})\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic extend(schema: ObjectValidator | MappedObjectValidator): ObjectValidator {\n\t\tconst shape = { ...this.shape, ...(schema instanceof ObjectValidator ? schema.shape : schema) };\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic pick(keys: readonly K[]): ObjectValidator<{ [Key in keyof Pick]: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tkeys.filter((key) => this.keys.includes(key)).map((key) => [key, this.shape[key as unknown as keyof typeof this.shape]])\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic omit(keys: readonly K[]): ObjectValidator<{ [Key in keyof Omit]: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tthis.keys.filter((key) => !keys.includes(key as any)).map((key) => [key, this.shape[key as unknown as keyof typeof this.shape]])\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tprotected override handle(value: unknown): Result {\n\t\tconst typeOfValue = typeof value;\n\t\tif (typeOfValue !== 'object') {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', `Expected the value to be an object, but received ${typeOfValue} instead`, value));\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', 'Expected the value to not be null', value));\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', 'Expected the value to not be an array', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value as I);\n\t\t}\n\n\t\tfor (const predicate of Object.values(this.shape) as BaseValidator[]) {\n\t\t\tpredicate.setParent(this.parent ?? value!);\n\t\t}\n\n\t\treturn this.handleStrategy(value as object);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, this.strategy, this.constraints]);\n\t}\n\n\tprivate handleIgnoreStrategy(value: object): Result {\n\t\tconst errors: [PropertyKey, BaseError][] = [];\n\t\tconst finalObject = {} as I;\n\t\tconst inputEntries = new Map(Object.entries(value) as [keyof I, unknown][]);\n\n\t\tconst runPredicate = (key: keyof I, predicate: BaseValidator) => {\n\t\t\tconst result = predicate.run(value[key as keyof object]);\n\n\t\t\tif (result.isOk()) {\n\t\t\t\tfinalObject[key] = result.value as I[keyof I];\n\t\t\t} else {\n\t\t\t\tconst error = result.error!;\n\t\t\t\terrors.push([key, error]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [key, predicate] of this.requiredKeys) {\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t} else {\n\t\t\t\terrors.push([key, new MissingPropertyError(key)]);\n\t\t\t}\n\t\t}\n\n\t\t// Run possibly undefined keys that also have defaults even if there are no more keys to process (this is necessary so we fill in those defaults)\n\t\tfor (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) {\n\t\t\tinputEntries.delete(key);\n\t\t\trunPredicate(key, validator);\n\t\t}\n\n\t\t// Early exit if there are no more properties to validate in the object and there are errors to report\n\t\tif (inputEntries.size === 0) {\n\t\t\treturn errors.length === 0 //\n\t\t\t\t? Result.ok(finalObject)\n\t\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t\t}\n\n\t\t// In the event the remaining keys to check are less than the number of possible undefined keys, we check those\n\t\t// as it could yield a faster execution\n\t\tconst checkInputEntriesInsteadOfSchemaKeys = this.possiblyUndefinedKeys.size > inputEntries.size;\n\n\t\tif (checkInputEntriesInsteadOfSchemaKeys) {\n\t\t\tfor (const [key] of inputEntries) {\n\t\t\t\tconst predicate = this.possiblyUndefinedKeys.get(key);\n\n\t\t\t\tif (predicate) {\n\t\t\t\t\trunPredicate(key, predicate);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const [key, predicate] of this.possiblyUndefinedKeys) {\n\t\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\t\trunPredicate(key, predicate);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(finalObject)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n\n\tprivate handleStrictStrategy(value: object): Result {\n\t\tconst errors: [PropertyKey, BaseError][] = [];\n\t\tconst finalResult = {} as I;\n\t\tconst inputEntries = new Map(Object.entries(value) as [keyof I, unknown][]);\n\n\t\tconst runPredicate = (key: keyof I, predicate: BaseValidator) => {\n\t\t\tconst result = predicate.run(value[key as keyof object]);\n\n\t\t\tif (result.isOk()) {\n\t\t\t\tfinalResult[key] = result.value as I[keyof I];\n\t\t\t} else {\n\t\t\t\tconst error = result.error!;\n\t\t\t\terrors.push([key, error]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [key, predicate] of this.requiredKeys) {\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t} else {\n\t\t\t\terrors.push([key, new MissingPropertyError(key)]);\n\t\t\t}\n\t\t}\n\n\t\t// Run possibly undefined keys that also have defaults even if there are no more keys to process (this is necessary so we fill in those defaults)\n\t\tfor (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) {\n\t\t\tinputEntries.delete(key);\n\t\t\trunPredicate(key, validator);\n\t\t}\n\n\t\tfor (const [key, predicate] of this.possiblyUndefinedKeys) {\n\t\t\t// All of these validators are assumed to be possibly undefined, so if we have gone through the entire object and there's still validators,\n\t\t\t// safe to assume we're done here\n\t\t\tif (inputEntries.size === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t}\n\t\t}\n\n\t\tif (inputEntries.size !== 0) {\n\t\t\tfor (const [key, value] of inputEntries.entries()) {\n\t\t\t\terrors.push([key, new UnknownPropertyError(key, value)]);\n\t\t\t}\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(finalResult)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n\n\tprivate handlePassthroughStrategy(value: object): Result {\n\t\tconst result = this.handleIgnoreStrategy(value);\n\t\treturn result.isErr() ? result : Result.ok({ ...value, ...result.value } as I);\n\t}\n}\n\nexport const enum ObjectValidatorStrategy {\n\tIgnore,\n\tStrict,\n\tPassthrough\n}\n","import type { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class PassthroughValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn Result.ok(value as T);\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class RecordValidator extends BaseValidator> {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result, ValidationError | CombinedPropertyError> {\n\t\tif (typeof value !== 'object') {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected an object', value));\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected the value to not be null', value));\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected the value to not be an array', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value as Record);\n\t\t}\n\n\t\tconst errors: [string, BaseError][] = [];\n\t\tconst transformed: Record = {};\n\n\t\tfor (const [key, val] of Object.entries(value!)) {\n\t\t\tconst result = this.validator.run(val);\n\t\t\tif (result.isOk()) transformed[key] = result.value;\n\t\t\telse errors.push([key, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedError } from '../lib/errors/CombinedError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class SetValidator extends BaseValidator> {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result, ValidationError | CombinedError> {\n\t\tif (!(values instanceof Set)) {\n\t\t\treturn Result.err(new ValidationError('s.set(T)', 'Expected a set', values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values);\n\t\t}\n\n\t\tconst errors: BaseError[] = [];\n\t\tconst transformed = new Set();\n\n\t\tfor (const value of values) {\n\t\t\tconst result = this.validator.run(value);\n\t\t\tif (result.isOk()) transformed.add(result.value);\n\t\t\telse errors.push(result.error!);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedError(errors));\n\t}\n}\n","/**\n * [RFC-5322](https://datatracker.ietf.org/doc/html/rfc5322)\n * compliant {@link RegExp} to validate an email address\n *\n * @see https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression/201378#201378\n */\nconst accountRegex =\n\t/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")$/;\n\n/**\n * Validates an email address string based on various checks:\n * - It must be a non nullish and non empty string\n * - It must include at least an `@` symbol`\n * - The account name may not exceed 64 characters\n * - The domain name may not exceed 255 characters\n * - The domain must include at least one `.` symbol\n * - Each part of the domain, split by `.` must not exceed 63 characters\n * - The email address must be [RFC-5322](https://datatracker.ietf.org/doc/html/rfc5322) compliant\n * @param email The email to validate\n * @returns `true` if the email is valid, `false` otherwise\n *\n * @remark Based on the following sources:\n * - `email-validator` by [manisharaan](https://github.com/manishsaraan) ([code](https://github.com/manishsaraan/email-validator/blob/master/index.js))\n * - [Comparing E-mail Address Validating Regular Expressions](http://fightingforalostcause.net/misc/2006/compare-email-regex.php)\n * - [Validating Email Addresses by Derrick Pallas](http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx)\n * - [StackOverflow answer by bortzmeyer](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378)\n * - [The wikipedia page on Email addresses](https://en.wikipedia.org/wiki/Email_address)\n */\nexport function validateEmail(email: string): boolean {\n\t// 1. Non-nullish and non-empty string check.\n\t//\n\t// If a nullish or empty email was provided then do an early exit\n\tif (!email) return false;\n\n\t// Find the location of the @ symbol:\n\tconst atIndex = email.indexOf('@');\n\n\t// 2. @ presence check.\n\t//\n\t// If the email does not have the @ symbol, it's automatically invalid:\n\tif (atIndex === -1) return false;\n\n\t// 3. maximum length check.\n\t//\n\t// From @, if exceeds 64 characters, then the\n\t// position of the @ symbol is 64 or greater. In this case, the email is\n\t// invalid:\n\tif (atIndex > 64) return false;\n\n\tconst domainIndex = atIndex + 1;\n\n\t// 7.1. Duplicated @ symbol check.\n\t//\n\t// If there's a second @ symbol, the email is automatically invalid:\n\tif (email.includes('@', domainIndex)) return false;\n\n\t// 4. maximum length check.\n\t//\n\t// From @, if exceeds 255 characters, then it\n\t// means that the amount of characters between the start of and the\n\t// end of the string is separated by 255 or more characters.\n\tif (email.length - domainIndex > 255) return false;\n\n\t// Find the location of the . symbol in :\n\tlet dotIndex = email.indexOf('.', domainIndex);\n\n\t// 5. dot (.) symbol check.\n\t//\n\t// From @, if does not contain a dot (.) symbol,\n\t// then it means the domain is invalid.\n\tif (dotIndex === -1) return false;\n\n\t// 6. parts length.\n\t//\n\t// Assign a temporary variable to store the start of the last read domain\n\t// part, this would be at the start of .\n\t//\n\t// For a part to be correct, it must have at most, 63 characters.\n\t// We repeat this step for every sub-section of contained within\n\t// dot (.) symbols.\n\t//\n\t// The following step is a more optimized version of the following code:\n\t//\n\t// ```javascript\n\t// domain.split('.').some((part) => part.length > 63);\n\t// ```\n\tlet lastDotIndex = domainIndex;\n\tdo {\n\t\tif (dotIndex - lastDotIndex > 63) return false;\n\n\t\tlastDotIndex = dotIndex + 1;\n\t} while ((dotIndex = email.indexOf('.', lastDotIndex)) !== -1);\n\n\t// The loop iterates from the first to the n - 1 part, this line checks for\n\t// the last (n) part:\n\tif (email.length - lastDotIndex > 63) return false;\n\n\t// 7.2. Character checks.\n\t//\n\t// From @:\n\t// - Extract the part by slicing the input from start to the @\n\t// character. Validate afterwards.\n\t// - Extract the part by slicing the input from the start of\n\t// . Validate afterwards.\n\t//\n\t// Note: we inline the variables so isn't created unless the\n\t// check passes.\n\treturn accountRegex.test(email.slice(0, atIndex)) && validateEmailDomain(email.slice(domainIndex));\n}\n\nfunction validateEmailDomain(domain: string): boolean {\n\ttry {\n\t\treturn new URL(`http://${domain}`).hostname === domain;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","/**\n * Code ported from https://github.com/nodejs/node/blob/5fad0b93667ffc6e4def52996b9529ac99b26319/lib/internal/net.js\n */\n\n// IPv4 Segment\nconst v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';\nconst v4Str = `(${v4Seg}[.]){3}${v4Seg}`;\nconst IPv4Reg = new RegExp(`^${v4Str}$`);\n\n// IPv6 Segment\nconst v6Seg = '(?:[0-9a-fA-F]{1,4})';\nconst IPv6Reg = new RegExp(\n\t'^(' +\n\t\t`(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +\n\t\t`(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +\n\t\t`(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +\n\t\t`(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +\n\t\t`(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +\n\t\t`(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +\n\t\t`(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +\n\t\t`(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +\n\t\t')(%[0-9a-zA-Z-.:]{1,})?$'\n);\n\nexport function isIPv4(s: string): boolean {\n\treturn IPv4Reg.test(s);\n}\n\nexport function isIPv6(s: string): boolean {\n\treturn IPv6Reg.test(s);\n}\n\nexport function isIP(s: string): number {\n\tif (isIPv4(s)) return 4;\n\tif (isIPv6(s)) return 6;\n\treturn 0;\n}\n","export const phoneNumberRegex = /^((?:\\+|0{0,2})\\d{1,2}\\s?)?\\(?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$/;\n\nexport function validatePhoneNumber(input: string) {\n\treturn phoneNumberRegex.test(input);\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { BaseConstraintError, type ConstraintErrorNames } from './BaseConstraintError';\n\nexport class MultiplePossibilitiesConstraintError extends BaseConstraintError {\n\tpublic readonly expected: readonly string[];\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: readonly string[]) {\n\t\tsuper(constraint, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tconstraint: this.constraint,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst constraint = options.stylize(this.constraint, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[MultiplePossibilitiesConstraintError: ${constraint}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst verticalLine = options.stylize('|', 'undefined');\n\t\tconst padding = `\\n ${verticalLine} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('MultiplePossibilitiesConstraintError', 'special')} > ${constraint}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\n\t\tconst expectedPadding = `\\n ${verticalLine} - `;\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected any of the following:', 'string')}${expectedPadding}${this.expected\n\t\t\t.map((possible) => options.stylize(possible, 'boolean'))\n\t\t\t.join(expectedPadding)}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","export function combinedErrorFn

(...fns: ErrorFn[]): ErrorFn {\n\tswitch (fns.length) {\n\t\tcase 0:\n\t\t\treturn () => null;\n\t\tcase 1:\n\t\t\treturn fns[0];\n\t\tcase 2: {\n\t\t\tconst [fn0, fn1] = fns;\n\t\t\treturn (...params) => fn0(...params) || fn1(...params);\n\t\t}\n\t\tdefault: {\n\t\t\treturn (...params) => {\n\t\t\t\tfor (const fn of fns) {\n\t\t\t\t\tconst result = fn(...params);\n\t\t\t\t\tif (result) return result;\n\t\t\t\t}\n\n\t\t\t\treturn null;\n\t\t\t};\n\t\t}\n\t}\n}\n\nexport type ErrorFn

= (...params: P) => E | null;\n","import { MultiplePossibilitiesConstraintError } from '../../lib/errors/MultiplePossibilitiesConstraintError';\nimport { combinedErrorFn, ErrorFn } from './common/combinedResultFn';\n\nexport type StringProtocol = `${string}:`;\n\nexport type StringDomain = `${string}.${string}`;\n\nexport interface UrlOptions {\n\tallowedProtocols?: StringProtocol[];\n\tallowedDomains?: StringDomain[];\n}\n\nexport function createUrlValidators(options?: UrlOptions) {\n\tconst fns: ErrorFn<[input: string, url: URL], MultiplePossibilitiesConstraintError>[] = [];\n\n\tif (options?.allowedProtocols?.length) fns.push(allowedProtocolsFn(options.allowedProtocols));\n\tif (options?.allowedDomains?.length) fns.push(allowedDomainsFn(options.allowedDomains));\n\n\treturn combinedErrorFn(...fns);\n}\n\nfunction allowedProtocolsFn(allowedProtocols: StringProtocol[]) {\n\treturn (input: string, url: URL) =>\n\t\tallowedProtocols.includes(url.protocol as StringProtocol)\n\t\t\t? null\n\t\t\t: new MultiplePossibilitiesConstraintError('s.string.url', 'Invalid URL protocol', input, allowedProtocols);\n}\n\nfunction allowedDomainsFn(allowedDomains: StringDomain[]) {\n\treturn (input: string, url: URL) =>\n\t\tallowedDomains.includes(url.hostname as StringDomain)\n\t\t\t? null\n\t\t\t: new MultiplePossibilitiesConstraintError('s.string.url', 'Invalid URL domain', input, allowedDomains);\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { validateEmail } from './util/emailValidator';\nimport { isIP, isIPv4, isIPv6 } from './util/net';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\nimport { validatePhoneNumber } from './util/phoneValidator';\nimport { createUrlValidators } from './util/urlValidators';\n\nexport type StringConstraintName =\n\t| `s.string.${\n\t\t\t| `length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual'}`\n\t\t\t| 'regex'\n\t\t\t| 'url'\n\t\t\t| 'uuid'\n\t\t\t| 'email'\n\t\t\t| `ip${'v4' | 'v6' | ''}`\n\t\t\t| 'date'\n\t\t\t| 'phone'}`;\n\nexport type StringProtocol = `${string}:`;\n\nexport type StringDomain = `${string}.${string}`;\n\nexport interface UrlOptions {\n\tallowedProtocols?: StringProtocol[];\n\tallowedDomains?: StringDomain[];\n}\n\nexport type UUIDVersion = 1 | 3 | 4 | 5;\n\nexport interface StringUuidOptions {\n\tversion?: UUIDVersion | `${UUIDVersion}-${UUIDVersion}` | null;\n\tnullable?: boolean;\n}\n\nfunction stringLengthComparator(comparator: Comparator, name: StringConstraintName, expected: string, length: number): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid string length', input, expected));\n\t\t}\n\t};\n}\n\nexport function stringLengthLessThan(length: number): IConstraint {\n\tconst expected = `expected.length < ${length}`;\n\treturn stringLengthComparator(lessThan, 's.string.lengthLessThan', expected, length);\n}\n\nexport function stringLengthLessThanOrEqual(length: number): IConstraint {\n\tconst expected = `expected.length <= ${length}`;\n\treturn stringLengthComparator(lessThanOrEqual, 's.string.lengthLessThanOrEqual', expected, length);\n}\n\nexport function stringLengthGreaterThan(length: number): IConstraint {\n\tconst expected = `expected.length > ${length}`;\n\treturn stringLengthComparator(greaterThan, 's.string.lengthGreaterThan', expected, length);\n}\n\nexport function stringLengthGreaterThanOrEqual(length: number): IConstraint {\n\tconst expected = `expected.length >= ${length}`;\n\treturn stringLengthComparator(greaterThanOrEqual, 's.string.lengthGreaterThanOrEqual', expected, length);\n}\n\nexport function stringLengthEqual(length: number): IConstraint {\n\tconst expected = `expected.length === ${length}`;\n\treturn stringLengthComparator(equal, 's.string.lengthEqual', expected, length);\n}\n\nexport function stringLengthNotEqual(length: number): IConstraint {\n\tconst expected = `expected.length !== ${length}`;\n\treturn stringLengthComparator(notEqual, 's.string.lengthNotEqual', expected, length);\n}\n\nexport function stringEmail(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validateEmail(input)\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.string.email', 'Invalid email address', input, 'expected to be an email address'));\n\t\t}\n\t};\n}\n\nfunction stringRegexValidator(type: StringConstraintName, expected: string, regex: RegExp): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn regex.test(input) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(type, 'Invalid string format', input, expected));\n\t\t}\n\t};\n}\n\nexport function stringUrl(options?: UrlOptions): IConstraint {\n\tconst validatorFn = createUrlValidators(options);\n\treturn {\n\t\trun(input: string) {\n\t\t\tlet url: URL;\n\t\t\ttry {\n\t\t\t\turl = new URL(input);\n\t\t\t} catch {\n\t\t\t\treturn Result.err(new ExpectedConstraintError('s.string.url', 'Invalid URL', input, 'expected to match an URL'));\n\t\t\t}\n\n\t\t\tconst validatorFnResult = validatorFn(input, url);\n\t\t\tif (validatorFnResult === null) return Result.ok(input);\n\t\t\treturn Result.err(validatorFnResult);\n\t\t}\n\t};\n}\n\nexport function stringIp(version?: 4 | 6): IConstraint {\n\tconst ipVersion = version ? (`v${version}` as const) : '';\n\tconst validatorFn = version === 4 ? isIPv4 : version === 6 ? isIPv6 : isIP;\n\n\tconst name = `s.string.ip${ipVersion}` as const;\n\tconst message = `Invalid IP${ipVersion} address`;\n\tconst expected = `expected to be an IP${ipVersion} address`;\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validatorFn(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, message, input, expected));\n\t\t}\n\t};\n}\n\nexport function stringRegex(regex: RegExp) {\n\treturn stringRegexValidator('s.string.regex', `expected ${regex}.test(expected) to be true`, regex);\n}\n\nexport function stringUuid({ version = 4, nullable = false }: StringUuidOptions = {}) {\n\tversion ??= '1-5';\n\tconst regex = new RegExp(\n\t\t`^(?:[0-9A-F]{8}-[0-9A-F]{4}-[${version}][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}${\n\t\t\tnullable ? '|00000000-0000-0000-0000-000000000000' : ''\n\t\t})$`,\n\t\t'i'\n\t);\n\tconst expected = `expected to match UUID${typeof version === 'number' ? `v${version}` : ` in range of ${version}`}`;\n\treturn stringRegexValidator('s.string.uuid', expected, regex);\n}\n\nexport function stringDate(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\tconst time = Date.parse(input);\n\n\t\t\treturn Number.isNaN(time)\n\t\t\t\t? Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError(\n\t\t\t\t\t\t\t's.string.date',\n\t\t\t\t\t\t\t'Invalid date string',\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t'expected to be a valid date string (in the ISO 8601 or ECMA-262 format)'\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Result.ok(input);\n\t\t}\n\t};\n}\n\nexport function stringPhone(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validatePhoneNumber(input)\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.string.phone', 'Invalid phone number', input, 'expected to be a phone number'));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tstringDate,\n\tstringEmail,\n\tstringIp,\n\tstringLengthEqual,\n\tstringLengthGreaterThan,\n\tstringLengthGreaterThanOrEqual,\n\tstringLengthLessThan,\n\tstringLengthLessThanOrEqual,\n\tstringLengthNotEqual,\n\tstringPhone,\n\tstringRegex,\n\tstringUrl,\n\tstringUuid,\n\tStringUuidOptions,\n\ttype UrlOptions\n} from '../constraints/StringConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class StringValidator extends BaseValidator {\n\tpublic lengthLessThan(length: number): this {\n\t\treturn this.addConstraint(stringLengthLessThan(length) as IConstraint);\n\t}\n\n\tpublic lengthLessThanOrEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthLessThanOrEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthGreaterThan(length: number): this {\n\t\treturn this.addConstraint(stringLengthGreaterThan(length) as IConstraint);\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthGreaterThanOrEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthNotEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthNotEqual(length) as IConstraint);\n\t}\n\n\tpublic get email(): this {\n\t\treturn this.addConstraint(stringEmail() as IConstraint);\n\t}\n\n\tpublic url(options?: UrlOptions): this {\n\t\treturn this.addConstraint(stringUrl(options) as IConstraint);\n\t}\n\n\tpublic uuid(options?: StringUuidOptions): this {\n\t\treturn this.addConstraint(stringUuid(options) as IConstraint);\n\t}\n\n\tpublic regex(regex: RegExp): this {\n\t\treturn this.addConstraint(stringRegex(regex) as IConstraint);\n\t}\n\n\tpublic get date() {\n\t\treturn this.addConstraint(stringDate() as IConstraint);\n\t}\n\n\tpublic get ipv4(): this {\n\t\treturn this.ip(4);\n\t}\n\n\tpublic get ipv6(): this {\n\t\treturn this.ip(6);\n\t}\n\n\tpublic ip(version?: 4 | 6): this {\n\t\treturn this.addConstraint(stringIp(version) as IConstraint);\n\t}\n\n\tpublic phone(): this {\n\t\treturn this.addConstraint(stringPhone() as IConstraint);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'string' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.string', 'Expected a string primitive', value));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class TupleValidator extends BaseValidator<[...T]> {\n\tprivate readonly validators: BaseValidator<[...T]>[] = [];\n\n\tpublic constructor(validators: BaseValidator<[...T]>[], constraints: readonly IConstraint<[...T]>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validators = validators;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validators, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result<[...T], ValidationError | CombinedPropertyError> {\n\t\tif (!Array.isArray(values)) {\n\t\t\treturn Result.err(new ValidationError('s.tuple(T)', 'Expected an array', values));\n\t\t}\n\n\t\tif (values.length !== this.validators.length) {\n\t\t\treturn Result.err(new ValidationError('s.tuple(T)', `Expected an array of length ${this.validators.length}`, values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values as [...T]);\n\t\t}\n\n\t\tconst errors: [number, BaseError][] = [];\n\t\tconst transformed: T = [] as unknown as T;\n\n\t\tfor (let i = 0; i < values.length; i++) {\n\t\t\tconst result = this.validators[i].run(values[i]);\n\t\t\tif (result.isOk()) transformed.push(result.value);\n\t\t\telse errors.push([i, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class MapValidator extends BaseValidator> {\n\tprivate readonly keyValidator: BaseValidator;\n\tprivate readonly valueValidator: BaseValidator;\n\n\tpublic constructor(keyValidator: BaseValidator, valueValidator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.keyValidator = keyValidator;\n\t\tthis.valueValidator = valueValidator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.keyValidator, this.valueValidator, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result, ValidationError | CombinedPropertyError> {\n\t\tif (!(value instanceof Map)) {\n\t\t\treturn Result.err(new ValidationError('s.map(K, V)', 'Expected a map', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value);\n\t\t}\n\n\t\tconst errors: [string, BaseError][] = [];\n\t\tconst transformed = new Map();\n\n\t\tfor (const [key, val] of value.entries()) {\n\t\t\tconst keyResult = this.keyValidator.run(key);\n\t\t\tconst valueResult = this.valueValidator.run(val);\n\t\t\tconst { length } = errors;\n\t\t\tif (keyResult.isErr()) errors.push([key, keyResult.error]);\n\t\t\tif (valueResult.isErr()) errors.push([key, valueResult.error]);\n\t\t\tif (errors.length === length) transformed.set(keyResult.value!, valueResult.value!);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { Result } from '../lib/Result';\nimport type { IConstraint, Unwrap } from '../type-exports';\nimport { BaseValidator, ValidatorError } from './imports';\n\nexport class LazyValidator, R = Unwrap> extends BaseValidator {\n\tprivate readonly validator: (value: unknown) => T;\n\n\tpublic constructor(validator: (value: unknown) => T, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result {\n\t\treturn this.validator(values).run(values) as Result;\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class UnknownEnumValueError extends BaseError {\n\tpublic readonly value: string | number;\n\tpublic readonly enumKeys: string[];\n\tpublic readonly enumMappings: Map;\n\n\tpublic constructor(value: string | number, keys: string[], enumMappings: Map) {\n\t\tsuper('Expected the value to be one of the following enum values:');\n\n\t\tthis.value = value;\n\t\tthis.enumKeys = keys;\n\t\tthis.enumMappings = enumMappings;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalue: this.value,\n\t\t\tenumKeys: this.enumKeys,\n\t\t\tenumMappings: [...this.enumMappings.entries()]\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst value = options.stylize(this.value.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[UnknownEnumValueError: ${value}]`, 'special');\n\t\t}\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst pairs = this.enumKeys\n\t\t\t.map((key) => {\n\t\t\t\tconst enumValue = this.enumMappings.get(key)!;\n\t\t\t\treturn `${options.stylize(key, 'string')} or ${options.stylize(\n\t\t\t\t\tenumValue.toString(),\n\t\t\t\t\ttypeof enumValue === 'number' ? 'number' : 'string'\n\t\t\t\t)}`;\n\t\t\t})\n\t\t\t.join(padding);\n\n\t\tconst header = `${options.stylize('UnknownEnumValueError', 'special')} > ${value}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst pairsBlock = `${padding}${pairs}`;\n\t\treturn `${header}\\n ${message}\\n${pairsBlock}`;\n\t}\n}\n","import { UnknownEnumValueError } from '../lib/errors/UnknownEnumValueError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NativeEnumValidator extends BaseValidator {\n\tpublic readonly enumShape: T;\n\tpublic readonly hasNumericElements: boolean = false;\n\tprivate readonly enumKeys: string[];\n\tprivate readonly enumMapping = new Map();\n\n\tpublic constructor(enumShape: T) {\n\t\tsuper();\n\t\tthis.enumShape = enumShape;\n\n\t\tthis.enumKeys = Object.keys(enumShape).filter((key) => {\n\t\t\treturn typeof enumShape[enumShape[key]] !== 'number';\n\t\t});\n\n\t\tfor (const key of this.enumKeys) {\n\t\t\tconst enumValue = enumShape[key] as T[keyof T];\n\n\t\t\tthis.enumMapping.set(key, enumValue);\n\t\t\tthis.enumMapping.set(enumValue, enumValue);\n\n\t\t\tif (typeof enumValue === 'number') {\n\t\t\t\tthis.hasNumericElements = true;\n\t\t\t\tthis.enumMapping.set(`${enumValue}`, enumValue);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected override handle(value: unknown): Result {\n\t\tconst typeOfValue = typeof value;\n\n\t\tif (typeOfValue === 'number') {\n\t\t\tif (!this.hasNumericElements) {\n\t\t\t\treturn Result.err(new ValidationError('s.nativeEnum(T)', 'Expected the value to be a string', value));\n\t\t\t}\n\t\t} else if (typeOfValue !== 'string') {\n\t\t\t// typeOfValue !== 'number' is implied here\n\t\t\treturn Result.err(new ValidationError('s.nativeEnum(T)', 'Expected the value to be a string or number', value));\n\t\t}\n\n\t\tconst casted = value as string | number;\n\n\t\tconst possibleEnumValue = this.enumMapping.get(casted);\n\n\t\treturn typeof possibleEnumValue === 'undefined'\n\t\t\t? Result.err(new UnknownEnumValueError(casted, this.enumKeys, this.enumMapping))\n\t\t\t: Result.ok(possibleEnumValue);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.enumShape]);\n\t}\n}\n\nexport interface NativeEnumLike {\n\t[key: string]: string | number;\n\t[key: number]: string;\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\nimport type { TypedArray } from './util/typedArray';\n\nexport type TypedArrayConstraintName = `s.typedArray(T).${'byteLength' | 'length'}${\n\t| 'LessThan'\n\t| 'LessThanOrEqual'\n\t| 'GreaterThan'\n\t| 'GreaterThanOrEqual'\n\t| 'Equal'\n\t| 'NotEqual'\n\t| 'Range'\n\t| 'RangeInclusive'\n\t| 'RangeExclusive'}`;\n\nfunction typedArrayByteLengthComparator(\n\tcomparator: Comparator,\n\tname: TypedArrayConstraintName,\n\texpected: string,\n\tlength: number\n): IConstraint {\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn comparator(input.byteLength, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Typed Array byte length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.byteLength < ${value}`;\n\treturn typedArrayByteLengthComparator(lessThan, 's.typedArray(T).byteLengthLessThan', expected, value);\n}\n\nexport function typedArrayByteLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength <= ${value}`;\n\treturn typedArrayByteLengthComparator(lessThanOrEqual, 's.typedArray(T).byteLengthLessThanOrEqual', expected, value);\n}\n\nexport function typedArrayByteLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.byteLength > ${value}`;\n\treturn typedArrayByteLengthComparator(greaterThan, 's.typedArray(T).byteLengthGreaterThan', expected, value);\n}\n\nexport function typedArrayByteLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength >= ${value}`;\n\treturn typedArrayByteLengthComparator(greaterThanOrEqual, 's.typedArray(T).byteLengthGreaterThanOrEqual', expected, value);\n}\n\nexport function typedArrayByteLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength === ${value}`;\n\treturn typedArrayByteLengthComparator(equal, 's.typedArray(T).byteLengthEqual', expected, value);\n}\n\nexport function typedArrayByteLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength !== ${value}`;\n\treturn typedArrayByteLengthComparator(notEqual, 's.typedArray(T).byteLengthNotEqual', expected, value);\n}\n\nexport function typedArrayByteLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.byteLength >= ${start} && expected.byteLength < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength >= start && input.byteLength < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).byteLengthRange', 'Invalid Typed Array byte length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthRangeInclusive(start: number, end: number) {\n\tconst expected = `expected.byteLength >= ${start} && expected.byteLength <= ${end}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength >= start && input.byteLength <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError('s.typedArray(T).byteLengthRangeInclusive', 'Invalid Typed Array byte length', input, expected)\n\t\t\t\t );\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.byteLength > ${startAfter} && expected.byteLength < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength > startAfter && input.byteLength < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError('s.typedArray(T).byteLengthRangeExclusive', 'Invalid Typed Array byte length', input, expected)\n\t\t\t\t );\n\t\t}\n\t};\n}\n\nfunction typedArrayLengthComparator(\n\tcomparator: Comparator,\n\tname: TypedArrayConstraintName,\n\texpected: string,\n\tlength: number\n): IConstraint {\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.length < ${value}`;\n\treturn typedArrayLengthComparator(lessThan, 's.typedArray(T).lengthLessThan', expected, value);\n}\n\nexport function typedArrayLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length <= ${value}`;\n\treturn typedArrayLengthComparator(lessThanOrEqual, 's.typedArray(T).lengthLessThanOrEqual', expected, value);\n}\n\nexport function typedArrayLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.length > ${value}`;\n\treturn typedArrayLengthComparator(greaterThan, 's.typedArray(T).lengthGreaterThan', expected, value);\n}\n\nexport function typedArrayLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length >= ${value}`;\n\treturn typedArrayLengthComparator(greaterThanOrEqual, 's.typedArray(T).lengthGreaterThanOrEqual', expected, value);\n}\n\nexport function typedArrayLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.length === ${value}`;\n\treturn typedArrayLengthComparator(equal, 's.typedArray(T).lengthEqual', expected, value);\n}\n\nexport function typedArrayLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.length !== ${value}`;\n\treturn typedArrayLengthComparator(notEqual, 's.typedArray(T).lengthNotEqual', expected, value);\n}\n\nexport function typedArrayLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length >= start && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRange', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthRangeInclusive(start: number, end: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length <= ${end}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length >= start && input.length <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRangeInclusive', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length > startAfter && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRangeExclusive', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n","const vowels = ['a', 'e', 'i', 'o', 'u'];\n\nexport const aOrAn = (word: string) => {\n\treturn `${vowels.includes(word[0].toLowerCase()) ? 'an' : 'a'} ${word}`;\n};\n","export type TypedArray =\n\t| Int8Array\n\t| Uint8Array\n\t| Uint8ClampedArray\n\t| Int16Array\n\t| Uint16Array\n\t| Int32Array\n\t| Uint32Array\n\t| Float32Array\n\t| Float64Array\n\t| BigInt64Array\n\t| BigUint64Array;\n\nexport const TypedArrays = {\n\tInt8Array: (x: unknown): x is Int8Array => x instanceof Int8Array,\n\tUint8Array: (x: unknown): x is Uint8Array => x instanceof Uint8Array,\n\tUint8ClampedArray: (x: unknown): x is Uint8ClampedArray => x instanceof Uint8ClampedArray,\n\tInt16Array: (x: unknown): x is Int16Array => x instanceof Int16Array,\n\tUint16Array: (x: unknown): x is Uint16Array => x instanceof Uint16Array,\n\tInt32Array: (x: unknown): x is Int32Array => x instanceof Int32Array,\n\tUint32Array: (x: unknown): x is Uint32Array => x instanceof Uint32Array,\n\tFloat32Array: (x: unknown): x is Float32Array => x instanceof Float32Array,\n\tFloat64Array: (x: unknown): x is Float64Array => x instanceof Float64Array,\n\tBigInt64Array: (x: unknown): x is BigInt64Array => x instanceof BigInt64Array,\n\tBigUint64Array: (x: unknown): x is BigUint64Array => x instanceof BigUint64Array,\n\tTypedArray: (x: unknown): x is TypedArray => ArrayBuffer.isView(x) && !(x instanceof DataView)\n} as const;\n\nexport type TypedArrayName = keyof typeof TypedArrays;\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\ttypedArrayByteLengthEqual,\n\ttypedArrayByteLengthGreaterThan,\n\ttypedArrayByteLengthGreaterThanOrEqual,\n\ttypedArrayByteLengthLessThan,\n\ttypedArrayByteLengthLessThanOrEqual,\n\ttypedArrayByteLengthNotEqual,\n\ttypedArrayByteLengthRange,\n\ttypedArrayByteLengthRangeExclusive,\n\ttypedArrayByteLengthRangeInclusive,\n\ttypedArrayLengthEqual,\n\ttypedArrayLengthGreaterThan,\n\ttypedArrayLengthGreaterThanOrEqual,\n\ttypedArrayLengthLessThan,\n\ttypedArrayLengthLessThanOrEqual,\n\ttypedArrayLengthNotEqual,\n\ttypedArrayLengthRange,\n\ttypedArrayLengthRangeExclusive,\n\ttypedArrayLengthRangeInclusive\n} from '../constraints/TypedArrayLengthConstraints';\nimport { aOrAn } from '../constraints/util/common/vowels';\nimport { TypedArray, TypedArrayName, TypedArrays } from '../constraints/util/typedArray';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class TypedArrayValidator extends BaseValidator {\n\tprivate readonly type: TypedArrayName;\n\n\tpublic constructor(type: TypedArrayName, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.type = type;\n\t}\n\n\tpublic byteLengthLessThan(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthLessThan(length));\n\t}\n\n\tpublic byteLengthLessThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthLessThanOrEqual(length));\n\t}\n\n\tpublic byteLengthGreaterThan(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthGreaterThan(length));\n\t}\n\n\tpublic byteLengthGreaterThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthGreaterThanOrEqual(length));\n\t}\n\n\tpublic byteLengthEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthEqual(length));\n\t}\n\n\tpublic byteLengthNotEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthNotEqual(length));\n\t}\n\n\tpublic byteLengthRange(start: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRange(start, endBefore));\n\t}\n\n\tpublic byteLengthRangeInclusive(startAt: number, endAt: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRangeInclusive(startAt, endAt) as IConstraint);\n\t}\n\n\tpublic byteLengthRangeExclusive(startAfter: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRangeExclusive(startAfter, endBefore));\n\t}\n\n\tpublic lengthLessThan(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthLessThan(length));\n\t}\n\n\tpublic lengthLessThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthLessThanOrEqual(length));\n\t}\n\n\tpublic lengthGreaterThan(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthGreaterThan(length));\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthGreaterThanOrEqual(length));\n\t}\n\n\tpublic lengthEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthEqual(length));\n\t}\n\n\tpublic lengthNotEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthNotEqual(length));\n\t}\n\n\tpublic lengthRange(start: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayLengthRange(start, endBefore));\n\t}\n\n\tpublic lengthRangeInclusive(startAt: number, endAt: number) {\n\t\treturn this.addConstraint(typedArrayLengthRangeInclusive(startAt, endAt));\n\t}\n\n\tpublic lengthRangeExclusive(startAfter: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayLengthRangeExclusive(startAfter, endBefore));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.type, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn TypedArrays[this.type](value)\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.typedArray', `Expected ${aOrAn(this.type)}`, value));\n\t}\n}\n","import type { TypedArray, TypedArrayName } from '../constraints/util/typedArray';\nimport type { Unwrap, UnwrapTuple } from '../lib/util-types';\nimport {\n\tArrayValidator,\n\tBaseValidator,\n\tBigIntValidator,\n\tBooleanValidator,\n\tDateValidator,\n\tInstanceValidator,\n\tLiteralValidator,\n\tMapValidator,\n\tNeverValidator,\n\tNullishValidator,\n\tNumberValidator,\n\tObjectValidator,\n\tPassthroughValidator,\n\tRecordValidator,\n\tSetValidator,\n\tStringValidator,\n\tTupleValidator,\n\tUnionValidator\n} from '../validators/imports';\nimport { LazyValidator } from '../validators/LazyValidator';\nimport { NativeEnumLike, NativeEnumValidator } from '../validators/NativeEnumValidator';\nimport { TypedArrayValidator } from '../validators/TypedArrayValidator';\nimport type { Constructor, MappedObjectValidator } from './util-types';\n\nexport class Shapes {\n\tpublic get string() {\n\t\treturn new StringValidator();\n\t}\n\n\tpublic get number() {\n\t\treturn new NumberValidator();\n\t}\n\n\tpublic get bigint() {\n\t\treturn new BigIntValidator();\n\t}\n\n\tpublic get boolean() {\n\t\treturn new BooleanValidator();\n\t}\n\n\tpublic get date() {\n\t\treturn new DateValidator();\n\t}\n\n\tpublic object(shape: MappedObjectValidator) {\n\t\treturn new ObjectValidator(shape);\n\t}\n\n\tpublic get undefined() {\n\t\treturn this.literal(undefined);\n\t}\n\n\tpublic get null() {\n\t\treturn this.literal(null);\n\t}\n\n\tpublic get nullish() {\n\t\treturn new NullishValidator();\n\t}\n\n\tpublic get any() {\n\t\treturn new PassthroughValidator();\n\t}\n\n\tpublic get unknown() {\n\t\treturn new PassthroughValidator();\n\t}\n\n\tpublic get never() {\n\t\treturn new NeverValidator();\n\t}\n\n\tpublic enum(...values: readonly T[]) {\n\t\treturn this.union(...values.map((value) => this.literal(value)));\n\t}\n\n\tpublic nativeEnum(enumShape: T): NativeEnumValidator {\n\t\treturn new NativeEnumValidator(enumShape);\n\t}\n\n\tpublic literal(value: T): BaseValidator {\n\t\tif (value instanceof Date) return this.date.equal(value) as unknown as BaseValidator;\n\t\treturn new LiteralValidator(value);\n\t}\n\n\tpublic instance(expected: Constructor): InstanceValidator {\n\t\treturn new InstanceValidator(expected);\n\t}\n\n\tpublic union[]]>(...validators: [...T]): UnionValidator> {\n\t\treturn new UnionValidator(validators);\n\t}\n\n\tpublic array(validator: BaseValidator): ArrayValidator;\n\tpublic array(validator: BaseValidator): ArrayValidator;\n\tpublic array(validator: BaseValidator) {\n\t\treturn new ArrayValidator(validator);\n\t}\n\n\tpublic typedArray(type: TypedArrayName = 'TypedArray') {\n\t\treturn new TypedArrayValidator(type);\n\t}\n\n\tpublic get int8Array() {\n\t\treturn this.typedArray('Int8Array');\n\t}\n\n\tpublic get uint8Array() {\n\t\treturn this.typedArray('Uint8Array');\n\t}\n\n\tpublic get uint8ClampedArray() {\n\t\treturn this.typedArray('Uint8ClampedArray');\n\t}\n\n\tpublic get int16Array() {\n\t\treturn this.typedArray('Int16Array');\n\t}\n\n\tpublic get uint16Array() {\n\t\treturn this.typedArray('Uint16Array');\n\t}\n\n\tpublic get int32Array() {\n\t\treturn this.typedArray('Int32Array');\n\t}\n\n\tpublic get uint32Array() {\n\t\treturn this.typedArray('Uint32Array');\n\t}\n\n\tpublic get float32Array() {\n\t\treturn this.typedArray('Float32Array');\n\t}\n\n\tpublic get float64Array() {\n\t\treturn this.typedArray('Float64Array');\n\t}\n\n\tpublic get bigInt64Array() {\n\t\treturn this.typedArray('BigInt64Array');\n\t}\n\n\tpublic get bigUint64Array() {\n\t\treturn this.typedArray('BigUint64Array');\n\t}\n\n\tpublic tuple[]]>(validators: [...T]): TupleValidator> {\n\t\treturn new TupleValidator(validators);\n\t}\n\n\tpublic set(validator: BaseValidator) {\n\t\treturn new SetValidator(validator);\n\t}\n\n\tpublic record(validator: BaseValidator) {\n\t\treturn new RecordValidator(validator);\n\t}\n\n\tpublic map(keyValidator: BaseValidator, valueValidator: BaseValidator) {\n\t\treturn new MapValidator(keyValidator, valueValidator);\n\t}\n\n\tpublic lazy>(validator: (value: unknown) => T) {\n\t\treturn new LazyValidator(validator);\n\t}\n}\n","import { Shapes } from './lib/Shapes';\n\nexport const s = new Shapes();\n\nexport * from './lib/configs';\nexport * from './lib/errors/BaseError';\nexport * from './lib/errors/CombinedError';\nexport * from './lib/errors/CombinedPropertyError';\nexport * from './lib/errors/ExpectedConstraintError';\nexport * from './lib/errors/ExpectedValidationError';\nexport * from './lib/errors/MissingPropertyError';\nexport * from './lib/errors/MultiplePossibilitiesConstraintError';\nexport * from './lib/errors/UnknownEnumValueError';\nexport * from './lib/errors/UnknownPropertyError';\nexport * from './lib/errors/ValidationError';\nexport * from './lib/Result';\nexport * from './type-exports';\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/dist/index.mjs b/node_modules/@sapphire/shapeshift/dist/index.mjs new file mode 100644 index 0000000..941922e --- /dev/null +++ b/node_modules/@sapphire/shapeshift/dist/index.mjs @@ -0,0 +1,2215 @@ +import get from 'lodash/get.js'; +import { inspect } from 'node:util'; +import fastDeepEqual from 'fast-deep-equal/es6/index.js'; +import uniqWith from 'lodash/uniqWith.js'; + +var __defProp = Object.defineProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + +// src/lib/configs.ts +var validationEnabled = true; +function setGlobalValidationEnabled(enabled) { + validationEnabled = enabled; +} +__name(setGlobalValidationEnabled, "setGlobalValidationEnabled"); +function getGlobalValidationEnabled() { + return validationEnabled; +} +__name(getGlobalValidationEnabled, "getGlobalValidationEnabled"); + +// src/lib/Result.ts +var Result = class { + constructor(success, value, error) { + this.success = success; + if (success) { + this.value = value; + } else { + this.error = error; + } + } + isOk() { + return this.success; + } + isErr() { + return !this.success; + } + unwrap() { + if (this.isOk()) + return this.value; + throw this.error; + } + static ok(value) { + return new Result(true, value); + } + static err(error) { + return new Result(false, void 0, error); + } +}; +__name(Result, "Result"); + +// src/validators/util/getValue.ts +function getValue(valueOrFn) { + return typeof valueOrFn === "function" ? valueOrFn() : valueOrFn; +} +__name(getValue, "getValue"); + +// src/lib/errors/BaseError.ts +var customInspectSymbol = Symbol.for("nodejs.util.inspect.custom"); +var customInspectSymbolStackLess = Symbol.for("nodejs.util.inspect.custom.stack-less"); +var BaseError = class extends Error { + [customInspectSymbol](depth, options) { + return `${this[customInspectSymbolStackLess](depth, options)} +${this.stack.slice(this.stack.indexOf("\n"))}`; + } +}; +__name(BaseError, "BaseError"); + +// src/lib/errors/BaseConstraintError.ts +var BaseConstraintError = class extends BaseError { + constructor(constraint, message, given) { + super(message); + this.constraint = constraint; + this.given = given; + } +}; +__name(BaseConstraintError, "BaseConstraintError"); + +// src/lib/errors/ExpectedConstraintError.ts +var ExpectedConstraintError = class extends BaseConstraintError { + constructor(constraint, message, given, expected) { + super(constraint, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + constraint: this.constraint, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const constraint = options.stylize(this.constraint, "string"); + if (depth < 0) { + return options.stylize(`[ExpectedConstraintError: ${constraint}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = inspect(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ExpectedConstraintError", "special")} > ${constraint}`; + const message = options.stylize(this.message, "regexp"); + const expectedBlock = ` + ${options.stylize("Expected: ", "string")}${options.stylize(this.expected, "boolean")}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } +}; +__name(ExpectedConstraintError, "ExpectedConstraintError"); + +// src/constraints/ObjectConstrains.ts +function whenConstraint(key, options, validator) { + return { + run(input, parent) { + if (!parent) { + return Result.err(new ExpectedConstraintError("s.object(T.when)", "Validator has no parent", parent, "Validator to have a parent")); + } + const isKeyArray = Array.isArray(key); + const value = isKeyArray ? key.map((k) => get(parent, k)) : get(parent, key); + const predicate = resolveBooleanIs(options, value, isKeyArray) ? options.then : options.otherwise; + if (predicate) { + return predicate(validator).run(input); + } + return Result.ok(input); + } + }; +} +__name(whenConstraint, "whenConstraint"); +function resolveBooleanIs(options, value, isKeyArray) { + if (options.is === void 0) { + return isKeyArray ? !value.some((val) => !val) : Boolean(value); + } + if (typeof options.is === "function") { + return options.is(value); + } + return value === options.is; +} +__name(resolveBooleanIs, "resolveBooleanIs"); + +// src/validators/BaseValidator.ts +var BaseValidator = class { + constructor(constraints = []) { + this.constraints = []; + this.isValidationEnabled = null; + this.constraints = constraints; + } + setParent(parent) { + this.parent = parent; + return this; + } + get optional() { + return new UnionValidator([new LiteralValidator(void 0), this.clone()]); + } + get nullable() { + return new UnionValidator([new LiteralValidator(null), this.clone()]); + } + get nullish() { + return new UnionValidator([new NullishValidator(), this.clone()]); + } + get array() { + return new ArrayValidator(this.clone()); + } + get set() { + return new SetValidator(this.clone()); + } + or(...predicates) { + return new UnionValidator([this.clone(), ...predicates]); + } + transform(cb) { + return this.addConstraint({ run: (input) => Result.ok(cb(input)) }); + } + reshape(cb) { + return this.addConstraint({ run: cb }); + } + default(value) { + return new DefaultValidator(this.clone(), value); + } + when(key, options) { + return this.addConstraint(whenConstraint(key, options, this)); + } + run(value) { + let result = this.handle(value); + if (result.isErr()) + return result; + for (const constraint of this.constraints) { + result = constraint.run(result.value, this.parent); + if (result.isErr()) + break; + } + return result; + } + parse(value) { + if (!this.shouldRunConstraints) { + return this.handle(value).unwrap(); + } + return this.constraints.reduce((v, constraint) => constraint.run(v).unwrap(), this.handle(value).unwrap()); + } + is(value) { + return this.run(value).isOk(); + } + setValidationEnabled(isValidationEnabled) { + const clone = this.clone(); + clone.isValidationEnabled = isValidationEnabled; + return clone; + } + getValidationEnabled() { + return getValue(this.isValidationEnabled); + } + get shouldRunConstraints() { + return getValue(this.isValidationEnabled) ?? getGlobalValidationEnabled(); + } + clone() { + const clone = Reflect.construct(this.constructor, [this.constraints]); + clone.isValidationEnabled = this.isValidationEnabled; + return clone; + } + addConstraint(constraint) { + const clone = this.clone(); + clone.constraints = clone.constraints.concat(constraint); + return clone; + } +}; +__name(BaseValidator, "BaseValidator"); +function isUnique(input) { + if (input.length < 2) + return true; + const uniqueArray2 = uniqWith(input, fastDeepEqual); + return uniqueArray2.length === input.length; +} +__name(isUnique, "isUnique"); + +// src/constraints/util/operators.ts +function lessThan(a, b) { + return a < b; +} +__name(lessThan, "lessThan"); +function lessThanOrEqual(a, b) { + return a <= b; +} +__name(lessThanOrEqual, "lessThanOrEqual"); +function greaterThan(a, b) { + return a > b; +} +__name(greaterThan, "greaterThan"); +function greaterThanOrEqual(a, b) { + return a >= b; +} +__name(greaterThanOrEqual, "greaterThanOrEqual"); +function equal(a, b) { + return a === b; +} +__name(equal, "equal"); +function notEqual(a, b) { + return a !== b; +} +__name(notEqual, "notEqual"); + +// src/constraints/ArrayConstraints.ts +function arrayLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Array length", input, expected)); + } + }; +} +__name(arrayLengthComparator, "arrayLengthComparator"); +function arrayLengthLessThan(value) { + const expected = `expected.length < ${value}`; + return arrayLengthComparator(lessThan, "s.array(T).lengthLessThan", expected, value); +} +__name(arrayLengthLessThan, "arrayLengthLessThan"); +function arrayLengthLessThanOrEqual(value) { + const expected = `expected.length <= ${value}`; + return arrayLengthComparator(lessThanOrEqual, "s.array(T).lengthLessThanOrEqual", expected, value); +} +__name(arrayLengthLessThanOrEqual, "arrayLengthLessThanOrEqual"); +function arrayLengthGreaterThan(value) { + const expected = `expected.length > ${value}`; + return arrayLengthComparator(greaterThan, "s.array(T).lengthGreaterThan", expected, value); +} +__name(arrayLengthGreaterThan, "arrayLengthGreaterThan"); +function arrayLengthGreaterThanOrEqual(value) { + const expected = `expected.length >= ${value}`; + return arrayLengthComparator(greaterThanOrEqual, "s.array(T).lengthGreaterThanOrEqual", expected, value); +} +__name(arrayLengthGreaterThanOrEqual, "arrayLengthGreaterThanOrEqual"); +function arrayLengthEqual(value) { + const expected = `expected.length === ${value}`; + return arrayLengthComparator(equal, "s.array(T).lengthEqual", expected, value); +} +__name(arrayLengthEqual, "arrayLengthEqual"); +function arrayLengthNotEqual(value) { + const expected = `expected.length !== ${value}`; + return arrayLengthComparator(notEqual, "s.array(T).lengthNotEqual", expected, value); +} +__name(arrayLengthNotEqual, "arrayLengthNotEqual"); +function arrayLengthRange(start, endBefore) { + const expected = `expected.length >= ${start} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length >= start && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRange", "Invalid Array length", input, expected)); + } + }; +} +__name(arrayLengthRange, "arrayLengthRange"); +function arrayLengthRangeInclusive(start, end) { + const expected = `expected.length >= ${start} && expected.length <= ${end}`; + return { + run(input) { + return input.length >= start && input.length <= end ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRangeInclusive", "Invalid Array length", input, expected)); + } + }; +} +__name(arrayLengthRangeInclusive, "arrayLengthRangeInclusive"); +function arrayLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length > startAfter && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).lengthRangeExclusive", "Invalid Array length", input, expected)); + } + }; +} +__name(arrayLengthRangeExclusive, "arrayLengthRangeExclusive"); +var uniqueArray = { + run(input) { + return isUnique(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.array(T).unique", "Array values are not unique", input, "Expected all values to be unique")); + } +}; + +// src/lib/errors/CombinedPropertyError.ts +var CombinedPropertyError = class extends BaseError { + constructor(errors) { + super("Received one or more errors"); + this.errors = errors; + } + [customInspectSymbolStackLess](depth, options) { + if (depth < 0) { + return options.stylize("[CombinedPropertyError]", "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const header = `${options.stylize("CombinedPropertyError", "special")} (${options.stylize(this.errors.length.toString(), "number")})`; + const message = options.stylize(this.message, "regexp"); + const errors = this.errors.map(([key, error]) => { + const property = CombinedPropertyError.formatProperty(key, options); + const body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\n/g, padding); + return ` input${property}${padding}${body}`; + }).join("\n\n"); + return `${header} + ${message} + +${errors}`; + } + static formatProperty(key, options) { + if (typeof key === "string") + return options.stylize(`.${key}`, "symbol"); + if (typeof key === "number") + return `[${options.stylize(key.toString(), "number")}]`; + return `[${options.stylize("Symbol", "symbol")}(${key.description})]`; + } +}; +__name(CombinedPropertyError, "CombinedPropertyError"); +var ValidationError = class extends BaseError { + constructor(validator, message, given) { + super(message); + this.validator = validator; + this.given = given; + } + toJSON() { + return { + name: this.name, + validator: this.validator, + given: this.given + }; + } + [customInspectSymbolStackLess](depth, options) { + const validator = options.stylize(this.validator, "string"); + if (depth < 0) { + return options.stylize(`[ValidationError: ${validator}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = inspect(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ValidationError", "special")} > ${validator}`; + const message = options.stylize(this.message, "regexp"); + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${givenBlock}`; + } +}; +__name(ValidationError, "ValidationError"); + +// src/validators/ArrayValidator.ts +var ArrayValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + lengthLessThan(length) { + return this.addConstraint(arrayLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(arrayLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(arrayLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(arrayLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(arrayLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(arrayLengthNotEqual(length)); + } + lengthRange(start, endBefore) { + return this.addConstraint(arrayLengthRange(start, endBefore)); + } + lengthRangeInclusive(startAt, endAt) { + return this.addConstraint(arrayLengthRangeInclusive(startAt, endAt)); + } + lengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(arrayLengthRangeExclusive(startAfter, endBefore)); + } + get unique() { + return this.addConstraint(uniqueArray); + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + if (!Array.isArray(values)) { + return Result.err(new ValidationError("s.array(T)", "Expected an array", values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = []; + for (let i = 0; i < values.length; i++) { + const result = this.validator.run(values[i]); + if (result.isOk()) + transformed.push(result.value); + else + errors.push([i, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } +}; +__name(ArrayValidator, "ArrayValidator"); + +// src/constraints/BigIntConstraints.ts +function bigintComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input, number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid bigint value", input, expected)); + } + }; +} +__name(bigintComparator, "bigintComparator"); +function bigintLessThan(value) { + const expected = `expected < ${value}n`; + return bigintComparator(lessThan, "s.bigint.lessThan", expected, value); +} +__name(bigintLessThan, "bigintLessThan"); +function bigintLessThanOrEqual(value) { + const expected = `expected <= ${value}n`; + return bigintComparator(lessThanOrEqual, "s.bigint.lessThanOrEqual", expected, value); +} +__name(bigintLessThanOrEqual, "bigintLessThanOrEqual"); +function bigintGreaterThan(value) { + const expected = `expected > ${value}n`; + return bigintComparator(greaterThan, "s.bigint.greaterThan", expected, value); +} +__name(bigintGreaterThan, "bigintGreaterThan"); +function bigintGreaterThanOrEqual(value) { + const expected = `expected >= ${value}n`; + return bigintComparator(greaterThanOrEqual, "s.bigint.greaterThanOrEqual", expected, value); +} +__name(bigintGreaterThanOrEqual, "bigintGreaterThanOrEqual"); +function bigintEqual(value) { + const expected = `expected === ${value}n`; + return bigintComparator(equal, "s.bigint.equal", expected, value); +} +__name(bigintEqual, "bigintEqual"); +function bigintNotEqual(value) { + const expected = `expected !== ${value}n`; + return bigintComparator(notEqual, "s.bigint.notEqual", expected, value); +} +__name(bigintNotEqual, "bigintNotEqual"); +function bigintDivisibleBy(divider) { + const expected = `expected % ${divider}n === 0n`; + return { + run(input) { + return input % divider === 0n ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.bigint.divisibleBy", "BigInt is not divisible", input, expected)); + } + }; +} +__name(bigintDivisibleBy, "bigintDivisibleBy"); + +// src/validators/BigIntValidator.ts +var BigIntValidator = class extends BaseValidator { + lessThan(number) { + return this.addConstraint(bigintLessThan(number)); + } + lessThanOrEqual(number) { + return this.addConstraint(bigintLessThanOrEqual(number)); + } + greaterThan(number) { + return this.addConstraint(bigintGreaterThan(number)); + } + greaterThanOrEqual(number) { + return this.addConstraint(bigintGreaterThanOrEqual(number)); + } + equal(number) { + return this.addConstraint(bigintEqual(number)); + } + notEqual(number) { + return this.addConstraint(bigintNotEqual(number)); + } + get positive() { + return this.greaterThanOrEqual(0n); + } + get negative() { + return this.lessThan(0n); + } + divisibleBy(number) { + return this.addConstraint(bigintDivisibleBy(number)); + } + get abs() { + return this.transform((value) => value < 0 ? -value : value); + } + intN(bits) { + return this.transform((value) => BigInt.asIntN(bits, value)); + } + uintN(bits) { + return this.transform((value) => BigInt.asUintN(bits, value)); + } + handle(value) { + return typeof value === "bigint" ? Result.ok(value) : Result.err(new ValidationError("s.bigint", "Expected a bigint primitive", value)); + } +}; +__name(BigIntValidator, "BigIntValidator"); + +// src/constraints/BooleanConstraints.ts +var booleanTrue = { + run(input) { + return input ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.boolean.true", "Invalid boolean value", input, "true")); + } +}; +var booleanFalse = { + run(input) { + return input ? Result.err(new ExpectedConstraintError("s.boolean.false", "Invalid boolean value", input, "false")) : Result.ok(input); + } +}; + +// src/validators/BooleanValidator.ts +var BooleanValidator = class extends BaseValidator { + get true() { + return this.addConstraint(booleanTrue); + } + get false() { + return this.addConstraint(booleanFalse); + } + equal(value) { + return value ? this.true : this.false; + } + notEqual(value) { + return value ? this.false : this.true; + } + handle(value) { + return typeof value === "boolean" ? Result.ok(value) : Result.err(new ValidationError("s.boolean", "Expected a boolean primitive", value)); + } +}; +__name(BooleanValidator, "BooleanValidator"); + +// src/constraints/DateConstraints.ts +function dateComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input.getTime(), number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Date value", input, expected)); + } + }; +} +__name(dateComparator, "dateComparator"); +function dateLessThan(value) { + const expected = `expected < ${value.toISOString()}`; + return dateComparator(lessThan, "s.date.lessThan", expected, value.getTime()); +} +__name(dateLessThan, "dateLessThan"); +function dateLessThanOrEqual(value) { + const expected = `expected <= ${value.toISOString()}`; + return dateComparator(lessThanOrEqual, "s.date.lessThanOrEqual", expected, value.getTime()); +} +__name(dateLessThanOrEqual, "dateLessThanOrEqual"); +function dateGreaterThan(value) { + const expected = `expected > ${value.toISOString()}`; + return dateComparator(greaterThan, "s.date.greaterThan", expected, value.getTime()); +} +__name(dateGreaterThan, "dateGreaterThan"); +function dateGreaterThanOrEqual(value) { + const expected = `expected >= ${value.toISOString()}`; + return dateComparator(greaterThanOrEqual, "s.date.greaterThanOrEqual", expected, value.getTime()); +} +__name(dateGreaterThanOrEqual, "dateGreaterThanOrEqual"); +function dateEqual(value) { + const expected = `expected === ${value.toISOString()}`; + return dateComparator(equal, "s.date.equal", expected, value.getTime()); +} +__name(dateEqual, "dateEqual"); +function dateNotEqual(value) { + const expected = `expected !== ${value.toISOString()}`; + return dateComparator(notEqual, "s.date.notEqual", expected, value.getTime()); +} +__name(dateNotEqual, "dateNotEqual"); +var dateInvalid = { + run(input) { + return Number.isNaN(input.getTime()) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.date.invalid", "Invalid Date value", input, "expected === NaN")); + } +}; +var dateValid = { + run(input) { + return Number.isNaN(input.getTime()) ? Result.err(new ExpectedConstraintError("s.date.valid", "Invalid Date value", input, "expected !== NaN")) : Result.ok(input); + } +}; + +// src/validators/DateValidator.ts +var DateValidator = class extends BaseValidator { + lessThan(date) { + return this.addConstraint(dateLessThan(new Date(date))); + } + lessThanOrEqual(date) { + return this.addConstraint(dateLessThanOrEqual(new Date(date))); + } + greaterThan(date) { + return this.addConstraint(dateGreaterThan(new Date(date))); + } + greaterThanOrEqual(date) { + return this.addConstraint(dateGreaterThanOrEqual(new Date(date))); + } + equal(date) { + const resolved = new Date(date); + return Number.isNaN(resolved.getTime()) ? this.invalid : this.addConstraint(dateEqual(resolved)); + } + notEqual(date) { + const resolved = new Date(date); + return Number.isNaN(resolved.getTime()) ? this.valid : this.addConstraint(dateNotEqual(resolved)); + } + get valid() { + return this.addConstraint(dateValid); + } + get invalid() { + return this.addConstraint(dateInvalid); + } + handle(value) { + return value instanceof Date ? Result.ok(value) : Result.err(new ValidationError("s.date", "Expected a Date", value)); + } +}; +__name(DateValidator, "DateValidator"); +var ExpectedValidationError = class extends ValidationError { + constructor(validator, message, given, expected) { + super(validator, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + validator: this.validator, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const validator = options.stylize(this.validator, "string"); + if (depth < 0) { + return options.stylize(`[ExpectedValidationError: ${validator}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const expected = inspect(this.expected, newOptions).replace(/\n/g, padding); + const given = inspect(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("ExpectedValidationError", "special")} > ${validator}`; + const message = options.stylize(this.message, "regexp"); + const expectedBlock = ` + ${options.stylize("Expected:", "string")}${padding}${expected}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } +}; +__name(ExpectedValidationError, "ExpectedValidationError"); + +// src/validators/InstanceValidator.ts +var InstanceValidator = class extends BaseValidator { + constructor(expected, constraints = []) { + super(constraints); + this.expected = expected; + } + handle(value) { + return value instanceof this.expected ? Result.ok(value) : Result.err(new ExpectedValidationError("s.instance(V)", "Expected", value, this.expected)); + } + clone() { + return Reflect.construct(this.constructor, [this.expected, this.constraints]); + } +}; +__name(InstanceValidator, "InstanceValidator"); + +// src/validators/LiteralValidator.ts +var LiteralValidator = class extends BaseValidator { + constructor(literal, constraints = []) { + super(constraints); + this.expected = literal; + } + handle(value) { + return Object.is(value, this.expected) ? Result.ok(value) : Result.err(new ExpectedValidationError("s.literal(V)", "Expected values to be equals", value, this.expected)); + } + clone() { + return Reflect.construct(this.constructor, [this.expected, this.constraints]); + } +}; +__name(LiteralValidator, "LiteralValidator"); + +// src/validators/NeverValidator.ts +var NeverValidator = class extends BaseValidator { + handle(value) { + return Result.err(new ValidationError("s.never", "Expected a value to not be passed", value)); + } +}; +__name(NeverValidator, "NeverValidator"); + +// src/validators/NullishValidator.ts +var NullishValidator = class extends BaseValidator { + handle(value) { + return value === void 0 || value === null ? Result.ok(value) : Result.err(new ValidationError("s.nullish", "Expected undefined or null", value)); + } +}; +__name(NullishValidator, "NullishValidator"); + +// src/constraints/NumberConstraints.ts +function numberComparator(comparator, name, expected, number) { + return { + run(input) { + return comparator(input, number) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid number value", input, expected)); + } + }; +} +__name(numberComparator, "numberComparator"); +function numberLessThan(value) { + const expected = `expected < ${value}`; + return numberComparator(lessThan, "s.number.lessThan", expected, value); +} +__name(numberLessThan, "numberLessThan"); +function numberLessThanOrEqual(value) { + const expected = `expected <= ${value}`; + return numberComparator(lessThanOrEqual, "s.number.lessThanOrEqual", expected, value); +} +__name(numberLessThanOrEqual, "numberLessThanOrEqual"); +function numberGreaterThan(value) { + const expected = `expected > ${value}`; + return numberComparator(greaterThan, "s.number.greaterThan", expected, value); +} +__name(numberGreaterThan, "numberGreaterThan"); +function numberGreaterThanOrEqual(value) { + const expected = `expected >= ${value}`; + return numberComparator(greaterThanOrEqual, "s.number.greaterThanOrEqual", expected, value); +} +__name(numberGreaterThanOrEqual, "numberGreaterThanOrEqual"); +function numberEqual(value) { + const expected = `expected === ${value}`; + return numberComparator(equal, "s.number.equal", expected, value); +} +__name(numberEqual, "numberEqual"); +function numberNotEqual(value) { + const expected = `expected !== ${value}`; + return numberComparator(notEqual, "s.number.notEqual", expected, value); +} +__name(numberNotEqual, "numberNotEqual"); +var numberInt = { + run(input) { + return Number.isInteger(input) ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.number.int", "Given value is not an integer", input, "Number.isInteger(expected) to be true") + ); + } +}; +var numberSafeInt = { + run(input) { + return Number.isSafeInteger(input) ? Result.ok(input) : Result.err( + new ExpectedConstraintError( + "s.number.safeInt", + "Given value is not a safe integer", + input, + "Number.isSafeInteger(expected) to be true" + ) + ); + } +}; +var numberFinite = { + run(input) { + return Number.isFinite(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.finite", "Given value is not finite", input, "Number.isFinite(expected) to be true")); + } +}; +var numberNaN = { + run(input) { + return Number.isNaN(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.equal(NaN)", "Invalid number value", input, "expected === NaN")); + } +}; +var numberNotNaN = { + run(input) { + return Number.isNaN(input) ? Result.err(new ExpectedConstraintError("s.number.notEqual(NaN)", "Invalid number value", input, "expected !== NaN")) : Result.ok(input); + } +}; +function numberDivisibleBy(divider) { + const expected = `expected % ${divider} === 0`; + return { + run(input) { + return input % divider === 0 ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.number.divisibleBy", "Number is not divisible", input, expected)); + } + }; +} +__name(numberDivisibleBy, "numberDivisibleBy"); + +// src/validators/NumberValidator.ts +var NumberValidator = class extends BaseValidator { + lessThan(number) { + return this.addConstraint(numberLessThan(number)); + } + lessThanOrEqual(number) { + return this.addConstraint(numberLessThanOrEqual(number)); + } + greaterThan(number) { + return this.addConstraint(numberGreaterThan(number)); + } + greaterThanOrEqual(number) { + return this.addConstraint(numberGreaterThanOrEqual(number)); + } + equal(number) { + return Number.isNaN(number) ? this.addConstraint(numberNaN) : this.addConstraint(numberEqual(number)); + } + notEqual(number) { + return Number.isNaN(number) ? this.addConstraint(numberNotNaN) : this.addConstraint(numberNotEqual(number)); + } + get int() { + return this.addConstraint(numberInt); + } + get safeInt() { + return this.addConstraint(numberSafeInt); + } + get finite() { + return this.addConstraint(numberFinite); + } + get positive() { + return this.greaterThanOrEqual(0); + } + get negative() { + return this.lessThan(0); + } + divisibleBy(divider) { + return this.addConstraint(numberDivisibleBy(divider)); + } + get abs() { + return this.transform(Math.abs); + } + get sign() { + return this.transform(Math.sign); + } + get trunc() { + return this.transform(Math.trunc); + } + get floor() { + return this.transform(Math.floor); + } + get fround() { + return this.transform(Math.fround); + } + get round() { + return this.transform(Math.round); + } + get ceil() { + return this.transform(Math.ceil); + } + handle(value) { + return typeof value === "number" ? Result.ok(value) : Result.err(new ValidationError("s.number", "Expected a number primitive", value)); + } +}; +__name(NumberValidator, "NumberValidator"); + +// src/lib/errors/MissingPropertyError.ts +var MissingPropertyError = class extends BaseError { + constructor(property) { + super("A required property is missing"); + this.property = property; + } + toJSON() { + return { + name: this.name, + property: this.property + }; + } + [customInspectSymbolStackLess](depth, options) { + const property = options.stylize(this.property.toString(), "string"); + if (depth < 0) { + return options.stylize(`[MissingPropertyError: ${property}]`, "special"); + } + const header = `${options.stylize("MissingPropertyError", "special")} > ${property}`; + const message = options.stylize(this.message, "regexp"); + return `${header} + ${message}`; + } +}; +__name(MissingPropertyError, "MissingPropertyError"); +var UnknownPropertyError = class extends BaseError { + constructor(property, value) { + super("Received unexpected property"); + this.property = property; + this.value = value; + } + toJSON() { + return { + name: this.name, + property: this.property, + value: this.value + }; + } + [customInspectSymbolStackLess](depth, options) { + const property = options.stylize(this.property.toString(), "string"); + if (depth < 0) { + return options.stylize(`[UnknownPropertyError: ${property}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const given = inspect(this.value, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("UnknownPropertyError", "special")} > ${property}`; + const message = options.stylize(this.message, "regexp"); + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${givenBlock}`; + } +}; +__name(UnknownPropertyError, "UnknownPropertyError"); + +// src/validators/DefaultValidator.ts +var DefaultValidator = class extends BaseValidator { + constructor(validator, value, constraints = []) { + super(constraints); + this.validator = validator; + this.defaultValue = value; + } + default(value) { + const clone = this.clone(); + clone.defaultValue = value; + return clone; + } + handle(value) { + return typeof value === "undefined" ? Result.ok(getValue(this.defaultValue)) : this.validator["handle"](value); + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.defaultValue, this.constraints]); + } +}; +__name(DefaultValidator, "DefaultValidator"); + +// src/lib/errors/CombinedError.ts +var CombinedError = class extends BaseError { + constructor(errors) { + super("Received one or more errors"); + this.errors = errors; + } + [customInspectSymbolStackLess](depth, options) { + if (depth < 0) { + return options.stylize("[CombinedError]", "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1, compact: true }; + const padding = ` + ${options.stylize("|", "undefined")} `; + const header = `${options.stylize("CombinedError", "special")} (${options.stylize(this.errors.length.toString(), "number")})`; + const message = options.stylize(this.message, "regexp"); + const errors = this.errors.map((error, i) => { + const index = options.stylize((i + 1).toString(), "number"); + const body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\n/g, padding); + return ` ${index} ${body}`; + }).join("\n\n"); + return `${header} + ${message} + +${errors}`; + } +}; +__name(CombinedError, "CombinedError"); + +// src/validators/UnionValidator.ts +var UnionValidator = class extends BaseValidator { + constructor(validators, constraints = []) { + super(constraints); + this.validators = validators; + } + get optional() { + if (this.validators.length === 0) + return new UnionValidator([new LiteralValidator(void 0)], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) + return this.clone(); + if (validator.expected === null) { + return new UnionValidator( + [new NullishValidator(), ...this.validators.slice(1)], + this.constraints + ); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new LiteralValidator(void 0), ...this.validators]); + } + get required() { + if (this.validators.length === 0) + return this.clone(); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) + return new UnionValidator(this.validators.slice(1), this.constraints); + } else if (validator instanceof NullishValidator) { + return new UnionValidator([new LiteralValidator(null), ...this.validators.slice(1)], this.constraints); + } + return this.clone(); + } + get nullable() { + if (this.validators.length === 0) + return new UnionValidator([new LiteralValidator(null)], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === null) + return this.clone(); + if (validator.expected === void 0) { + return new UnionValidator( + [new NullishValidator(), ...this.validators.slice(1)], + this.constraints + ); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new LiteralValidator(null), ...this.validators]); + } + get nullish() { + if (this.validators.length === 0) + return new UnionValidator([new NullishValidator()], this.constraints); + const [validator] = this.validators; + if (validator instanceof LiteralValidator) { + if (validator.expected === null || validator.expected === void 0) { + return new UnionValidator([new NullishValidator(), ...this.validators.slice(1)], this.constraints); + } + } else if (validator instanceof NullishValidator) { + return this.clone(); + } + return new UnionValidator([new NullishValidator(), ...this.validators]); + } + or(...predicates) { + return new UnionValidator([...this.validators, ...predicates]); + } + clone() { + return Reflect.construct(this.constructor, [this.validators, this.constraints]); + } + handle(value) { + const errors = []; + for (const validator of this.validators) { + const result = validator.run(value); + if (result.isOk()) + return result; + errors.push(result.error); + } + return Result.err(new CombinedError(errors)); + } +}; +__name(UnionValidator, "UnionValidator"); + +// src/validators/ObjectValidator.ts +var ObjectValidator = class extends BaseValidator { + constructor(shape, strategy = ObjectValidatorStrategy.Ignore, constraints = []) { + super(constraints); + this.keys = []; + this.requiredKeys = /* @__PURE__ */ new Map(); + this.possiblyUndefinedKeys = /* @__PURE__ */ new Map(); + this.possiblyUndefinedKeysWithDefaults = /* @__PURE__ */ new Map(); + this.shape = shape; + this.strategy = strategy; + switch (this.strategy) { + case ObjectValidatorStrategy.Ignore: + this.handleStrategy = (value) => this.handleIgnoreStrategy(value); + break; + case ObjectValidatorStrategy.Strict: { + this.handleStrategy = (value) => this.handleStrictStrategy(value); + break; + } + case ObjectValidatorStrategy.Passthrough: + this.handleStrategy = (value) => this.handlePassthroughStrategy(value); + break; + } + const shapeEntries = Object.entries(shape); + this.keys = shapeEntries.map(([key]) => key); + for (const [key, validator] of shapeEntries) { + if (validator instanceof UnionValidator) { + const [possiblyLiteralOrNullishPredicate] = validator["validators"]; + if (possiblyLiteralOrNullishPredicate instanceof NullishValidator) { + this.possiblyUndefinedKeys.set(key, validator); + } else if (possiblyLiteralOrNullishPredicate instanceof LiteralValidator) { + if (possiblyLiteralOrNullishPredicate.expected === void 0) { + this.possiblyUndefinedKeys.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof DefaultValidator) { + this.possiblyUndefinedKeysWithDefaults.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof NullishValidator) { + this.possiblyUndefinedKeys.set(key, validator); + } else if (validator instanceof LiteralValidator) { + if (validator.expected === void 0) { + this.possiblyUndefinedKeys.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } else if (validator instanceof DefaultValidator) { + this.possiblyUndefinedKeysWithDefaults.set(key, validator); + } else { + this.requiredKeys.set(key, validator); + } + } + } + get strict() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Strict, this.constraints]); + } + get ignore() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Ignore, this.constraints]); + } + get passthrough() { + return Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Passthrough, this.constraints]); + } + get partial() { + const shape = Object.fromEntries(this.keys.map((key) => [key, this.shape[key].optional])); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + get required() { + const shape = Object.fromEntries( + this.keys.map((key) => { + let validator = this.shape[key]; + if (validator instanceof UnionValidator) + validator = validator.required; + return [key, validator]; + }) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + extend(schema) { + const shape = { ...this.shape, ...schema instanceof ObjectValidator ? schema.shape : schema }; + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + pick(keys) { + const shape = Object.fromEntries( + keys.filter((key) => this.keys.includes(key)).map((key) => [key, this.shape[key]]) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + omit(keys) { + const shape = Object.fromEntries( + this.keys.filter((key) => !keys.includes(key)).map((key) => [key, this.shape[key]]) + ); + return Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]); + } + handle(value) { + const typeOfValue = typeof value; + if (typeOfValue !== "object") { + return Result.err(new ValidationError("s.object(T)", `Expected the value to be an object, but received ${typeOfValue} instead`, value)); + } + if (value === null) { + return Result.err(new ValidationError("s.object(T)", "Expected the value to not be null", value)); + } + if (Array.isArray(value)) { + return Result.err(new ValidationError("s.object(T)", "Expected the value to not be an array", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + for (const predicate of Object.values(this.shape)) { + predicate.setParent(this.parent ?? value); + } + return this.handleStrategy(value); + } + clone() { + return Reflect.construct(this.constructor, [this.shape, this.strategy, this.constraints]); + } + handleIgnoreStrategy(value) { + const errors = []; + const finalObject = {}; + const inputEntries = new Map(Object.entries(value)); + const runPredicate = /* @__PURE__ */ __name((key, predicate) => { + const result = predicate.run(value[key]); + if (result.isOk()) { + finalObject[key] = result.value; + } else { + const error = result.error; + errors.push([key, error]); + } + }, "runPredicate"); + for (const [key, predicate] of this.requiredKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } else { + errors.push([key, new MissingPropertyError(key)]); + } + } + for (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) { + inputEntries.delete(key); + runPredicate(key, validator); + } + if (inputEntries.size === 0) { + return errors.length === 0 ? Result.ok(finalObject) : Result.err(new CombinedPropertyError(errors)); + } + const checkInputEntriesInsteadOfSchemaKeys = this.possiblyUndefinedKeys.size > inputEntries.size; + if (checkInputEntriesInsteadOfSchemaKeys) { + for (const [key] of inputEntries) { + const predicate = this.possiblyUndefinedKeys.get(key); + if (predicate) { + runPredicate(key, predicate); + } + } + } else { + for (const [key, predicate] of this.possiblyUndefinedKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } + } + } + return errors.length === 0 ? Result.ok(finalObject) : Result.err(new CombinedPropertyError(errors)); + } + handleStrictStrategy(value) { + const errors = []; + const finalResult = {}; + const inputEntries = new Map(Object.entries(value)); + const runPredicate = /* @__PURE__ */ __name((key, predicate) => { + const result = predicate.run(value[key]); + if (result.isOk()) { + finalResult[key] = result.value; + } else { + const error = result.error; + errors.push([key, error]); + } + }, "runPredicate"); + for (const [key, predicate] of this.requiredKeys) { + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } else { + errors.push([key, new MissingPropertyError(key)]); + } + } + for (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) { + inputEntries.delete(key); + runPredicate(key, validator); + } + for (const [key, predicate] of this.possiblyUndefinedKeys) { + if (inputEntries.size === 0) { + break; + } + if (inputEntries.delete(key)) { + runPredicate(key, predicate); + } + } + if (inputEntries.size !== 0) { + for (const [key, value2] of inputEntries.entries()) { + errors.push([key, new UnknownPropertyError(key, value2)]); + } + } + return errors.length === 0 ? Result.ok(finalResult) : Result.err(new CombinedPropertyError(errors)); + } + handlePassthroughStrategy(value) { + const result = this.handleIgnoreStrategy(value); + return result.isErr() ? result : Result.ok({ ...value, ...result.value }); + } +}; +__name(ObjectValidator, "ObjectValidator"); +var ObjectValidatorStrategy = /* @__PURE__ */ ((ObjectValidatorStrategy2) => { + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Ignore"] = 0] = "Ignore"; + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Strict"] = 1] = "Strict"; + ObjectValidatorStrategy2[ObjectValidatorStrategy2["Passthrough"] = 2] = "Passthrough"; + return ObjectValidatorStrategy2; +})(ObjectValidatorStrategy || {}); + +// src/validators/PassthroughValidator.ts +var PassthroughValidator = class extends BaseValidator { + handle(value) { + return Result.ok(value); + } +}; +__name(PassthroughValidator, "PassthroughValidator"); + +// src/validators/RecordValidator.ts +var RecordValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(value) { + if (typeof value !== "object") { + return Result.err(new ValidationError("s.record(T)", "Expected an object", value)); + } + if (value === null) { + return Result.err(new ValidationError("s.record(T)", "Expected the value to not be null", value)); + } + if (Array.isArray(value)) { + return Result.err(new ValidationError("s.record(T)", "Expected the value to not be an array", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + const errors = []; + const transformed = {}; + for (const [key, val] of Object.entries(value)) { + const result = this.validator.run(val); + if (result.isOk()) + transformed[key] = result.value; + else + errors.push([key, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } +}; +__name(RecordValidator, "RecordValidator"); + +// src/validators/SetValidator.ts +var SetValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + if (!(values instanceof Set)) { + return Result.err(new ValidationError("s.set(T)", "Expected a set", values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = /* @__PURE__ */ new Set(); + for (const value of values) { + const result = this.validator.run(value); + if (result.isOk()) + transformed.add(result.value); + else + errors.push(result.error); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedError(errors)); + } +}; +__name(SetValidator, "SetValidator"); + +// src/constraints/util/emailValidator.ts +var accountRegex = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")$/; +function validateEmail(email) { + if (!email) + return false; + const atIndex = email.indexOf("@"); + if (atIndex === -1) + return false; + if (atIndex > 64) + return false; + const domainIndex = atIndex + 1; + if (email.includes("@", domainIndex)) + return false; + if (email.length - domainIndex > 255) + return false; + let dotIndex = email.indexOf(".", domainIndex); + if (dotIndex === -1) + return false; + let lastDotIndex = domainIndex; + do { + if (dotIndex - lastDotIndex > 63) + return false; + lastDotIndex = dotIndex + 1; + } while ((dotIndex = email.indexOf(".", lastDotIndex)) !== -1); + if (email.length - lastDotIndex > 63) + return false; + return accountRegex.test(email.slice(0, atIndex)) && validateEmailDomain(email.slice(domainIndex)); +} +__name(validateEmail, "validateEmail"); +function validateEmailDomain(domain) { + try { + return new URL(`http://${domain}`).hostname === domain; + } catch { + return false; + } +} +__name(validateEmailDomain, "validateEmailDomain"); + +// src/constraints/util/net.ts +var v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"; +var v4Str = `(${v4Seg}[.]){3}${v4Seg}`; +var IPv4Reg = new RegExp(`^${v4Str}$`); +var v6Seg = "(?:[0-9a-fA-F]{1,4})"; +var IPv6Reg = new RegExp( + `^((?:${v6Seg}:){7}(?:${v6Seg}|:)|(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$` +); +function isIPv4(s2) { + return IPv4Reg.test(s2); +} +__name(isIPv4, "isIPv4"); +function isIPv6(s2) { + return IPv6Reg.test(s2); +} +__name(isIPv6, "isIPv6"); +function isIP(s2) { + if (isIPv4(s2)) + return 4; + if (isIPv6(s2)) + return 6; + return 0; +} +__name(isIP, "isIP"); + +// src/constraints/util/phoneValidator.ts +var phoneNumberRegex = /^((?:\+|0{0,2})\d{1,2}\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/; +function validatePhoneNumber(input) { + return phoneNumberRegex.test(input); +} +__name(validatePhoneNumber, "validatePhoneNumber"); +var MultiplePossibilitiesConstraintError = class extends BaseConstraintError { + constructor(constraint, message, given, expected) { + super(constraint, message, given); + this.expected = expected; + } + toJSON() { + return { + name: this.name, + constraint: this.constraint, + given: this.given, + expected: this.expected + }; + } + [customInspectSymbolStackLess](depth, options) { + const constraint = options.stylize(this.constraint, "string"); + if (depth < 0) { + return options.stylize(`[MultiplePossibilitiesConstraintError: ${constraint}]`, "special"); + } + const newOptions = { ...options, depth: options.depth === null ? null : options.depth - 1 }; + const verticalLine = options.stylize("|", "undefined"); + const padding = ` + ${verticalLine} `; + const given = inspect(this.given, newOptions).replace(/\n/g, padding); + const header = `${options.stylize("MultiplePossibilitiesConstraintError", "special")} > ${constraint}`; + const message = options.stylize(this.message, "regexp"); + const expectedPadding = ` + ${verticalLine} - `; + const expectedBlock = ` + ${options.stylize("Expected any of the following:", "string")}${expectedPadding}${this.expected.map((possible) => options.stylize(possible, "boolean")).join(expectedPadding)}`; + const givenBlock = ` + ${options.stylize("Received:", "regexp")}${padding}${given}`; + return `${header} + ${message} +${expectedBlock} +${givenBlock}`; + } +}; +__name(MultiplePossibilitiesConstraintError, "MultiplePossibilitiesConstraintError"); + +// src/constraints/util/common/combinedResultFn.ts +function combinedErrorFn(...fns) { + switch (fns.length) { + case 0: + return () => null; + case 1: + return fns[0]; + case 2: { + const [fn0, fn1] = fns; + return (...params) => fn0(...params) || fn1(...params); + } + default: { + return (...params) => { + for (const fn of fns) { + const result = fn(...params); + if (result) + return result; + } + return null; + }; + } + } +} +__name(combinedErrorFn, "combinedErrorFn"); + +// src/constraints/util/urlValidators.ts +function createUrlValidators(options) { + const fns = []; + if (options?.allowedProtocols?.length) + fns.push(allowedProtocolsFn(options.allowedProtocols)); + if (options?.allowedDomains?.length) + fns.push(allowedDomainsFn(options.allowedDomains)); + return combinedErrorFn(...fns); +} +__name(createUrlValidators, "createUrlValidators"); +function allowedProtocolsFn(allowedProtocols) { + return (input, url) => allowedProtocols.includes(url.protocol) ? null : new MultiplePossibilitiesConstraintError("s.string.url", "Invalid URL protocol", input, allowedProtocols); +} +__name(allowedProtocolsFn, "allowedProtocolsFn"); +function allowedDomainsFn(allowedDomains) { + return (input, url) => allowedDomains.includes(url.hostname) ? null : new MultiplePossibilitiesConstraintError("s.string.url", "Invalid URL domain", input, allowedDomains); +} +__name(allowedDomainsFn, "allowedDomainsFn"); + +// src/constraints/StringConstraints.ts +function stringLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid string length", input, expected)); + } + }; +} +__name(stringLengthComparator, "stringLengthComparator"); +function stringLengthLessThan(length) { + const expected = `expected.length < ${length}`; + return stringLengthComparator(lessThan, "s.string.lengthLessThan", expected, length); +} +__name(stringLengthLessThan, "stringLengthLessThan"); +function stringLengthLessThanOrEqual(length) { + const expected = `expected.length <= ${length}`; + return stringLengthComparator(lessThanOrEqual, "s.string.lengthLessThanOrEqual", expected, length); +} +__name(stringLengthLessThanOrEqual, "stringLengthLessThanOrEqual"); +function stringLengthGreaterThan(length) { + const expected = `expected.length > ${length}`; + return stringLengthComparator(greaterThan, "s.string.lengthGreaterThan", expected, length); +} +__name(stringLengthGreaterThan, "stringLengthGreaterThan"); +function stringLengthGreaterThanOrEqual(length) { + const expected = `expected.length >= ${length}`; + return stringLengthComparator(greaterThanOrEqual, "s.string.lengthGreaterThanOrEqual", expected, length); +} +__name(stringLengthGreaterThanOrEqual, "stringLengthGreaterThanOrEqual"); +function stringLengthEqual(length) { + const expected = `expected.length === ${length}`; + return stringLengthComparator(equal, "s.string.lengthEqual", expected, length); +} +__name(stringLengthEqual, "stringLengthEqual"); +function stringLengthNotEqual(length) { + const expected = `expected.length !== ${length}`; + return stringLengthComparator(notEqual, "s.string.lengthNotEqual", expected, length); +} +__name(stringLengthNotEqual, "stringLengthNotEqual"); +function stringEmail() { + return { + run(input) { + return validateEmail(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.string.email", "Invalid email address", input, "expected to be an email address")); + } + }; +} +__name(stringEmail, "stringEmail"); +function stringRegexValidator(type, expected, regex) { + return { + run(input) { + return regex.test(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(type, "Invalid string format", input, expected)); + } + }; +} +__name(stringRegexValidator, "stringRegexValidator"); +function stringUrl(options) { + const validatorFn = createUrlValidators(options); + return { + run(input) { + let url; + try { + url = new URL(input); + } catch { + return Result.err(new ExpectedConstraintError("s.string.url", "Invalid URL", input, "expected to match an URL")); + } + const validatorFnResult = validatorFn(input, url); + if (validatorFnResult === null) + return Result.ok(input); + return Result.err(validatorFnResult); + } + }; +} +__name(stringUrl, "stringUrl"); +function stringIp(version) { + const ipVersion = version ? `v${version}` : ""; + const validatorFn = version === 4 ? isIPv4 : version === 6 ? isIPv6 : isIP; + const name = `s.string.ip${ipVersion}`; + const message = `Invalid IP${ipVersion} address`; + const expected = `expected to be an IP${ipVersion} address`; + return { + run(input) { + return validatorFn(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, message, input, expected)); + } + }; +} +__name(stringIp, "stringIp"); +function stringRegex(regex) { + return stringRegexValidator("s.string.regex", `expected ${regex}.test(expected) to be true`, regex); +} +__name(stringRegex, "stringRegex"); +function stringUuid({ version = 4, nullable = false } = {}) { + version ?? (version = "1-5"); + const regex = new RegExp( + `^(?:[0-9A-F]{8}-[0-9A-F]{4}-[${version}][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}${nullable ? "|00000000-0000-0000-0000-000000000000" : ""})$`, + "i" + ); + const expected = `expected to match UUID${typeof version === "number" ? `v${version}` : ` in range of ${version}`}`; + return stringRegexValidator("s.string.uuid", expected, regex); +} +__name(stringUuid, "stringUuid"); +function stringDate() { + return { + run(input) { + const time = Date.parse(input); + return Number.isNaN(time) ? Result.err( + new ExpectedConstraintError( + "s.string.date", + "Invalid date string", + input, + "expected to be a valid date string (in the ISO 8601 or ECMA-262 format)" + ) + ) : Result.ok(input); + } + }; +} +__name(stringDate, "stringDate"); +function stringPhone() { + return { + run(input) { + return validatePhoneNumber(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.string.phone", "Invalid phone number", input, "expected to be a phone number")); + } + }; +} +__name(stringPhone, "stringPhone"); + +// src/validators/StringValidator.ts +var StringValidator = class extends BaseValidator { + lengthLessThan(length) { + return this.addConstraint(stringLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(stringLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(stringLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(stringLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(stringLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(stringLengthNotEqual(length)); + } + get email() { + return this.addConstraint(stringEmail()); + } + url(options) { + return this.addConstraint(stringUrl(options)); + } + uuid(options) { + return this.addConstraint(stringUuid(options)); + } + regex(regex) { + return this.addConstraint(stringRegex(regex)); + } + get date() { + return this.addConstraint(stringDate()); + } + get ipv4() { + return this.ip(4); + } + get ipv6() { + return this.ip(6); + } + ip(version) { + return this.addConstraint(stringIp(version)); + } + phone() { + return this.addConstraint(stringPhone()); + } + handle(value) { + return typeof value === "string" ? Result.ok(value) : Result.err(new ValidationError("s.string", "Expected a string primitive", value)); + } +}; +__name(StringValidator, "StringValidator"); + +// src/validators/TupleValidator.ts +var TupleValidator = class extends BaseValidator { + constructor(validators, constraints = []) { + super(constraints); + this.validators = []; + this.validators = validators; + } + clone() { + return Reflect.construct(this.constructor, [this.validators, this.constraints]); + } + handle(values) { + if (!Array.isArray(values)) { + return Result.err(new ValidationError("s.tuple(T)", "Expected an array", values)); + } + if (values.length !== this.validators.length) { + return Result.err(new ValidationError("s.tuple(T)", `Expected an array of length ${this.validators.length}`, values)); + } + if (!this.shouldRunConstraints) { + return Result.ok(values); + } + const errors = []; + const transformed = []; + for (let i = 0; i < values.length; i++) { + const result = this.validators[i].run(values[i]); + if (result.isOk()) + transformed.push(result.value); + else + errors.push([i, result.error]); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } +}; +__name(TupleValidator, "TupleValidator"); + +// src/validators/MapValidator.ts +var MapValidator = class extends BaseValidator { + constructor(keyValidator, valueValidator, constraints = []) { + super(constraints); + this.keyValidator = keyValidator; + this.valueValidator = valueValidator; + } + clone() { + return Reflect.construct(this.constructor, [this.keyValidator, this.valueValidator, this.constraints]); + } + handle(value) { + if (!(value instanceof Map)) { + return Result.err(new ValidationError("s.map(K, V)", "Expected a map", value)); + } + if (!this.shouldRunConstraints) { + return Result.ok(value); + } + const errors = []; + const transformed = /* @__PURE__ */ new Map(); + for (const [key, val] of value.entries()) { + const keyResult = this.keyValidator.run(key); + const valueResult = this.valueValidator.run(val); + const { length } = errors; + if (keyResult.isErr()) + errors.push([key, keyResult.error]); + if (valueResult.isErr()) + errors.push([key, valueResult.error]); + if (errors.length === length) + transformed.set(keyResult.value, valueResult.value); + } + return errors.length === 0 ? Result.ok(transformed) : Result.err(new CombinedPropertyError(errors)); + } +}; +__name(MapValidator, "MapValidator"); + +// src/validators/LazyValidator.ts +var LazyValidator = class extends BaseValidator { + constructor(validator, constraints = []) { + super(constraints); + this.validator = validator; + } + clone() { + return Reflect.construct(this.constructor, [this.validator, this.constraints]); + } + handle(values) { + return this.validator(values).run(values); + } +}; +__name(LazyValidator, "LazyValidator"); + +// src/lib/errors/UnknownEnumValueError.ts +var UnknownEnumValueError = class extends BaseError { + constructor(value, keys, enumMappings) { + super("Expected the value to be one of the following enum values:"); + this.value = value; + this.enumKeys = keys; + this.enumMappings = enumMappings; + } + toJSON() { + return { + name: this.name, + value: this.value, + enumKeys: this.enumKeys, + enumMappings: [...this.enumMappings.entries()] + }; + } + [customInspectSymbolStackLess](depth, options) { + const value = options.stylize(this.value.toString(), "string"); + if (depth < 0) { + return options.stylize(`[UnknownEnumValueError: ${value}]`, "special"); + } + const padding = ` + ${options.stylize("|", "undefined")} `; + const pairs = this.enumKeys.map((key) => { + const enumValue = this.enumMappings.get(key); + return `${options.stylize(key, "string")} or ${options.stylize( + enumValue.toString(), + typeof enumValue === "number" ? "number" : "string" + )}`; + }).join(padding); + const header = `${options.stylize("UnknownEnumValueError", "special")} > ${value}`; + const message = options.stylize(this.message, "regexp"); + const pairsBlock = `${padding}${pairs}`; + return `${header} + ${message} +${pairsBlock}`; + } +}; +__name(UnknownEnumValueError, "UnknownEnumValueError"); + +// src/validators/NativeEnumValidator.ts +var NativeEnumValidator = class extends BaseValidator { + constructor(enumShape) { + super(); + this.hasNumericElements = false; + this.enumMapping = /* @__PURE__ */ new Map(); + this.enumShape = enumShape; + this.enumKeys = Object.keys(enumShape).filter((key) => { + return typeof enumShape[enumShape[key]] !== "number"; + }); + for (const key of this.enumKeys) { + const enumValue = enumShape[key]; + this.enumMapping.set(key, enumValue); + this.enumMapping.set(enumValue, enumValue); + if (typeof enumValue === "number") { + this.hasNumericElements = true; + this.enumMapping.set(`${enumValue}`, enumValue); + } + } + } + handle(value) { + const typeOfValue = typeof value; + if (typeOfValue === "number") { + if (!this.hasNumericElements) { + return Result.err(new ValidationError("s.nativeEnum(T)", "Expected the value to be a string", value)); + } + } else if (typeOfValue !== "string") { + return Result.err(new ValidationError("s.nativeEnum(T)", "Expected the value to be a string or number", value)); + } + const casted = value; + const possibleEnumValue = this.enumMapping.get(casted); + return typeof possibleEnumValue === "undefined" ? Result.err(new UnknownEnumValueError(casted, this.enumKeys, this.enumMapping)) : Result.ok(possibleEnumValue); + } + clone() { + return Reflect.construct(this.constructor, [this.enumShape]); + } +}; +__name(NativeEnumValidator, "NativeEnumValidator"); + +// src/constraints/TypedArrayLengthConstraints.ts +function typedArrayByteLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.byteLength, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Typed Array byte length", input, expected)); + } + }; +} +__name(typedArrayByteLengthComparator, "typedArrayByteLengthComparator"); +function typedArrayByteLengthLessThan(value) { + const expected = `expected.byteLength < ${value}`; + return typedArrayByteLengthComparator(lessThan, "s.typedArray(T).byteLengthLessThan", expected, value); +} +__name(typedArrayByteLengthLessThan, "typedArrayByteLengthLessThan"); +function typedArrayByteLengthLessThanOrEqual(value) { + const expected = `expected.byteLength <= ${value}`; + return typedArrayByteLengthComparator(lessThanOrEqual, "s.typedArray(T).byteLengthLessThanOrEqual", expected, value); +} +__name(typedArrayByteLengthLessThanOrEqual, "typedArrayByteLengthLessThanOrEqual"); +function typedArrayByteLengthGreaterThan(value) { + const expected = `expected.byteLength > ${value}`; + return typedArrayByteLengthComparator(greaterThan, "s.typedArray(T).byteLengthGreaterThan", expected, value); +} +__name(typedArrayByteLengthGreaterThan, "typedArrayByteLengthGreaterThan"); +function typedArrayByteLengthGreaterThanOrEqual(value) { + const expected = `expected.byteLength >= ${value}`; + return typedArrayByteLengthComparator(greaterThanOrEqual, "s.typedArray(T).byteLengthGreaterThanOrEqual", expected, value); +} +__name(typedArrayByteLengthGreaterThanOrEqual, "typedArrayByteLengthGreaterThanOrEqual"); +function typedArrayByteLengthEqual(value) { + const expected = `expected.byteLength === ${value}`; + return typedArrayByteLengthComparator(equal, "s.typedArray(T).byteLengthEqual", expected, value); +} +__name(typedArrayByteLengthEqual, "typedArrayByteLengthEqual"); +function typedArrayByteLengthNotEqual(value) { + const expected = `expected.byteLength !== ${value}`; + return typedArrayByteLengthComparator(notEqual, "s.typedArray(T).byteLengthNotEqual", expected, value); +} +__name(typedArrayByteLengthNotEqual, "typedArrayByteLengthNotEqual"); +function typedArrayByteLengthRange(start, endBefore) { + const expected = `expected.byteLength >= ${start} && expected.byteLength < ${endBefore}`; + return { + run(input) { + return input.byteLength >= start && input.byteLength < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).byteLengthRange", "Invalid Typed Array byte length", input, expected)); + } + }; +} +__name(typedArrayByteLengthRange, "typedArrayByteLengthRange"); +function typedArrayByteLengthRangeInclusive(start, end) { + const expected = `expected.byteLength >= ${start} && expected.byteLength <= ${end}`; + return { + run(input) { + return input.byteLength >= start && input.byteLength <= end ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.typedArray(T).byteLengthRangeInclusive", "Invalid Typed Array byte length", input, expected) + ); + } + }; +} +__name(typedArrayByteLengthRangeInclusive, "typedArrayByteLengthRangeInclusive"); +function typedArrayByteLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.byteLength > ${startAfter} && expected.byteLength < ${endBefore}`; + return { + run(input) { + return input.byteLength > startAfter && input.byteLength < endBefore ? Result.ok(input) : Result.err( + new ExpectedConstraintError("s.typedArray(T).byteLengthRangeExclusive", "Invalid Typed Array byte length", input, expected) + ); + } + }; +} +__name(typedArrayByteLengthRangeExclusive, "typedArrayByteLengthRangeExclusive"); +function typedArrayLengthComparator(comparator, name, expected, length) { + return { + run(input) { + return comparator(input.length, length) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, "Invalid Typed Array length", input, expected)); + } + }; +} +__name(typedArrayLengthComparator, "typedArrayLengthComparator"); +function typedArrayLengthLessThan(value) { + const expected = `expected.length < ${value}`; + return typedArrayLengthComparator(lessThan, "s.typedArray(T).lengthLessThan", expected, value); +} +__name(typedArrayLengthLessThan, "typedArrayLengthLessThan"); +function typedArrayLengthLessThanOrEqual(value) { + const expected = `expected.length <= ${value}`; + return typedArrayLengthComparator(lessThanOrEqual, "s.typedArray(T).lengthLessThanOrEqual", expected, value); +} +__name(typedArrayLengthLessThanOrEqual, "typedArrayLengthLessThanOrEqual"); +function typedArrayLengthGreaterThan(value) { + const expected = `expected.length > ${value}`; + return typedArrayLengthComparator(greaterThan, "s.typedArray(T).lengthGreaterThan", expected, value); +} +__name(typedArrayLengthGreaterThan, "typedArrayLengthGreaterThan"); +function typedArrayLengthGreaterThanOrEqual(value) { + const expected = `expected.length >= ${value}`; + return typedArrayLengthComparator(greaterThanOrEqual, "s.typedArray(T).lengthGreaterThanOrEqual", expected, value); +} +__name(typedArrayLengthGreaterThanOrEqual, "typedArrayLengthGreaterThanOrEqual"); +function typedArrayLengthEqual(value) { + const expected = `expected.length === ${value}`; + return typedArrayLengthComparator(equal, "s.typedArray(T).lengthEqual", expected, value); +} +__name(typedArrayLengthEqual, "typedArrayLengthEqual"); +function typedArrayLengthNotEqual(value) { + const expected = `expected.length !== ${value}`; + return typedArrayLengthComparator(notEqual, "s.typedArray(T).lengthNotEqual", expected, value); +} +__name(typedArrayLengthNotEqual, "typedArrayLengthNotEqual"); +function typedArrayLengthRange(start, endBefore) { + const expected = `expected.length >= ${start} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length >= start && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRange", "Invalid Typed Array length", input, expected)); + } + }; +} +__name(typedArrayLengthRange, "typedArrayLengthRange"); +function typedArrayLengthRangeInclusive(start, end) { + const expected = `expected.length >= ${start} && expected.length <= ${end}`; + return { + run(input) { + return input.length >= start && input.length <= end ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRangeInclusive", "Invalid Typed Array length", input, expected)); + } + }; +} +__name(typedArrayLengthRangeInclusive, "typedArrayLengthRangeInclusive"); +function typedArrayLengthRangeExclusive(startAfter, endBefore) { + const expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`; + return { + run(input) { + return input.length > startAfter && input.length < endBefore ? Result.ok(input) : Result.err(new ExpectedConstraintError("s.typedArray(T).lengthRangeExclusive", "Invalid Typed Array length", input, expected)); + } + }; +} +__name(typedArrayLengthRangeExclusive, "typedArrayLengthRangeExclusive"); + +// src/constraints/util/common/vowels.ts +var vowels = ["a", "e", "i", "o", "u"]; +var aOrAn = /* @__PURE__ */ __name((word) => { + return `${vowels.includes(word[0].toLowerCase()) ? "an" : "a"} ${word}`; +}, "aOrAn"); + +// src/constraints/util/typedArray.ts +var TypedArrays = { + Int8Array: (x) => x instanceof Int8Array, + Uint8Array: (x) => x instanceof Uint8Array, + Uint8ClampedArray: (x) => x instanceof Uint8ClampedArray, + Int16Array: (x) => x instanceof Int16Array, + Uint16Array: (x) => x instanceof Uint16Array, + Int32Array: (x) => x instanceof Int32Array, + Uint32Array: (x) => x instanceof Uint32Array, + Float32Array: (x) => x instanceof Float32Array, + Float64Array: (x) => x instanceof Float64Array, + BigInt64Array: (x) => x instanceof BigInt64Array, + BigUint64Array: (x) => x instanceof BigUint64Array, + TypedArray: (x) => ArrayBuffer.isView(x) && !(x instanceof DataView) +}; + +// src/validators/TypedArrayValidator.ts +var TypedArrayValidator = class extends BaseValidator { + constructor(type, constraints = []) { + super(constraints); + this.type = type; + } + byteLengthLessThan(length) { + return this.addConstraint(typedArrayByteLengthLessThan(length)); + } + byteLengthLessThanOrEqual(length) { + return this.addConstraint(typedArrayByteLengthLessThanOrEqual(length)); + } + byteLengthGreaterThan(length) { + return this.addConstraint(typedArrayByteLengthGreaterThan(length)); + } + byteLengthGreaterThanOrEqual(length) { + return this.addConstraint(typedArrayByteLengthGreaterThanOrEqual(length)); + } + byteLengthEqual(length) { + return this.addConstraint(typedArrayByteLengthEqual(length)); + } + byteLengthNotEqual(length) { + return this.addConstraint(typedArrayByteLengthNotEqual(length)); + } + byteLengthRange(start, endBefore) { + return this.addConstraint(typedArrayByteLengthRange(start, endBefore)); + } + byteLengthRangeInclusive(startAt, endAt) { + return this.addConstraint(typedArrayByteLengthRangeInclusive(startAt, endAt)); + } + byteLengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(typedArrayByteLengthRangeExclusive(startAfter, endBefore)); + } + lengthLessThan(length) { + return this.addConstraint(typedArrayLengthLessThan(length)); + } + lengthLessThanOrEqual(length) { + return this.addConstraint(typedArrayLengthLessThanOrEqual(length)); + } + lengthGreaterThan(length) { + return this.addConstraint(typedArrayLengthGreaterThan(length)); + } + lengthGreaterThanOrEqual(length) { + return this.addConstraint(typedArrayLengthGreaterThanOrEqual(length)); + } + lengthEqual(length) { + return this.addConstraint(typedArrayLengthEqual(length)); + } + lengthNotEqual(length) { + return this.addConstraint(typedArrayLengthNotEqual(length)); + } + lengthRange(start, endBefore) { + return this.addConstraint(typedArrayLengthRange(start, endBefore)); + } + lengthRangeInclusive(startAt, endAt) { + return this.addConstraint(typedArrayLengthRangeInclusive(startAt, endAt)); + } + lengthRangeExclusive(startAfter, endBefore) { + return this.addConstraint(typedArrayLengthRangeExclusive(startAfter, endBefore)); + } + clone() { + return Reflect.construct(this.constructor, [this.type, this.constraints]); + } + handle(value) { + return TypedArrays[this.type](value) ? Result.ok(value) : Result.err(new ValidationError("s.typedArray", `Expected ${aOrAn(this.type)}`, value)); + } +}; +__name(TypedArrayValidator, "TypedArrayValidator"); + +// src/lib/Shapes.ts +var Shapes = class { + get string() { + return new StringValidator(); + } + get number() { + return new NumberValidator(); + } + get bigint() { + return new BigIntValidator(); + } + get boolean() { + return new BooleanValidator(); + } + get date() { + return new DateValidator(); + } + object(shape) { + return new ObjectValidator(shape); + } + get undefined() { + return this.literal(void 0); + } + get null() { + return this.literal(null); + } + get nullish() { + return new NullishValidator(); + } + get any() { + return new PassthroughValidator(); + } + get unknown() { + return new PassthroughValidator(); + } + get never() { + return new NeverValidator(); + } + enum(...values) { + return this.union(...values.map((value) => this.literal(value))); + } + nativeEnum(enumShape) { + return new NativeEnumValidator(enumShape); + } + literal(value) { + if (value instanceof Date) + return this.date.equal(value); + return new LiteralValidator(value); + } + instance(expected) { + return new InstanceValidator(expected); + } + union(...validators) { + return new UnionValidator(validators); + } + array(validator) { + return new ArrayValidator(validator); + } + typedArray(type = "TypedArray") { + return new TypedArrayValidator(type); + } + get int8Array() { + return this.typedArray("Int8Array"); + } + get uint8Array() { + return this.typedArray("Uint8Array"); + } + get uint8ClampedArray() { + return this.typedArray("Uint8ClampedArray"); + } + get int16Array() { + return this.typedArray("Int16Array"); + } + get uint16Array() { + return this.typedArray("Uint16Array"); + } + get int32Array() { + return this.typedArray("Int32Array"); + } + get uint32Array() { + return this.typedArray("Uint32Array"); + } + get float32Array() { + return this.typedArray("Float32Array"); + } + get float64Array() { + return this.typedArray("Float64Array"); + } + get bigInt64Array() { + return this.typedArray("BigInt64Array"); + } + get bigUint64Array() { + return this.typedArray("BigUint64Array"); + } + tuple(validators) { + return new TupleValidator(validators); + } + set(validator) { + return new SetValidator(validator); + } + record(validator) { + return new RecordValidator(validator); + } + map(keyValidator, valueValidator) { + return new MapValidator(keyValidator, valueValidator); + } + lazy(validator) { + return new LazyValidator(validator); + } +}; +__name(Shapes, "Shapes"); + +// src/index.ts +var s = new Shapes(); + +export { BaseError, CombinedError, CombinedPropertyError, ExpectedConstraintError, ExpectedValidationError, MissingPropertyError, MultiplePossibilitiesConstraintError, Result, UnknownEnumValueError, UnknownPropertyError, ValidationError, customInspectSymbol, customInspectSymbolStackLess, getGlobalValidationEnabled, s, setGlobalValidationEnabled }; +//# sourceMappingURL=out.js.map +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/dist/index.mjs.map b/node_modules/@sapphire/shapeshift/dist/index.mjs.map new file mode 100644 index 0000000..871f0d6 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/lib/configs.ts","../src/lib/Result.ts","../src/validators/util/getValue.ts","../src/constraints/ObjectConstrains.ts","../src/lib/errors/ExpectedConstraintError.ts","../src/lib/errors/BaseError.ts","../src/lib/errors/BaseConstraintError.ts","../src/validators/BaseValidator.ts","../src/constraints/util/isUnique.ts","../src/constraints/util/operators.ts","../src/constraints/ArrayConstraints.ts","../src/lib/errors/CombinedPropertyError.ts","../src/lib/errors/ValidationError.ts","../src/validators/ArrayValidator.ts","../src/constraints/BigIntConstraints.ts","../src/validators/BigIntValidator.ts","../src/constraints/BooleanConstraints.ts","../src/validators/BooleanValidator.ts","../src/constraints/DateConstraints.ts","../src/validators/DateValidator.ts","../src/lib/errors/ExpectedValidationError.ts","../src/validators/InstanceValidator.ts","../src/validators/LiteralValidator.ts","../src/validators/NeverValidator.ts","../src/validators/NullishValidator.ts","../src/constraints/NumberConstraints.ts","../src/validators/NumberValidator.ts","../src/lib/errors/MissingPropertyError.ts","../src/lib/errors/UnknownPropertyError.ts","../src/validators/DefaultValidator.ts","../src/lib/errors/CombinedError.ts","../src/validators/UnionValidator.ts","../src/validators/ObjectValidator.ts","../src/validators/PassthroughValidator.ts","../src/validators/RecordValidator.ts","../src/validators/SetValidator.ts","../src/constraints/util/emailValidator.ts","../src/constraints/util/net.ts","../src/constraints/util/phoneValidator.ts","../src/lib/errors/MultiplePossibilitiesConstraintError.ts","../src/constraints/util/common/combinedResultFn.ts","../src/constraints/util/urlValidators.ts","../src/constraints/StringConstraints.ts","../src/validators/StringValidator.ts","../src/validators/TupleValidator.ts","../src/validators/MapValidator.ts","../src/validators/LazyValidator.ts","../src/lib/errors/UnknownEnumValueError.ts","../src/validators/NativeEnumValidator.ts","../src/constraints/TypedArrayLengthConstraints.ts","../src/constraints/util/common/vowels.ts","../src/constraints/util/typedArray.ts","../src/validators/TypedArrayValidator.ts","../src/lib/Shapes.ts","../src/index.ts"],"names":["uniqueArray","inspect","value","ObjectValidatorStrategy","s"],"mappings":";;;;AAAA,IAAI,oBAAoB;AAMjB,SAAS,2BAA2B,SAAkB;AAC5D,sBAA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KAAK,WAA0B,eAAe;AAAA,EACtD;AAAA,EAEA,IAAW,iBAAiB;AAC3B,WAAO,KAAK,WAA2B,gBAAgB;AAAA,EACxD;AAAA,EAEO,MAA2C,YAAoD;AACrG,WAAO,IAAI,eAAe,UAAU;AAAA,EACrC;AAAA,EAEO,IAAO,WAA6B;AAC1C,WAAO,IAAI,aAAa,SAAS;AAAA,EAClC;AAAA,EAEO,OAAU,WAA6B;AAC7C,WAAO,IAAI,gBAAgB,SAAS;AAAA,EACrC;AAAA,EAEO,IAAU,cAAgC,gBAAkC;AAClF,WAAO,IAAI,aAAa,cAAc,cAAc;AAAA,EACrD;AAAA,EAEO,KAAuC,WAAkC;AAC/E,WAAO,IAAI,cAAc,SAAS;AAAA,EACnC;AACD;AA/Ia;;;ACzBN,IAAM,IAAI,IAAI,OAAO","sourcesContent":["let validationEnabled = true;\n\n/**\n * Sets whether validators should run on the input, or if the input should be passed through.\n * @param enabled Whether validation should be done on inputs\n */\nexport function setGlobalValidationEnabled(enabled: boolean) {\n\tvalidationEnabled = enabled;\n}\n\n/**\n * @returns Whether validation is enabled\n */\nexport function getGlobalValidationEnabled() {\n\treturn validationEnabled;\n}\n","export class Result {\n\tpublic readonly success: boolean;\n\tpublic readonly value?: T;\n\tpublic readonly error?: E;\n\n\tprivate constructor(success: boolean, value?: T, error?: E) {\n\t\tthis.success = success;\n\t\tif (success) {\n\t\t\tthis.value = value;\n\t\t} else {\n\t\t\tthis.error = error;\n\t\t}\n\t}\n\n\tpublic isOk(): this is { success: true; value: T } {\n\t\treturn this.success;\n\t}\n\n\tpublic isErr(): this is { success: false; error: E } {\n\t\treturn !this.success;\n\t}\n\n\tpublic unwrap(): T {\n\t\tif (this.isOk()) return this.value;\n\t\tthrow this.error as Error;\n\t}\n\n\tpublic static ok(value: T): Result {\n\t\treturn new Result(true, value);\n\t}\n\n\tpublic static err(error: E): Result {\n\t\treturn new Result(false, undefined, error);\n\t}\n}\n","// https://github.com/microsoft/TypeScript/issues/37663\ntype Fn = (...args: unknown[]) => unknown;\n\nexport function getValue : T>(valueOrFn: T): U {\n\treturn typeof valueOrFn === 'function' ? valueOrFn() : valueOrFn;\n}\n","import get from 'lodash/get.js';\nimport { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { BaseValidator } from '../type-exports';\nimport type { IConstraint } from './type-exports';\n\nexport type ObjectConstraintName = `s.object(T.when)`;\n\nexport type WhenKey = PropertyKey | PropertyKey[];\n\nexport interface WhenOptions, Key extends WhenKey> {\n\tis?: boolean | ((value: Key extends Array ? any[] : any) => boolean);\n\tthen: (predicate: T) => T;\n\totherwise?: (predicate: T) => T;\n}\n\nexport function whenConstraint, I, Key extends WhenKey>(\n\tkey: Key,\n\toptions: WhenOptions,\n\tvalidator: T\n): IConstraint {\n\treturn {\n\t\trun(input: I, parent?: any) {\n\t\t\tif (!parent) {\n\t\t\t\treturn Result.err(new ExpectedConstraintError('s.object(T.when)', 'Validator has no parent', parent, 'Validator to have a parent'));\n\t\t\t}\n\n\t\t\tconst isKeyArray = Array.isArray(key);\n\n\t\t\tconst value = isKeyArray ? key.map((k) => get(parent, k)) : get(parent, key);\n\n\t\t\tconst predicate = resolveBooleanIs(options, value, isKeyArray) ? options.then : options.otherwise;\n\n\t\t\tif (predicate) {\n\t\t\t\treturn predicate(validator).run(input) as Result>;\n\t\t\t}\n\n\t\t\treturn Result.ok(input);\n\t\t}\n\t};\n}\n\nfunction resolveBooleanIs, Key extends WhenKey>(options: WhenOptions, value: any, isKeyArray: boolean) {\n\tif (options.is === undefined) {\n\t\treturn isKeyArray ? !value.some((val: any) => !val) : Boolean(value);\n\t}\n\n\tif (typeof options.is === 'function') {\n\t\treturn options.is(value);\n\t}\n\n\treturn value === options.is;\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { BaseConstraintError, type ConstraintErrorNames } from './BaseConstraintError';\n\nexport class ExpectedConstraintError extends BaseConstraintError {\n\tpublic readonly expected: string;\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: string) {\n\t\tsuper(constraint, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tconstraint: this.constraint,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst constraint = options.stylize(this.constraint, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ExpectedConstraintError: ${constraint}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ExpectedConstraintError', 'special')} > ${constraint}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected: ', 'string')}${options.stylize(this.expected, 'boolean')}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\n\nexport const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');\nexport const customInspectSymbolStackLess = Symbol.for('nodejs.util.inspect.custom.stack-less');\n\nexport abstract class BaseError extends Error {\n\tprotected [customInspectSymbol](depth: number, options: InspectOptionsStylized) {\n\t\treturn `${this[customInspectSymbolStackLess](depth, options)}\\n${this.stack!.slice(this.stack!.indexOf('\\n'))}`;\n\t}\n\n\tprotected abstract [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string;\n}\n","import type {\n\tArrayConstraintName,\n\tBigIntConstraintName,\n\tBooleanConstraintName,\n\tDateConstraintName,\n\tNumberConstraintName,\n\tObjectConstraintName,\n\tStringConstraintName,\n\tTypedArrayConstraintName\n} from '../../constraints/type-exports';\nimport { BaseError } from './BaseError';\n\nexport type ConstraintErrorNames =\n\t| TypedArrayConstraintName\n\t| ArrayConstraintName\n\t| BigIntConstraintName\n\t| BooleanConstraintName\n\t| DateConstraintName\n\t| NumberConstraintName\n\t| ObjectConstraintName\n\t| StringConstraintName;\n\nexport abstract class BaseConstraintError extends BaseError {\n\tpublic readonly constraint: ConstraintErrorNames;\n\tpublic readonly given: T;\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T) {\n\t\tsuper(message);\n\t\tthis.constraint = constraint;\n\t\tthis.given = given;\n\t}\n}\n","import { getGlobalValidationEnabled } from '../lib/configs';\nimport { Result } from '../lib/Result';\nimport { ArrayValidator, DefaultValidator, LiteralValidator, NullishValidator, SetValidator, UnionValidator } from './imports';\nimport { getValue } from './util/getValue';\nimport { whenConstraint, type WhenKey, type WhenOptions } from '../constraints/ObjectConstrains';\nimport type { CombinedError } from '../lib/errors/CombinedError';\nimport type { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport type { UnknownEnumValueError } from '../lib/errors/UnknownEnumValueError';\nimport type { ValidationError } from '../lib/errors/ValidationError';\nimport type { BaseConstraintError, InferResultType } from '../type-exports';\nimport type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\n\nexport abstract class BaseValidator {\n\tprotected parent?: object;\n\tprotected constraints: readonly IConstraint[] = [];\n\tprotected isValidationEnabled: boolean | (() => boolean) | null = null;\n\n\tpublic constructor(constraints: readonly IConstraint[] = []) {\n\t\tthis.constraints = constraints;\n\t}\n\n\tpublic setParent(parent: object): this {\n\t\tthis.parent = parent;\n\t\treturn this;\n\t}\n\n\tpublic get optional(): UnionValidator {\n\t\treturn new UnionValidator([new LiteralValidator(undefined), this.clone()]);\n\t}\n\n\tpublic get nullable(): UnionValidator {\n\t\treturn new UnionValidator([new LiteralValidator(null), this.clone()]);\n\t}\n\n\tpublic get nullish(): UnionValidator {\n\t\treturn new UnionValidator([new NullishValidator(), this.clone()]);\n\t}\n\n\tpublic get array(): ArrayValidator {\n\t\treturn new ArrayValidator(this.clone());\n\t}\n\n\tpublic get set(): SetValidator {\n\t\treturn new SetValidator(this.clone());\n\t}\n\n\tpublic or(...predicates: readonly BaseValidator[]): UnionValidator {\n\t\treturn new UnionValidator([this.clone(), ...predicates]);\n\t}\n\n\tpublic transform(cb: (value: T) => T): this;\n\tpublic transform(cb: (value: T) => O): BaseValidator;\n\tpublic transform(cb: (value: T) => O): BaseValidator {\n\t\treturn this.addConstraint({ run: (input) => Result.ok(cb(input) as unknown as T) }) as unknown as BaseValidator;\n\t}\n\n\tpublic reshape(cb: (input: T) => Result): this;\n\tpublic reshape, O = InferResultType>(cb: (input: T) => R): BaseValidator;\n\tpublic reshape, O = InferResultType>(cb: (input: T) => R): BaseValidator {\n\t\treturn this.addConstraint({ run: cb as unknown as (input: T) => Result> }) as unknown as BaseValidator;\n\t}\n\n\tpublic default(value: Exclude | (() => Exclude)): DefaultValidator> {\n\t\treturn new DefaultValidator(this.clone() as unknown as BaseValidator>, value);\n\t}\n\n\tpublic when = this>(key: Key, options: WhenOptions): this {\n\t\treturn this.addConstraint(whenConstraint(key, options, this as unknown as This));\n\t}\n\n\tpublic run(value: unknown): Result {\n\t\tlet result = this.handle(value) as Result;\n\t\tif (result.isErr()) return result;\n\n\t\tfor (const constraint of this.constraints) {\n\t\t\tresult = constraint.run(result.value as T, this.parent);\n\t\t\tif (result.isErr()) break;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic parse(value: unknown): R {\n\t\t// If validation is disabled (at the validator or global level), we only run the `handle` method, which will do some basic checks\n\t\t// (like that the input is a string for a string validator)\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn this.handle(value).unwrap() as R;\n\t\t}\n\n\t\treturn this.constraints.reduce((v, constraint) => constraint.run(v).unwrap(), this.handle(value).unwrap()) as R;\n\t}\n\n\tpublic is(value: unknown): value is R {\n\t\treturn this.run(value).isOk();\n\t}\n\n\t/**\n\t * Sets if the validator should also run constraints or just do basic checks.\n\t * @param isValidationEnabled Whether this validator should be enabled or disabled. You can pass boolean or a function returning boolean which will be called just before parsing.\n\t * Set to `null` to go off of the global configuration.\n\t */\n\tpublic setValidationEnabled(isValidationEnabled: boolean | (() => boolean) | null): this {\n\t\tconst clone = this.clone();\n\t\tclone.isValidationEnabled = isValidationEnabled;\n\t\treturn clone;\n\t}\n\n\tpublic getValidationEnabled() {\n\t\treturn getValue(this.isValidationEnabled);\n\t}\n\n\tprotected get shouldRunConstraints(): boolean {\n\t\treturn getValue(this.isValidationEnabled) ?? getGlobalValidationEnabled();\n\t}\n\n\tprotected clone(): this {\n\t\tconst clone: this = Reflect.construct(this.constructor, [this.constraints]);\n\t\tclone.isValidationEnabled = this.isValidationEnabled;\n\t\treturn clone;\n\t}\n\n\tprotected abstract handle(value: unknown): Result;\n\n\tprotected addConstraint(constraint: IConstraint): this {\n\t\tconst clone = this.clone();\n\t\tclone.constraints = clone.constraints.concat(constraint);\n\t\treturn clone;\n\t}\n}\n\nexport type ValidatorError = ValidationError | CombinedError | CombinedPropertyError | UnknownEnumValueError;\n","import fastDeepEqual from 'fast-deep-equal/es6/index.js';\nimport uniqWith from 'lodash/uniqWith.js';\n\nexport function isUnique(input: unknown[]) {\n\tif (input.length < 2) return true;\n\tconst uniqueArray = uniqWith(input, fastDeepEqual);\n\treturn uniqueArray.length === input.length;\n}\n","export function lessThan(a: number, b: number): boolean;\nexport function lessThan(a: bigint, b: bigint): boolean;\nexport function lessThan(a: number | bigint, b: number | bigint): boolean {\n\treturn a < b;\n}\n\nexport function lessThanOrEqual(a: number, b: number): boolean;\nexport function lessThanOrEqual(a: bigint, b: bigint): boolean;\nexport function lessThanOrEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a <= b;\n}\n\nexport function greaterThan(a: number, b: number): boolean;\nexport function greaterThan(a: bigint, b: bigint): boolean;\nexport function greaterThan(a: number | bigint, b: number | bigint): boolean {\n\treturn a > b;\n}\n\nexport function greaterThanOrEqual(a: number, b: number): boolean;\nexport function greaterThanOrEqual(a: bigint, b: bigint): boolean;\nexport function greaterThanOrEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a >= b;\n}\n\nexport function equal(a: number, b: number): boolean;\nexport function equal(a: bigint, b: bigint): boolean;\nexport function equal(a: number | bigint, b: number | bigint): boolean {\n\treturn a === b;\n}\n\nexport function notEqual(a: number, b: number): boolean;\nexport function notEqual(a: bigint, b: bigint): boolean;\nexport function notEqual(a: number | bigint, b: number | bigint): boolean {\n\treturn a !== b;\n}\n\nexport interface Comparator {\n\t(a: number, b: number): boolean;\n\t(a: bigint, b: bigint): boolean;\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { isUnique } from './util/isUnique';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type ArrayConstraintName = `s.array(T).${\n\t| 'unique'\n\t| `length${\n\t\t\t| 'LessThan'\n\t\t\t| 'LessThanOrEqual'\n\t\t\t| 'GreaterThan'\n\t\t\t| 'GreaterThanOrEqual'\n\t\t\t| 'Equal'\n\t\t\t| 'NotEqual'\n\t\t\t| 'Range'\n\t\t\t| 'RangeInclusive'\n\t\t\t| 'RangeExclusive'}`}`;\n\nfunction arrayLengthComparator(comparator: Comparator, name: ArrayConstraintName, expected: string, length: number): IConstraint {\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.length < ${value}`;\n\treturn arrayLengthComparator(lessThan, 's.array(T).lengthLessThan', expected, value);\n}\n\nexport function arrayLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length <= ${value}`;\n\treturn arrayLengthComparator(lessThanOrEqual, 's.array(T).lengthLessThanOrEqual', expected, value);\n}\n\nexport function arrayLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.length > ${value}`;\n\treturn arrayLengthComparator(greaterThan, 's.array(T).lengthGreaterThan', expected, value);\n}\n\nexport function arrayLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length >= ${value}`;\n\treturn arrayLengthComparator(greaterThanOrEqual, 's.array(T).lengthGreaterThanOrEqual', expected, value);\n}\n\nexport function arrayLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.length === ${value}`;\n\treturn arrayLengthComparator(equal, 's.array(T).lengthEqual', expected, value);\n}\n\nexport function arrayLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.length !== ${value}`;\n\treturn arrayLengthComparator(notEqual, 's.array(T).lengthNotEqual', expected, value);\n}\n\nexport function arrayLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length >= start && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRange', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthRangeInclusive(start: number, end: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length <= ${end}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length >= start && input.length <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRangeInclusive', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function arrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T[]) {\n\t\t\treturn input.length > startAfter && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).lengthRangeExclusive', 'Invalid Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport const uniqueArray: IConstraint = {\n\trun(input: unknown[]) {\n\t\treturn isUnique(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.array(T).unique', 'Array values are not unique', input, 'Expected all values to be unique'));\n\t}\n};\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class CombinedPropertyError extends BaseError {\n\tpublic readonly errors: [PropertyKey, BaseError][];\n\n\tpublic constructor(errors: [PropertyKey, BaseError][]) {\n\t\tsuper('Received one or more errors');\n\n\t\tthis.errors = errors;\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize('[CombinedPropertyError]', 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\n\t\tconst header = `${options.stylize('CombinedPropertyError', 'special')} (${options.stylize(this.errors.length.toString(), 'number')})`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst errors = this.errors\n\t\t\t.map(([key, error]) => {\n\t\t\t\tconst property = CombinedPropertyError.formatProperty(key, options);\n\t\t\t\tconst body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\\n/g, padding);\n\n\t\t\t\treturn ` input${property}${padding}${body}`;\n\t\t\t})\n\t\t\t.join('\\n\\n');\n\t\treturn `${header}\\n ${message}\\n\\n${errors}`;\n\t}\n\n\tprivate static formatProperty(key: PropertyKey, options: InspectOptionsStylized): string {\n\t\tif (typeof key === 'string') return options.stylize(`.${key}`, 'symbol');\n\t\tif (typeof key === 'number') return `[${options.stylize(key.toString(), 'number')}]`;\n\t\treturn `[${options.stylize('Symbol', 'symbol')}(${key.description})]`;\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class ValidationError extends BaseError {\n\tpublic readonly validator: string;\n\tpublic readonly given: unknown;\n\n\tpublic constructor(validator: string, message: string, given: unknown) {\n\t\tsuper(message);\n\n\t\tthis.validator = validator;\n\t\tthis.given = given;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalidator: this.validator,\n\t\t\tgiven: this.given\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst validator = options.stylize(this.validator, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ValidationError: ${validator}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ValidationError', 'special')} > ${validator}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${givenBlock}`;\n\t}\n}\n","import {\n\tarrayLengthEqual,\n\tarrayLengthGreaterThan,\n\tarrayLengthGreaterThanOrEqual,\n\tarrayLengthLessThan,\n\tarrayLengthLessThanOrEqual,\n\tarrayLengthNotEqual,\n\tarrayLengthRange,\n\tarrayLengthRangeExclusive,\n\tarrayLengthRangeInclusive,\n\tuniqueArray\n} from '../constraints/ArrayConstraints';\nimport type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport type { ExpandSmallerTuples, Tuple, UnshiftTuple } from '../lib/util-types';\nimport { BaseValidator } from './imports';\n\nexport class ArrayValidator extends BaseValidator {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tpublic lengthLessThan(length: N): ArrayValidator]>>> {\n\t\treturn this.addConstraint(arrayLengthLessThan(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthLessThanOrEqual(length: N): ArrayValidator]>> {\n\t\treturn this.addConstraint(arrayLengthLessThanOrEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthGreaterThan(length: N): ArrayValidator<[...Tuple, I, ...T]> {\n\t\treturn this.addConstraint(arrayLengthGreaterThan(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: N): ArrayValidator<[...Tuple, ...T]> {\n\t\treturn this.addConstraint(arrayLengthGreaterThanOrEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthEqual(length: N): ArrayValidator<[...Tuple]> {\n\t\treturn this.addConstraint(arrayLengthEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthNotEqual(length: number): ArrayValidator<[...T]> {\n\t\treturn this.addConstraint(arrayLengthNotEqual(length) as IConstraint) as any;\n\t}\n\n\tpublic lengthRange(\n\t\tstart: S,\n\t\tendBefore: E\n\t): ArrayValidator]>>, ExpandSmallerTuples]>>>> {\n\t\treturn this.addConstraint(arrayLengthRange(start, endBefore) as IConstraint) as any;\n\t}\n\n\tpublic lengthRangeInclusive(\n\t\tstartAt: S,\n\t\tendAt: E\n\t): ArrayValidator]>, ExpandSmallerTuples]>>>> {\n\t\treturn this.addConstraint(arrayLengthRangeInclusive(startAt, endAt) as IConstraint) as any;\n\t}\n\n\tpublic lengthRangeExclusive(\n\t\tstartAfter: S,\n\t\tendBefore: E\n\t): ArrayValidator]>>, ExpandSmallerTuples<[...Tuple]>>> {\n\t\treturn this.addConstraint(arrayLengthRangeExclusive(startAfter, endBefore) as IConstraint) as any;\n\t}\n\n\tpublic get unique(): this {\n\t\treturn this.addConstraint(uniqueArray as IConstraint);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result {\n\t\tif (!Array.isArray(values)) {\n\t\t\treturn Result.err(new ValidationError('s.array(T)', 'Expected an array', values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values as T);\n\t\t}\n\n\t\tconst errors: [number, BaseError][] = [];\n\t\tconst transformed: T = [] as unknown as T;\n\n\t\tfor (let i = 0; i < values.length; i++) {\n\t\t\tconst result = this.validator.run(values[i]);\n\t\t\tif (result.isOk()) transformed.push(result.value);\n\t\t\telse errors.push([i, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type BigIntConstraintName = `s.bigint.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'notEqual'\n\t| 'divisibleBy'}`;\n\nfunction bigintComparator(comparator: Comparator, name: BigIntConstraintName, expected: string, number: bigint): IConstraint {\n\treturn {\n\t\trun(input: bigint) {\n\t\t\treturn comparator(input, number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid bigint value', input, expected));\n\t\t}\n\t};\n}\n\nexport function bigintLessThan(value: bigint): IConstraint {\n\tconst expected = `expected < ${value}n`;\n\treturn bigintComparator(lessThan, 's.bigint.lessThan', expected, value);\n}\n\nexport function bigintLessThanOrEqual(value: bigint): IConstraint {\n\tconst expected = `expected <= ${value}n`;\n\treturn bigintComparator(lessThanOrEqual, 's.bigint.lessThanOrEqual', expected, value);\n}\n\nexport function bigintGreaterThan(value: bigint): IConstraint {\n\tconst expected = `expected > ${value}n`;\n\treturn bigintComparator(greaterThan, 's.bigint.greaterThan', expected, value);\n}\n\nexport function bigintGreaterThanOrEqual(value: bigint): IConstraint {\n\tconst expected = `expected >= ${value}n`;\n\treturn bigintComparator(greaterThanOrEqual, 's.bigint.greaterThanOrEqual', expected, value);\n}\n\nexport function bigintEqual(value: bigint): IConstraint {\n\tconst expected = `expected === ${value}n`;\n\treturn bigintComparator(equal, 's.bigint.equal', expected, value);\n}\n\nexport function bigintNotEqual(value: bigint): IConstraint {\n\tconst expected = `expected !== ${value}n`;\n\treturn bigintComparator(notEqual, 's.bigint.notEqual', expected, value);\n}\n\nexport function bigintDivisibleBy(divider: bigint): IConstraint {\n\tconst expected = `expected % ${divider}n === 0n`;\n\treturn {\n\t\trun(input: bigint) {\n\t\t\treturn input % divider === 0n //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.bigint.divisibleBy', 'BigInt is not divisible', input, expected));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tbigintDivisibleBy,\n\tbigintEqual,\n\tbigintGreaterThan,\n\tbigintGreaterThanOrEqual,\n\tbigintLessThan,\n\tbigintLessThanOrEqual,\n\tbigintNotEqual\n} from '../constraints/BigIntConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class BigIntValidator extends BaseValidator {\n\tpublic lessThan(number: bigint): this {\n\t\treturn this.addConstraint(bigintLessThan(number) as IConstraint);\n\t}\n\n\tpublic lessThanOrEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintLessThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic greaterThan(number: bigint): this {\n\t\treturn this.addConstraint(bigintGreaterThan(number) as IConstraint);\n\t}\n\n\tpublic greaterThanOrEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintGreaterThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic equal(number: N): BigIntValidator {\n\t\treturn this.addConstraint(bigintEqual(number) as IConstraint) as unknown as BigIntValidator;\n\t}\n\n\tpublic notEqual(number: bigint): this {\n\t\treturn this.addConstraint(bigintNotEqual(number) as IConstraint);\n\t}\n\n\tpublic get positive(): this {\n\t\treturn this.greaterThanOrEqual(0n);\n\t}\n\n\tpublic get negative(): this {\n\t\treturn this.lessThan(0n);\n\t}\n\n\tpublic divisibleBy(number: bigint): this {\n\t\treturn this.addConstraint(bigintDivisibleBy(number) as IConstraint);\n\t}\n\n\tpublic get abs(): this {\n\t\treturn this.transform((value) => (value < 0 ? -value : value) as T);\n\t}\n\n\tpublic intN(bits: number): this {\n\t\treturn this.transform((value) => BigInt.asIntN(bits, value) as T);\n\t}\n\n\tpublic uintN(bits: number): this {\n\t\treturn this.transform((value) => BigInt.asUintN(bits, value) as T);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'bigint' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.bigint', 'Expected a bigint primitive', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\n\nexport type BooleanConstraintName = `s.boolean.${boolean}`;\n\nexport const booleanTrue: IConstraint = {\n\trun(input: boolean) {\n\t\treturn input //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.boolean.true', 'Invalid boolean value', input, 'true'));\n\t}\n};\n\nexport const booleanFalse: IConstraint = {\n\trun(input: boolean) {\n\t\treturn input //\n\t\t\t? Result.err(new ExpectedConstraintError('s.boolean.false', 'Invalid boolean value', input, 'false'))\n\t\t\t: Result.ok(input);\n\t}\n};\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { booleanFalse, booleanTrue } from '../constraints/BooleanConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class BooleanValidator extends BaseValidator {\n\tpublic get true(): BooleanValidator {\n\t\treturn this.addConstraint(booleanTrue as IConstraint) as BooleanValidator;\n\t}\n\n\tpublic get false(): BooleanValidator {\n\t\treturn this.addConstraint(booleanFalse as IConstraint) as BooleanValidator;\n\t}\n\n\tpublic equal(value: R): BooleanValidator {\n\t\treturn (value ? this.true : this.false) as BooleanValidator;\n\t}\n\n\tpublic notEqual(value: R): BooleanValidator {\n\t\treturn (value ? this.false : this.true) as BooleanValidator;\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'boolean' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.boolean', 'Expected a boolean primitive', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type DateConstraintName = `s.date.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'notEqual'\n\t| 'valid'\n\t| 'invalid'}`;\n\nfunction dateComparator(comparator: Comparator, name: DateConstraintName, expected: string, number: number): IConstraint {\n\treturn {\n\t\trun(input: Date) {\n\t\t\treturn comparator(input.getTime(), number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Date value', input, expected));\n\t\t}\n\t};\n}\n\nexport function dateLessThan(value: Date): IConstraint {\n\tconst expected = `expected < ${value.toISOString()}`;\n\treturn dateComparator(lessThan, 's.date.lessThan', expected, value.getTime());\n}\n\nexport function dateLessThanOrEqual(value: Date): IConstraint {\n\tconst expected = `expected <= ${value.toISOString()}`;\n\treturn dateComparator(lessThanOrEqual, 's.date.lessThanOrEqual', expected, value.getTime());\n}\n\nexport function dateGreaterThan(value: Date): IConstraint {\n\tconst expected = `expected > ${value.toISOString()}`;\n\treturn dateComparator(greaterThan, 's.date.greaterThan', expected, value.getTime());\n}\n\nexport function dateGreaterThanOrEqual(value: Date): IConstraint {\n\tconst expected = `expected >= ${value.toISOString()}`;\n\treturn dateComparator(greaterThanOrEqual, 's.date.greaterThanOrEqual', expected, value.getTime());\n}\n\nexport function dateEqual(value: Date): IConstraint {\n\tconst expected = `expected === ${value.toISOString()}`;\n\treturn dateComparator(equal, 's.date.equal', expected, value.getTime());\n}\n\nexport function dateNotEqual(value: Date): IConstraint {\n\tconst expected = `expected !== ${value.toISOString()}`;\n\treturn dateComparator(notEqual, 's.date.notEqual', expected, value.getTime());\n}\n\nexport const dateInvalid: IConstraint = {\n\trun(input: Date) {\n\t\treturn Number.isNaN(input.getTime()) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.date.invalid', 'Invalid Date value', input, 'expected === NaN'));\n\t}\n};\n\nexport const dateValid: IConstraint = {\n\trun(input: Date) {\n\t\treturn Number.isNaN(input.getTime()) //\n\t\t\t? Result.err(new ExpectedConstraintError('s.date.valid', 'Invalid Date value', input, 'expected !== NaN'))\n\t\t\t: Result.ok(input);\n\t}\n};\n","import {\n\tdateEqual,\n\tdateGreaterThan,\n\tdateGreaterThanOrEqual,\n\tdateInvalid,\n\tdateLessThan,\n\tdateLessThanOrEqual,\n\tdateNotEqual,\n\tdateValid\n} from '../constraints/DateConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class DateValidator extends BaseValidator {\n\tpublic lessThan(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateLessThan(new Date(date)));\n\t}\n\n\tpublic lessThanOrEqual(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateLessThanOrEqual(new Date(date)));\n\t}\n\n\tpublic greaterThan(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateGreaterThan(new Date(date)));\n\t}\n\n\tpublic greaterThanOrEqual(date: Date | number | string): this {\n\t\treturn this.addConstraint(dateGreaterThanOrEqual(new Date(date)));\n\t}\n\n\tpublic equal(date: Date | number | string): this {\n\t\tconst resolved = new Date(date);\n\t\treturn Number.isNaN(resolved.getTime()) //\n\t\t\t? this.invalid\n\t\t\t: this.addConstraint(dateEqual(resolved));\n\t}\n\n\tpublic notEqual(date: Date | number | string): this {\n\t\tconst resolved = new Date(date);\n\t\treturn Number.isNaN(resolved.getTime()) //\n\t\t\t? this.valid\n\t\t\t: this.addConstraint(dateNotEqual(resolved));\n\t}\n\n\tpublic get valid(): this {\n\t\treturn this.addConstraint(dateValid);\n\t}\n\n\tpublic get invalid(): this {\n\t\treturn this.addConstraint(dateInvalid);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn value instanceof Date //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ValidationError('s.date', 'Expected a Date', value));\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { ValidationError } from './ValidationError';\n\nexport class ExpectedValidationError extends ValidationError {\n\tpublic readonly expected: T;\n\n\tpublic constructor(validator: string, message: string, given: unknown, expected: T) {\n\t\tsuper(validator, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic override toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalidator: this.validator,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst validator = options.stylize(this.validator, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[ExpectedValidationError: ${validator}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst expected = inspect(this.expected, newOptions).replace(/\\n/g, padding);\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('ExpectedValidationError', 'special')} > ${validator}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected:', 'string')}${padding}${expected}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { ExpectedValidationError } from '../lib/errors/ExpectedValidationError';\nimport { Result } from '../lib/Result';\nimport type { Constructor } from '../lib/util-types';\nimport { BaseValidator } from './imports';\n\nexport class InstanceValidator extends BaseValidator {\n\tpublic readonly expected: Constructor;\n\n\tpublic constructor(expected: Constructor, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.expected = expected;\n\t}\n\n\tprotected handle(value: unknown): Result>> {\n\t\treturn value instanceof this.expected //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ExpectedValidationError('s.instance(V)', 'Expected', value, this.expected));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.expected, this.constraints]);\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { ExpectedValidationError } from '../lib/errors/ExpectedValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class LiteralValidator extends BaseValidator {\n\tpublic readonly expected: T;\n\n\tpublic constructor(literal: T, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.expected = literal;\n\t}\n\n\tprotected handle(value: unknown): Result> {\n\t\treturn Object.is(value, this.expected) //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ExpectedValidationError('s.literal(V)', 'Expected values to be equals', value, this.expected));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.expected, this.constraints]);\n\t}\n}\n","import { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NeverValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn Result.err(new ValidationError('s.never', 'Expected a value to not be passed', value));\n\t}\n}\n","import { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NullishValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn value === undefined || value === null //\n\t\t\t? Result.ok(value)\n\t\t\t: Result.err(new ValidationError('s.nullish', 'Expected undefined or null', value));\n\t}\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\n\nexport type NumberConstraintName = `s.number.${\n\t| 'lessThan'\n\t| 'lessThanOrEqual'\n\t| 'greaterThan'\n\t| 'greaterThanOrEqual'\n\t| 'equal'\n\t| 'equal(NaN)'\n\t| 'notEqual'\n\t| 'notEqual(NaN)'\n\t| 'int'\n\t| 'safeInt'\n\t| 'finite'\n\t| 'divisibleBy'}`;\n\nfunction numberComparator(comparator: Comparator, name: NumberConstraintName, expected: string, number: number): IConstraint {\n\treturn {\n\t\trun(input: number) {\n\t\t\treturn comparator(input, number) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid number value', input, expected));\n\t\t}\n\t};\n}\n\nexport function numberLessThan(value: number): IConstraint {\n\tconst expected = `expected < ${value}`;\n\treturn numberComparator(lessThan, 's.number.lessThan', expected, value);\n}\n\nexport function numberLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected <= ${value}`;\n\treturn numberComparator(lessThanOrEqual, 's.number.lessThanOrEqual', expected, value);\n}\n\nexport function numberGreaterThan(value: number): IConstraint {\n\tconst expected = `expected > ${value}`;\n\treturn numberComparator(greaterThan, 's.number.greaterThan', expected, value);\n}\n\nexport function numberGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected >= ${value}`;\n\treturn numberComparator(greaterThanOrEqual, 's.number.greaterThanOrEqual', expected, value);\n}\n\nexport function numberEqual(value: number): IConstraint {\n\tconst expected = `expected === ${value}`;\n\treturn numberComparator(equal, 's.number.equal', expected, value);\n}\n\nexport function numberNotEqual(value: number): IConstraint {\n\tconst expected = `expected !== ${value}`;\n\treturn numberComparator(notEqual, 's.number.notEqual', expected, value);\n}\n\nexport const numberInt: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isInteger(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(\n\t\t\t\t\tnew ExpectedConstraintError('s.number.int', 'Given value is not an integer', input, 'Number.isInteger(expected) to be true')\n\t\t\t );\n\t}\n};\n\nexport const numberSafeInt: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isSafeInteger(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(\n\t\t\t\t\tnew ExpectedConstraintError(\n\t\t\t\t\t\t's.number.safeInt',\n\t\t\t\t\t\t'Given value is not a safe integer',\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\t'Number.isSafeInteger(expected) to be true'\n\t\t\t\t\t)\n\t\t\t );\n\t}\n};\n\nexport const numberFinite: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isFinite(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.number.finite', 'Given value is not finite', input, 'Number.isFinite(expected) to be true'));\n\t}\n};\n\nexport const numberNaN: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isNaN(input) //\n\t\t\t? Result.ok(input)\n\t\t\t: Result.err(new ExpectedConstraintError('s.number.equal(NaN)', 'Invalid number value', input, 'expected === NaN'));\n\t}\n};\n\nexport const numberNotNaN: IConstraint = {\n\trun(input: number) {\n\t\treturn Number.isNaN(input) //\n\t\t\t? Result.err(new ExpectedConstraintError('s.number.notEqual(NaN)', 'Invalid number value', input, 'expected !== NaN'))\n\t\t\t: Result.ok(input);\n\t}\n};\n\nexport function numberDivisibleBy(divider: number): IConstraint {\n\tconst expected = `expected % ${divider} === 0`;\n\treturn {\n\t\trun(input: number) {\n\t\t\treturn input % divider === 0 //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.number.divisibleBy', 'Number is not divisible', input, expected));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tnumberDivisibleBy,\n\tnumberEqual,\n\tnumberFinite,\n\tnumberGreaterThan,\n\tnumberGreaterThanOrEqual,\n\tnumberInt,\n\tnumberLessThan,\n\tnumberLessThanOrEqual,\n\tnumberNaN,\n\tnumberNotEqual,\n\tnumberNotNaN,\n\tnumberSafeInt\n} from '../constraints/NumberConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NumberValidator extends BaseValidator {\n\tpublic lessThan(number: number): this {\n\t\treturn this.addConstraint(numberLessThan(number) as IConstraint);\n\t}\n\n\tpublic lessThanOrEqual(number: number): this {\n\t\treturn this.addConstraint(numberLessThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic greaterThan(number: number): this {\n\t\treturn this.addConstraint(numberGreaterThan(number) as IConstraint);\n\t}\n\n\tpublic greaterThanOrEqual(number: number): this {\n\t\treturn this.addConstraint(numberGreaterThanOrEqual(number) as IConstraint);\n\t}\n\n\tpublic equal(number: N): NumberValidator {\n\t\treturn Number.isNaN(number) //\n\t\t\t? (this.addConstraint(numberNaN as IConstraint) as unknown as NumberValidator)\n\t\t\t: (this.addConstraint(numberEqual(number) as IConstraint) as unknown as NumberValidator);\n\t}\n\n\tpublic notEqual(number: number): this {\n\t\treturn Number.isNaN(number) //\n\t\t\t? this.addConstraint(numberNotNaN as IConstraint)\n\t\t\t: this.addConstraint(numberNotEqual(number) as IConstraint);\n\t}\n\n\tpublic get int(): this {\n\t\treturn this.addConstraint(numberInt as IConstraint);\n\t}\n\n\tpublic get safeInt(): this {\n\t\treturn this.addConstraint(numberSafeInt as IConstraint);\n\t}\n\n\tpublic get finite(): this {\n\t\treturn this.addConstraint(numberFinite as IConstraint);\n\t}\n\n\tpublic get positive(): this {\n\t\treturn this.greaterThanOrEqual(0);\n\t}\n\n\tpublic get negative(): this {\n\t\treturn this.lessThan(0);\n\t}\n\n\tpublic divisibleBy(divider: number): this {\n\t\treturn this.addConstraint(numberDivisibleBy(divider) as IConstraint);\n\t}\n\n\tpublic get abs(): this {\n\t\treturn this.transform(Math.abs as (value: number) => T);\n\t}\n\n\tpublic get sign(): this {\n\t\treturn this.transform(Math.sign as (value: number) => T);\n\t}\n\n\tpublic get trunc(): this {\n\t\treturn this.transform(Math.trunc as (value: number) => T);\n\t}\n\n\tpublic get floor(): this {\n\t\treturn this.transform(Math.floor as (value: number) => T);\n\t}\n\n\tpublic get fround(): this {\n\t\treturn this.transform(Math.fround as (value: number) => T);\n\t}\n\n\tpublic get round(): this {\n\t\treturn this.transform(Math.round as (value: number) => T);\n\t}\n\n\tpublic get ceil(): this {\n\t\treturn this.transform(Math.ceil as (value: number) => T);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'number' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.number', 'Expected a number primitive', value));\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class MissingPropertyError extends BaseError {\n\tpublic readonly property: PropertyKey;\n\n\tpublic constructor(property: PropertyKey) {\n\t\tsuper('A required property is missing');\n\t\tthis.property = property;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tproperty: this.property\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst property = options.stylize(this.property.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[MissingPropertyError: ${property}]`, 'special');\n\t\t}\n\n\t\tconst header = `${options.stylize('MissingPropertyError', 'special')} > ${property}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\treturn `${header}\\n ${message}`;\n\t}\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class UnknownPropertyError extends BaseError {\n\tpublic readonly property: PropertyKey;\n\tpublic readonly value: unknown;\n\n\tpublic constructor(property: PropertyKey, value: unknown) {\n\t\tsuper('Received unexpected property');\n\n\t\tthis.property = property;\n\t\tthis.value = value;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tproperty: this.property,\n\t\t\tvalue: this.value\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst property = options.stylize(this.property.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[UnknownPropertyError: ${property}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst given = inspect(this.value, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('UnknownPropertyError', 'special')} > ${property}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${givenBlock}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport { Result } from '../lib/Result';\nimport type { ValidatorError } from './BaseValidator';\nimport { BaseValidator } from './imports';\nimport { getValue } from './util/getValue';\n\nexport class DefaultValidator extends BaseValidator {\n\tprivate readonly validator: BaseValidator;\n\tprivate defaultValue: T | (() => T);\n\n\tpublic constructor(validator: BaseValidator, value: T | (() => T), constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t\tthis.defaultValue = value;\n\t}\n\n\tpublic override default(value: Exclude | (() => Exclude)): DefaultValidator> {\n\t\tconst clone = this.clone() as unknown as DefaultValidator>;\n\t\tclone.defaultValue = value;\n\t\treturn clone;\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'undefined' //\n\t\t\t? Result.ok(getValue(this.defaultValue))\n\t\t\t: this.validator['handle'](value); // eslint-disable-line @typescript-eslint/dot-notation\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.defaultValue, this.constraints]);\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class CombinedError extends BaseError {\n\tpublic readonly errors: readonly BaseError[];\n\n\tpublic constructor(errors: readonly BaseError[]) {\n\t\tsuper('Received one or more errors');\n\n\t\tthis.errors = errors;\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize('[CombinedError]', 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1, compact: true };\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\n\t\tconst header = `${options.stylize('CombinedError', 'special')} (${options.stylize(this.errors.length.toString(), 'number')})`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst errors = this.errors\n\t\t\t.map((error, i) => {\n\t\t\t\tconst index = options.stylize((i + 1).toString(), 'number');\n\t\t\t\tconst body = error[customInspectSymbolStackLess](depth - 1, newOptions).replace(/\\n/g, padding);\n\n\t\t\t\treturn ` ${index} ${body}`;\n\t\t\t})\n\t\t\t.join('\\n\\n');\n\t\treturn `${header}\\n ${message}\\n\\n${errors}`;\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedError } from '../lib/errors/CombinedError';\nimport type { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator, LiteralValidator, NullishValidator } from './imports';\n\nexport class UnionValidator extends BaseValidator {\n\tprivate validators: readonly BaseValidator[];\n\n\tpublic constructor(validators: readonly BaseValidator[], constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validators = validators;\n\t}\n\n\tpublic override get optional(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new LiteralValidator(undefined)], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already optional, return a clone:\n\t\t\tif (validator.expected === undefined) return this.clone();\n\n\t\t\t// If it's nullable, convert the nullable validator into a nullish validator to optimize `null | undefined`:\n\t\t\tif (validator.expected === null) {\n\t\t\t\treturn new UnionValidator(\n\t\t\t\t\t[new NullishValidator(), ...this.validators.slice(1)],\n\t\t\t\t\tthis.constraints\n\t\t\t\t) as UnionValidator;\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish (which validates optional), return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new LiteralValidator(undefined), ...this.validators]);\n\t}\n\n\tpublic get required(): UnionValidator> {\n\t\ttype RequiredValidator = UnionValidator>;\n\n\t\tif (this.validators.length === 0) return this.clone() as unknown as RequiredValidator;\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\tif (validator.expected === undefined) return new UnionValidator(this.validators.slice(1), this.constraints) as RequiredValidator;\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\treturn new UnionValidator([new LiteralValidator(null), ...this.validators.slice(1)], this.constraints) as RequiredValidator;\n\t\t}\n\n\t\treturn this.clone() as unknown as RequiredValidator;\n\t}\n\n\tpublic override get nullable(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new LiteralValidator(null)], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already nullable, return a clone:\n\t\t\tif (validator.expected === null) return this.clone();\n\n\t\t\t// If it's optional, convert the optional validator into a nullish validator to optimize `null | undefined`:\n\t\t\tif (validator.expected === undefined) {\n\t\t\t\treturn new UnionValidator(\n\t\t\t\t\t[new NullishValidator(), ...this.validators.slice(1)],\n\t\t\t\t\tthis.constraints\n\t\t\t\t) as UnionValidator;\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish (which validates nullable), return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new LiteralValidator(null), ...this.validators]);\n\t}\n\n\tpublic override get nullish(): UnionValidator {\n\t\tif (this.validators.length === 0) return new UnionValidator([new NullishValidator()], this.constraints);\n\n\t\tconst [validator] = this.validators;\n\t\tif (validator instanceof LiteralValidator) {\n\t\t\t// If already nullable or optional, promote the union to nullish:\n\t\t\tif (validator.expected === null || validator.expected === undefined) {\n\t\t\t\treturn new UnionValidator([new NullishValidator(), ...this.validators.slice(1)], this.constraints);\n\t\t\t}\n\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t// If it's already nullish, return a clone:\n\t\t\treturn this.clone();\n\t\t}\n\n\t\treturn new UnionValidator([new NullishValidator(), ...this.validators]);\n\t}\n\n\tpublic override or(...predicates: readonly BaseValidator[]): UnionValidator {\n\t\treturn new UnionValidator([...this.validators, ...predicates]);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validators, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\tconst errors: BaseError[] = [];\n\n\t\tfor (const validator of this.validators) {\n\t\t\tconst result = validator.run(value);\n\t\t\tif (result.isOk()) return result as Result;\n\t\t\terrors.push(result.error!);\n\t\t}\n\n\t\treturn Result.err(new CombinedError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { MissingPropertyError } from '../lib/errors/MissingPropertyError';\nimport { UnknownPropertyError } from '../lib/errors/UnknownPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport type { MappedObjectValidator, UndefinedToOptional } from '../lib/util-types';\nimport { BaseValidator } from './BaseValidator';\nimport { DefaultValidator } from './DefaultValidator';\nimport { LiteralValidator } from './LiteralValidator';\nimport { NullishValidator } from './NullishValidator';\nimport { UnionValidator } from './UnionValidator';\n\nexport class ObjectValidator> extends BaseValidator {\n\tpublic readonly shape: MappedObjectValidator;\n\tpublic readonly strategy: ObjectValidatorStrategy;\n\tprivate readonly keys: readonly (keyof I)[] = [];\n\tprivate readonly handleStrategy: (value: object) => Result;\n\n\tprivate readonly requiredKeys = new Map>();\n\tprivate readonly possiblyUndefinedKeys = new Map>();\n\tprivate readonly possiblyUndefinedKeysWithDefaults = new Map>();\n\n\tpublic constructor(\n\t\tshape: MappedObjectValidator,\n\t\tstrategy: ObjectValidatorStrategy = ObjectValidatorStrategy.Ignore,\n\t\tconstraints: readonly IConstraint[] = []\n\t) {\n\t\tsuper(constraints);\n\t\tthis.shape = shape;\n\t\tthis.strategy = strategy;\n\n\t\tswitch (this.strategy) {\n\t\t\tcase ObjectValidatorStrategy.Ignore:\n\t\t\t\tthis.handleStrategy = (value) => this.handleIgnoreStrategy(value);\n\t\t\t\tbreak;\n\t\t\tcase ObjectValidatorStrategy.Strict: {\n\t\t\t\tthis.handleStrategy = (value) => this.handleStrictStrategy(value);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase ObjectValidatorStrategy.Passthrough:\n\t\t\t\tthis.handleStrategy = (value) => this.handlePassthroughStrategy(value);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst shapeEntries = Object.entries(shape) as [keyof I, BaseValidator][];\n\t\tthis.keys = shapeEntries.map(([key]) => key);\n\n\t\tfor (const [key, validator] of shapeEntries) {\n\t\t\tif (validator instanceof UnionValidator) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\t\t\tconst [possiblyLiteralOrNullishPredicate] = validator['validators'];\n\n\t\t\t\tif (possiblyLiteralOrNullishPredicate instanceof NullishValidator) {\n\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t} else if (possiblyLiteralOrNullishPredicate instanceof LiteralValidator) {\n\t\t\t\t\tif (possiblyLiteralOrNullishPredicate.expected === undefined) {\n\t\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t\t}\n\t\t\t\t} else if (validator instanceof DefaultValidator) {\n\t\t\t\t\tthis.possiblyUndefinedKeysWithDefaults.set(key, validator);\n\t\t\t\t} else {\n\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t}\n\t\t\t} else if (validator instanceof NullishValidator) {\n\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t} else if (validator instanceof LiteralValidator) {\n\t\t\t\tif (validator.expected === undefined) {\n\t\t\t\t\tthis.possiblyUndefinedKeys.set(key, validator);\n\t\t\t\t} else {\n\t\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t\t}\n\t\t\t} else if (validator instanceof DefaultValidator) {\n\t\t\t\tthis.possiblyUndefinedKeysWithDefaults.set(key, validator);\n\t\t\t} else {\n\t\t\t\tthis.requiredKeys.set(key, validator);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic get strict(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Strict, this.constraints]);\n\t}\n\n\tpublic get ignore(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Ignore, this.constraints]);\n\t}\n\n\tpublic get passthrough(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, ObjectValidatorStrategy.Passthrough, this.constraints]);\n\t}\n\n\tpublic get partial(): ObjectValidator<{ [Key in keyof I]?: I[Key] }> {\n\t\tconst shape = Object.fromEntries(this.keys.map((key) => [key, this.shape[key as unknown as keyof typeof this.shape].optional]));\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic get required(): ObjectValidator<{ [Key in keyof I]-?: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tthis.keys.map((key) => {\n\t\t\t\tlet validator = this.shape[key as unknown as keyof typeof this.shape];\n\t\t\t\tif (validator instanceof UnionValidator) validator = validator.required;\n\t\t\t\treturn [key, validator];\n\t\t\t})\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic extend(schema: ObjectValidator | MappedObjectValidator): ObjectValidator {\n\t\tconst shape = { ...this.shape, ...(schema instanceof ObjectValidator ? schema.shape : schema) };\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic pick(keys: readonly K[]): ObjectValidator<{ [Key in keyof Pick]: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tkeys.filter((key) => this.keys.includes(key)).map((key) => [key, this.shape[key as unknown as keyof typeof this.shape]])\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tpublic omit(keys: readonly K[]): ObjectValidator<{ [Key in keyof Omit]: I[Key] }> {\n\t\tconst shape = Object.fromEntries(\n\t\t\tthis.keys.filter((key) => !keys.includes(key as any)).map((key) => [key, this.shape[key as unknown as keyof typeof this.shape]])\n\t\t);\n\t\treturn Reflect.construct(this.constructor, [shape, this.strategy, this.constraints]);\n\t}\n\n\tprotected override handle(value: unknown): Result {\n\t\tconst typeOfValue = typeof value;\n\t\tif (typeOfValue !== 'object') {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', `Expected the value to be an object, but received ${typeOfValue} instead`, value));\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', 'Expected the value to not be null', value));\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\treturn Result.err(new ValidationError('s.object(T)', 'Expected the value to not be an array', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value as I);\n\t\t}\n\n\t\tfor (const predicate of Object.values(this.shape) as BaseValidator[]) {\n\t\t\tpredicate.setParent(this.parent ?? value!);\n\t\t}\n\n\t\treturn this.handleStrategy(value as object);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.shape, this.strategy, this.constraints]);\n\t}\n\n\tprivate handleIgnoreStrategy(value: object): Result {\n\t\tconst errors: [PropertyKey, BaseError][] = [];\n\t\tconst finalObject = {} as I;\n\t\tconst inputEntries = new Map(Object.entries(value) as [keyof I, unknown][]);\n\n\t\tconst runPredicate = (key: keyof I, predicate: BaseValidator) => {\n\t\t\tconst result = predicate.run(value[key as keyof object]);\n\n\t\t\tif (result.isOk()) {\n\t\t\t\tfinalObject[key] = result.value as I[keyof I];\n\t\t\t} else {\n\t\t\t\tconst error = result.error!;\n\t\t\t\terrors.push([key, error]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [key, predicate] of this.requiredKeys) {\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t} else {\n\t\t\t\terrors.push([key, new MissingPropertyError(key)]);\n\t\t\t}\n\t\t}\n\n\t\t// Run possibly undefined keys that also have defaults even if there are no more keys to process (this is necessary so we fill in those defaults)\n\t\tfor (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) {\n\t\t\tinputEntries.delete(key);\n\t\t\trunPredicate(key, validator);\n\t\t}\n\n\t\t// Early exit if there are no more properties to validate in the object and there are errors to report\n\t\tif (inputEntries.size === 0) {\n\t\t\treturn errors.length === 0 //\n\t\t\t\t? Result.ok(finalObject)\n\t\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t\t}\n\n\t\t// In the event the remaining keys to check are less than the number of possible undefined keys, we check those\n\t\t// as it could yield a faster execution\n\t\tconst checkInputEntriesInsteadOfSchemaKeys = this.possiblyUndefinedKeys.size > inputEntries.size;\n\n\t\tif (checkInputEntriesInsteadOfSchemaKeys) {\n\t\t\tfor (const [key] of inputEntries) {\n\t\t\t\tconst predicate = this.possiblyUndefinedKeys.get(key);\n\n\t\t\t\tif (predicate) {\n\t\t\t\t\trunPredicate(key, predicate);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const [key, predicate] of this.possiblyUndefinedKeys) {\n\t\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\t\trunPredicate(key, predicate);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(finalObject)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n\n\tprivate handleStrictStrategy(value: object): Result {\n\t\tconst errors: [PropertyKey, BaseError][] = [];\n\t\tconst finalResult = {} as I;\n\t\tconst inputEntries = new Map(Object.entries(value) as [keyof I, unknown][]);\n\n\t\tconst runPredicate = (key: keyof I, predicate: BaseValidator) => {\n\t\t\tconst result = predicate.run(value[key as keyof object]);\n\n\t\t\tif (result.isOk()) {\n\t\t\t\tfinalResult[key] = result.value as I[keyof I];\n\t\t\t} else {\n\t\t\t\tconst error = result.error!;\n\t\t\t\terrors.push([key, error]);\n\t\t\t}\n\t\t};\n\n\t\tfor (const [key, predicate] of this.requiredKeys) {\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t} else {\n\t\t\t\terrors.push([key, new MissingPropertyError(key)]);\n\t\t\t}\n\t\t}\n\n\t\t// Run possibly undefined keys that also have defaults even if there are no more keys to process (this is necessary so we fill in those defaults)\n\t\tfor (const [key, validator] of this.possiblyUndefinedKeysWithDefaults) {\n\t\t\tinputEntries.delete(key);\n\t\t\trunPredicate(key, validator);\n\t\t}\n\n\t\tfor (const [key, predicate] of this.possiblyUndefinedKeys) {\n\t\t\t// All of these validators are assumed to be possibly undefined, so if we have gone through the entire object and there's still validators,\n\t\t\t// safe to assume we're done here\n\t\t\tif (inputEntries.size === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (inputEntries.delete(key)) {\n\t\t\t\trunPredicate(key, predicate);\n\t\t\t}\n\t\t}\n\n\t\tif (inputEntries.size !== 0) {\n\t\t\tfor (const [key, value] of inputEntries.entries()) {\n\t\t\t\terrors.push([key, new UnknownPropertyError(key, value)]);\n\t\t\t}\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(finalResult)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n\n\tprivate handlePassthroughStrategy(value: object): Result {\n\t\tconst result = this.handleIgnoreStrategy(value);\n\t\treturn result.isErr() ? result : Result.ok({ ...value, ...result.value } as I);\n\t}\n}\n\nexport const enum ObjectValidatorStrategy {\n\tIgnore,\n\tStrict,\n\tPassthrough\n}\n","import type { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class PassthroughValidator extends BaseValidator {\n\tprotected handle(value: unknown): Result {\n\t\treturn Result.ok(value as T);\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class RecordValidator extends BaseValidator> {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result, ValidationError | CombinedPropertyError> {\n\t\tif (typeof value !== 'object') {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected an object', value));\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected the value to not be null', value));\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\treturn Result.err(new ValidationError('s.record(T)', 'Expected the value to not be an array', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value as Record);\n\t\t}\n\n\t\tconst errors: [string, BaseError][] = [];\n\t\tconst transformed: Record = {};\n\n\t\tfor (const [key, val] of Object.entries(value!)) {\n\t\t\tconst result = this.validator.run(val);\n\t\t\tif (result.isOk()) transformed[key] = result.value;\n\t\t\telse errors.push([key, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedError } from '../lib/errors/CombinedError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class SetValidator extends BaseValidator> {\n\tprivate readonly validator: BaseValidator;\n\n\tpublic constructor(validator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result, ValidationError | CombinedError> {\n\t\tif (!(values instanceof Set)) {\n\t\t\treturn Result.err(new ValidationError('s.set(T)', 'Expected a set', values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values);\n\t\t}\n\n\t\tconst errors: BaseError[] = [];\n\t\tconst transformed = new Set();\n\n\t\tfor (const value of values) {\n\t\t\tconst result = this.validator.run(value);\n\t\t\tif (result.isOk()) transformed.add(result.value);\n\t\t\telse errors.push(result.error!);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedError(errors));\n\t}\n}\n","/**\n * [RFC-5322](https://datatracker.ietf.org/doc/html/rfc5322)\n * compliant {@link RegExp} to validate an email address\n *\n * @see https://stackoverflow.com/questions/201323/how-can-i-validate-an-email-address-using-a-regular-expression/201378#201378\n */\nconst accountRegex =\n\t/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")$/;\n\n/**\n * Validates an email address string based on various checks:\n * - It must be a non nullish and non empty string\n * - It must include at least an `@` symbol`\n * - The account name may not exceed 64 characters\n * - The domain name may not exceed 255 characters\n * - The domain must include at least one `.` symbol\n * - Each part of the domain, split by `.` must not exceed 63 characters\n * - The email address must be [RFC-5322](https://datatracker.ietf.org/doc/html/rfc5322) compliant\n * @param email The email to validate\n * @returns `true` if the email is valid, `false` otherwise\n *\n * @remark Based on the following sources:\n * - `email-validator` by [manisharaan](https://github.com/manishsaraan) ([code](https://github.com/manishsaraan/email-validator/blob/master/index.js))\n * - [Comparing E-mail Address Validating Regular Expressions](http://fightingforalostcause.net/misc/2006/compare-email-regex.php)\n * - [Validating Email Addresses by Derrick Pallas](http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx)\n * - [StackOverflow answer by bortzmeyer](http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378)\n * - [The wikipedia page on Email addresses](https://en.wikipedia.org/wiki/Email_address)\n */\nexport function validateEmail(email: string): boolean {\n\t// 1. Non-nullish and non-empty string check.\n\t//\n\t// If a nullish or empty email was provided then do an early exit\n\tif (!email) return false;\n\n\t// Find the location of the @ symbol:\n\tconst atIndex = email.indexOf('@');\n\n\t// 2. @ presence check.\n\t//\n\t// If the email does not have the @ symbol, it's automatically invalid:\n\tif (atIndex === -1) return false;\n\n\t// 3. maximum length check.\n\t//\n\t// From @, if exceeds 64 characters, then the\n\t// position of the @ symbol is 64 or greater. In this case, the email is\n\t// invalid:\n\tif (atIndex > 64) return false;\n\n\tconst domainIndex = atIndex + 1;\n\n\t// 7.1. Duplicated @ symbol check.\n\t//\n\t// If there's a second @ symbol, the email is automatically invalid:\n\tif (email.includes('@', domainIndex)) return false;\n\n\t// 4. maximum length check.\n\t//\n\t// From @, if exceeds 255 characters, then it\n\t// means that the amount of characters between the start of and the\n\t// end of the string is separated by 255 or more characters.\n\tif (email.length - domainIndex > 255) return false;\n\n\t// Find the location of the . symbol in :\n\tlet dotIndex = email.indexOf('.', domainIndex);\n\n\t// 5. dot (.) symbol check.\n\t//\n\t// From @, if does not contain a dot (.) symbol,\n\t// then it means the domain is invalid.\n\tif (dotIndex === -1) return false;\n\n\t// 6. parts length.\n\t//\n\t// Assign a temporary variable to store the start of the last read domain\n\t// part, this would be at the start of .\n\t//\n\t// For a part to be correct, it must have at most, 63 characters.\n\t// We repeat this step for every sub-section of contained within\n\t// dot (.) symbols.\n\t//\n\t// The following step is a more optimized version of the following code:\n\t//\n\t// ```javascript\n\t// domain.split('.').some((part) => part.length > 63);\n\t// ```\n\tlet lastDotIndex = domainIndex;\n\tdo {\n\t\tif (dotIndex - lastDotIndex > 63) return false;\n\n\t\tlastDotIndex = dotIndex + 1;\n\t} while ((dotIndex = email.indexOf('.', lastDotIndex)) !== -1);\n\n\t// The loop iterates from the first to the n - 1 part, this line checks for\n\t// the last (n) part:\n\tif (email.length - lastDotIndex > 63) return false;\n\n\t// 7.2. Character checks.\n\t//\n\t// From @:\n\t// - Extract the part by slicing the input from start to the @\n\t// character. Validate afterwards.\n\t// - Extract the part by slicing the input from the start of\n\t// . Validate afterwards.\n\t//\n\t// Note: we inline the variables so isn't created unless the\n\t// check passes.\n\treturn accountRegex.test(email.slice(0, atIndex)) && validateEmailDomain(email.slice(domainIndex));\n}\n\nfunction validateEmailDomain(domain: string): boolean {\n\ttry {\n\t\treturn new URL(`http://${domain}`).hostname === domain;\n\t} catch {\n\t\treturn false;\n\t}\n}\n","/**\n * Code ported from https://github.com/nodejs/node/blob/5fad0b93667ffc6e4def52996b9529ac99b26319/lib/internal/net.js\n */\n\n// IPv4 Segment\nconst v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';\nconst v4Str = `(${v4Seg}[.]){3}${v4Seg}`;\nconst IPv4Reg = new RegExp(`^${v4Str}$`);\n\n// IPv6 Segment\nconst v6Seg = '(?:[0-9a-fA-F]{1,4})';\nconst IPv6Reg = new RegExp(\n\t'^(' +\n\t\t`(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +\n\t\t`(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +\n\t\t`(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +\n\t\t`(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +\n\t\t`(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +\n\t\t`(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +\n\t\t`(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +\n\t\t`(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +\n\t\t')(%[0-9a-zA-Z-.:]{1,})?$'\n);\n\nexport function isIPv4(s: string): boolean {\n\treturn IPv4Reg.test(s);\n}\n\nexport function isIPv6(s: string): boolean {\n\treturn IPv6Reg.test(s);\n}\n\nexport function isIP(s: string): number {\n\tif (isIPv4(s)) return 4;\n\tif (isIPv6(s)) return 6;\n\treturn 0;\n}\n","export const phoneNumberRegex = /^((?:\\+|0{0,2})\\d{1,2}\\s?)?\\(?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}$/;\n\nexport function validatePhoneNumber(input: string) {\n\treturn phoneNumberRegex.test(input);\n}\n","import { inspect, type InspectOptionsStylized } from 'node:util';\nimport { customInspectSymbolStackLess } from './BaseError';\nimport { BaseConstraintError, type ConstraintErrorNames } from './BaseConstraintError';\n\nexport class MultiplePossibilitiesConstraintError extends BaseConstraintError {\n\tpublic readonly expected: readonly string[];\n\n\tpublic constructor(constraint: ConstraintErrorNames, message: string, given: T, expected: readonly string[]) {\n\t\tsuper(constraint, message, given);\n\t\tthis.expected = expected;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tconstraint: this.constraint,\n\t\t\tgiven: this.given,\n\t\t\texpected: this.expected\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst constraint = options.stylize(this.constraint, 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[MultiplePossibilitiesConstraintError: ${constraint}]`, 'special');\n\t\t}\n\n\t\tconst newOptions = { ...options, depth: options.depth === null ? null : options.depth! - 1 };\n\n\t\tconst verticalLine = options.stylize('|', 'undefined');\n\t\tconst padding = `\\n ${verticalLine} `;\n\t\tconst given = inspect(this.given, newOptions).replace(/\\n/g, padding);\n\n\t\tconst header = `${options.stylize('MultiplePossibilitiesConstraintError', 'special')} > ${constraint}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\n\t\tconst expectedPadding = `\\n ${verticalLine} - `;\n\t\tconst expectedBlock = `\\n ${options.stylize('Expected any of the following:', 'string')}${expectedPadding}${this.expected\n\t\t\t.map((possible) => options.stylize(possible, 'boolean'))\n\t\t\t.join(expectedPadding)}`;\n\t\tconst givenBlock = `\\n ${options.stylize('Received:', 'regexp')}${padding}${given}`;\n\t\treturn `${header}\\n ${message}\\n${expectedBlock}\\n${givenBlock}`;\n\t}\n}\n","export function combinedErrorFn

(...fns: ErrorFn[]): ErrorFn {\n\tswitch (fns.length) {\n\t\tcase 0:\n\t\t\treturn () => null;\n\t\tcase 1:\n\t\t\treturn fns[0];\n\t\tcase 2: {\n\t\t\tconst [fn0, fn1] = fns;\n\t\t\treturn (...params) => fn0(...params) || fn1(...params);\n\t\t}\n\t\tdefault: {\n\t\t\treturn (...params) => {\n\t\t\t\tfor (const fn of fns) {\n\t\t\t\t\tconst result = fn(...params);\n\t\t\t\t\tif (result) return result;\n\t\t\t\t}\n\n\t\t\t\treturn null;\n\t\t\t};\n\t\t}\n\t}\n}\n\nexport type ErrorFn

= (...params: P) => E | null;\n","import { MultiplePossibilitiesConstraintError } from '../../lib/errors/MultiplePossibilitiesConstraintError';\nimport { combinedErrorFn, ErrorFn } from './common/combinedResultFn';\n\nexport type StringProtocol = `${string}:`;\n\nexport type StringDomain = `${string}.${string}`;\n\nexport interface UrlOptions {\n\tallowedProtocols?: StringProtocol[];\n\tallowedDomains?: StringDomain[];\n}\n\nexport function createUrlValidators(options?: UrlOptions) {\n\tconst fns: ErrorFn<[input: string, url: URL], MultiplePossibilitiesConstraintError>[] = [];\n\n\tif (options?.allowedProtocols?.length) fns.push(allowedProtocolsFn(options.allowedProtocols));\n\tif (options?.allowedDomains?.length) fns.push(allowedDomainsFn(options.allowedDomains));\n\n\treturn combinedErrorFn(...fns);\n}\n\nfunction allowedProtocolsFn(allowedProtocols: StringProtocol[]) {\n\treturn (input: string, url: URL) =>\n\t\tallowedProtocols.includes(url.protocol as StringProtocol)\n\t\t\t? null\n\t\t\t: new MultiplePossibilitiesConstraintError('s.string.url', 'Invalid URL protocol', input, allowedProtocols);\n}\n\nfunction allowedDomainsFn(allowedDomains: StringDomain[]) {\n\treturn (input: string, url: URL) =>\n\t\tallowedDomains.includes(url.hostname as StringDomain)\n\t\t\t? null\n\t\t\t: new MultiplePossibilitiesConstraintError('s.string.url', 'Invalid URL domain', input, allowedDomains);\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { validateEmail } from './util/emailValidator';\nimport { isIP, isIPv4, isIPv6 } from './util/net';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\nimport { validatePhoneNumber } from './util/phoneValidator';\nimport { createUrlValidators } from './util/urlValidators';\n\nexport type StringConstraintName =\n\t| `s.string.${\n\t\t\t| `length${'LessThan' | 'LessThanOrEqual' | 'GreaterThan' | 'GreaterThanOrEqual' | 'Equal' | 'NotEqual'}`\n\t\t\t| 'regex'\n\t\t\t| 'url'\n\t\t\t| 'uuid'\n\t\t\t| 'email'\n\t\t\t| `ip${'v4' | 'v6' | ''}`\n\t\t\t| 'date'\n\t\t\t| 'phone'}`;\n\nexport type StringProtocol = `${string}:`;\n\nexport type StringDomain = `${string}.${string}`;\n\nexport interface UrlOptions {\n\tallowedProtocols?: StringProtocol[];\n\tallowedDomains?: StringDomain[];\n}\n\nexport type UUIDVersion = 1 | 3 | 4 | 5;\n\nexport interface StringUuidOptions {\n\tversion?: UUIDVersion | `${UUIDVersion}-${UUIDVersion}` | null;\n\tnullable?: boolean;\n}\n\nfunction stringLengthComparator(comparator: Comparator, name: StringConstraintName, expected: string, length: number): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid string length', input, expected));\n\t\t}\n\t};\n}\n\nexport function stringLengthLessThan(length: number): IConstraint {\n\tconst expected = `expected.length < ${length}`;\n\treturn stringLengthComparator(lessThan, 's.string.lengthLessThan', expected, length);\n}\n\nexport function stringLengthLessThanOrEqual(length: number): IConstraint {\n\tconst expected = `expected.length <= ${length}`;\n\treturn stringLengthComparator(lessThanOrEqual, 's.string.lengthLessThanOrEqual', expected, length);\n}\n\nexport function stringLengthGreaterThan(length: number): IConstraint {\n\tconst expected = `expected.length > ${length}`;\n\treturn stringLengthComparator(greaterThan, 's.string.lengthGreaterThan', expected, length);\n}\n\nexport function stringLengthGreaterThanOrEqual(length: number): IConstraint {\n\tconst expected = `expected.length >= ${length}`;\n\treturn stringLengthComparator(greaterThanOrEqual, 's.string.lengthGreaterThanOrEqual', expected, length);\n}\n\nexport function stringLengthEqual(length: number): IConstraint {\n\tconst expected = `expected.length === ${length}`;\n\treturn stringLengthComparator(equal, 's.string.lengthEqual', expected, length);\n}\n\nexport function stringLengthNotEqual(length: number): IConstraint {\n\tconst expected = `expected.length !== ${length}`;\n\treturn stringLengthComparator(notEqual, 's.string.lengthNotEqual', expected, length);\n}\n\nexport function stringEmail(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validateEmail(input)\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.string.email', 'Invalid email address', input, 'expected to be an email address'));\n\t\t}\n\t};\n}\n\nfunction stringRegexValidator(type: StringConstraintName, expected: string, regex: RegExp): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn regex.test(input) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(type, 'Invalid string format', input, expected));\n\t\t}\n\t};\n}\n\nexport function stringUrl(options?: UrlOptions): IConstraint {\n\tconst validatorFn = createUrlValidators(options);\n\treturn {\n\t\trun(input: string) {\n\t\t\tlet url: URL;\n\t\t\ttry {\n\t\t\t\turl = new URL(input);\n\t\t\t} catch {\n\t\t\t\treturn Result.err(new ExpectedConstraintError('s.string.url', 'Invalid URL', input, 'expected to match an URL'));\n\t\t\t}\n\n\t\t\tconst validatorFnResult = validatorFn(input, url);\n\t\t\tif (validatorFnResult === null) return Result.ok(input);\n\t\t\treturn Result.err(validatorFnResult);\n\t\t}\n\t};\n}\n\nexport function stringIp(version?: 4 | 6): IConstraint {\n\tconst ipVersion = version ? (`v${version}` as const) : '';\n\tconst validatorFn = version === 4 ? isIPv4 : version === 6 ? isIPv6 : isIP;\n\n\tconst name = `s.string.ip${ipVersion}` as const;\n\tconst message = `Invalid IP${ipVersion} address`;\n\tconst expected = `expected to be an IP${ipVersion} address`;\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validatorFn(input) ? Result.ok(input) : Result.err(new ExpectedConstraintError(name, message, input, expected));\n\t\t}\n\t};\n}\n\nexport function stringRegex(regex: RegExp) {\n\treturn stringRegexValidator('s.string.regex', `expected ${regex}.test(expected) to be true`, regex);\n}\n\nexport function stringUuid({ version = 4, nullable = false }: StringUuidOptions = {}) {\n\tversion ??= '1-5';\n\tconst regex = new RegExp(\n\t\t`^(?:[0-9A-F]{8}-[0-9A-F]{4}-[${version}][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}${\n\t\t\tnullable ? '|00000000-0000-0000-0000-000000000000' : ''\n\t\t})$`,\n\t\t'i'\n\t);\n\tconst expected = `expected to match UUID${typeof version === 'number' ? `v${version}` : ` in range of ${version}`}`;\n\treturn stringRegexValidator('s.string.uuid', expected, regex);\n}\n\nexport function stringDate(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\tconst time = Date.parse(input);\n\n\t\t\treturn Number.isNaN(time)\n\t\t\t\t? Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError(\n\t\t\t\t\t\t\t's.string.date',\n\t\t\t\t\t\t\t'Invalid date string',\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t'expected to be a valid date string (in the ISO 8601 or ECMA-262 format)'\n\t\t\t\t\t\t)\n\t\t\t\t )\n\t\t\t\t: Result.ok(input);\n\t\t}\n\t};\n}\n\nexport function stringPhone(): IConstraint {\n\treturn {\n\t\trun(input: string) {\n\t\t\treturn validatePhoneNumber(input)\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.string.phone', 'Invalid phone number', input, 'expected to be a phone number'));\n\t\t}\n\t};\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\tstringDate,\n\tstringEmail,\n\tstringIp,\n\tstringLengthEqual,\n\tstringLengthGreaterThan,\n\tstringLengthGreaterThanOrEqual,\n\tstringLengthLessThan,\n\tstringLengthLessThanOrEqual,\n\tstringLengthNotEqual,\n\tstringPhone,\n\tstringRegex,\n\tstringUrl,\n\tstringUuid,\n\tStringUuidOptions,\n\ttype UrlOptions\n} from '../constraints/StringConstraints';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class StringValidator extends BaseValidator {\n\tpublic lengthLessThan(length: number): this {\n\t\treturn this.addConstraint(stringLengthLessThan(length) as IConstraint);\n\t}\n\n\tpublic lengthLessThanOrEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthLessThanOrEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthGreaterThan(length: number): this {\n\t\treturn this.addConstraint(stringLengthGreaterThan(length) as IConstraint);\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthGreaterThanOrEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthEqual(length) as IConstraint);\n\t}\n\n\tpublic lengthNotEqual(length: number): this {\n\t\treturn this.addConstraint(stringLengthNotEqual(length) as IConstraint);\n\t}\n\n\tpublic get email(): this {\n\t\treturn this.addConstraint(stringEmail() as IConstraint);\n\t}\n\n\tpublic url(options?: UrlOptions): this {\n\t\treturn this.addConstraint(stringUrl(options) as IConstraint);\n\t}\n\n\tpublic uuid(options?: StringUuidOptions): this {\n\t\treturn this.addConstraint(stringUuid(options) as IConstraint);\n\t}\n\n\tpublic regex(regex: RegExp): this {\n\t\treturn this.addConstraint(stringRegex(regex) as IConstraint);\n\t}\n\n\tpublic get date() {\n\t\treturn this.addConstraint(stringDate() as IConstraint);\n\t}\n\n\tpublic get ipv4(): this {\n\t\treturn this.ip(4);\n\t}\n\n\tpublic get ipv6(): this {\n\t\treturn this.ip(6);\n\t}\n\n\tpublic ip(version?: 4 | 6): this {\n\t\treturn this.addConstraint(stringIp(version) as IConstraint);\n\t}\n\n\tpublic phone(): this {\n\t\treturn this.addConstraint(stringPhone() as IConstraint);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn typeof value === 'string' //\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.string', 'Expected a string primitive', value));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class TupleValidator extends BaseValidator<[...T]> {\n\tprivate readonly validators: BaseValidator<[...T]>[] = [];\n\n\tpublic constructor(validators: BaseValidator<[...T]>[], constraints: readonly IConstraint<[...T]>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validators = validators;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validators, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result<[...T], ValidationError | CombinedPropertyError> {\n\t\tif (!Array.isArray(values)) {\n\t\t\treturn Result.err(new ValidationError('s.tuple(T)', 'Expected an array', values));\n\t\t}\n\n\t\tif (values.length !== this.validators.length) {\n\t\t\treturn Result.err(new ValidationError('s.tuple(T)', `Expected an array of length ${this.validators.length}`, values));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(values as [...T]);\n\t\t}\n\n\t\tconst errors: [number, BaseError][] = [];\n\t\tconst transformed: T = [] as unknown as T;\n\n\t\tfor (let i = 0; i < values.length; i++) {\n\t\t\tconst result = this.validators[i].run(values[i]);\n\t\t\tif (result.isOk()) transformed.push(result.value);\n\t\t\telse errors.push([i, result.error!]);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport type { BaseError } from '../lib/errors/BaseError';\nimport { CombinedPropertyError } from '../lib/errors/CombinedPropertyError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class MapValidator extends BaseValidator> {\n\tprivate readonly keyValidator: BaseValidator;\n\tprivate readonly valueValidator: BaseValidator;\n\n\tpublic constructor(keyValidator: BaseValidator, valueValidator: BaseValidator, constraints: readonly IConstraint>[] = []) {\n\t\tsuper(constraints);\n\t\tthis.keyValidator = keyValidator;\n\t\tthis.valueValidator = valueValidator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.keyValidator, this.valueValidator, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result, ValidationError | CombinedPropertyError> {\n\t\tif (!(value instanceof Map)) {\n\t\t\treturn Result.err(new ValidationError('s.map(K, V)', 'Expected a map', value));\n\t\t}\n\n\t\tif (!this.shouldRunConstraints) {\n\t\t\treturn Result.ok(value);\n\t\t}\n\n\t\tconst errors: [string, BaseError][] = [];\n\t\tconst transformed = new Map();\n\n\t\tfor (const [key, val] of value.entries()) {\n\t\t\tconst keyResult = this.keyValidator.run(key);\n\t\t\tconst valueResult = this.valueValidator.run(val);\n\t\t\tconst { length } = errors;\n\t\t\tif (keyResult.isErr()) errors.push([key, keyResult.error]);\n\t\t\tif (valueResult.isErr()) errors.push([key, valueResult.error]);\n\t\t\tif (errors.length === length) transformed.set(keyResult.value!, valueResult.value!);\n\t\t}\n\n\t\treturn errors.length === 0 //\n\t\t\t? Result.ok(transformed)\n\t\t\t: Result.err(new CombinedPropertyError(errors));\n\t}\n}\n","import type { Result } from '../lib/Result';\nimport type { IConstraint, Unwrap } from '../type-exports';\nimport { BaseValidator, ValidatorError } from './imports';\n\nexport class LazyValidator, R = Unwrap> extends BaseValidator {\n\tprivate readonly validator: (value: unknown) => T;\n\n\tpublic constructor(validator: (value: unknown) => T, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.validator = validator;\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.validator, this.constraints]);\n\t}\n\n\tprotected handle(values: unknown): Result {\n\t\treturn this.validator(values).run(values) as Result;\n\t}\n}\n","import type { InspectOptionsStylized } from 'node:util';\nimport { BaseError, customInspectSymbolStackLess } from './BaseError';\n\nexport class UnknownEnumValueError extends BaseError {\n\tpublic readonly value: string | number;\n\tpublic readonly enumKeys: string[];\n\tpublic readonly enumMappings: Map;\n\n\tpublic constructor(value: string | number, keys: string[], enumMappings: Map) {\n\t\tsuper('Expected the value to be one of the following enum values:');\n\n\t\tthis.value = value;\n\t\tthis.enumKeys = keys;\n\t\tthis.enumMappings = enumMappings;\n\t}\n\n\tpublic toJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tvalue: this.value,\n\t\t\tenumKeys: this.enumKeys,\n\t\t\tenumMappings: [...this.enumMappings.entries()]\n\t\t};\n\t}\n\n\tprotected [customInspectSymbolStackLess](depth: number, options: InspectOptionsStylized): string {\n\t\tconst value = options.stylize(this.value.toString(), 'string');\n\t\tif (depth < 0) {\n\t\t\treturn options.stylize(`[UnknownEnumValueError: ${value}]`, 'special');\n\t\t}\n\n\t\tconst padding = `\\n ${options.stylize('|', 'undefined')} `;\n\t\tconst pairs = this.enumKeys\n\t\t\t.map((key) => {\n\t\t\t\tconst enumValue = this.enumMappings.get(key)!;\n\t\t\t\treturn `${options.stylize(key, 'string')} or ${options.stylize(\n\t\t\t\t\tenumValue.toString(),\n\t\t\t\t\ttypeof enumValue === 'number' ? 'number' : 'string'\n\t\t\t\t)}`;\n\t\t\t})\n\t\t\t.join(padding);\n\n\t\tconst header = `${options.stylize('UnknownEnumValueError', 'special')} > ${value}`;\n\t\tconst message = options.stylize(this.message, 'regexp');\n\t\tconst pairsBlock = `${padding}${pairs}`;\n\t\treturn `${header}\\n ${message}\\n${pairsBlock}`;\n\t}\n}\n","import { UnknownEnumValueError } from '../lib/errors/UnknownEnumValueError';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class NativeEnumValidator extends BaseValidator {\n\tpublic readonly enumShape: T;\n\tpublic readonly hasNumericElements: boolean = false;\n\tprivate readonly enumKeys: string[];\n\tprivate readonly enumMapping = new Map();\n\n\tpublic constructor(enumShape: T) {\n\t\tsuper();\n\t\tthis.enumShape = enumShape;\n\n\t\tthis.enumKeys = Object.keys(enumShape).filter((key) => {\n\t\t\treturn typeof enumShape[enumShape[key]] !== 'number';\n\t\t});\n\n\t\tfor (const key of this.enumKeys) {\n\t\t\tconst enumValue = enumShape[key] as T[keyof T];\n\n\t\t\tthis.enumMapping.set(key, enumValue);\n\t\t\tthis.enumMapping.set(enumValue, enumValue);\n\n\t\t\tif (typeof enumValue === 'number') {\n\t\t\t\tthis.hasNumericElements = true;\n\t\t\t\tthis.enumMapping.set(`${enumValue}`, enumValue);\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected override handle(value: unknown): Result {\n\t\tconst typeOfValue = typeof value;\n\n\t\tif (typeOfValue === 'number') {\n\t\t\tif (!this.hasNumericElements) {\n\t\t\t\treturn Result.err(new ValidationError('s.nativeEnum(T)', 'Expected the value to be a string', value));\n\t\t\t}\n\t\t} else if (typeOfValue !== 'string') {\n\t\t\t// typeOfValue !== 'number' is implied here\n\t\t\treturn Result.err(new ValidationError('s.nativeEnum(T)', 'Expected the value to be a string or number', value));\n\t\t}\n\n\t\tconst casted = value as string | number;\n\n\t\tconst possibleEnumValue = this.enumMapping.get(casted);\n\n\t\treturn typeof possibleEnumValue === 'undefined'\n\t\t\t? Result.err(new UnknownEnumValueError(casted, this.enumKeys, this.enumMapping))\n\t\t\t: Result.ok(possibleEnumValue);\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.enumShape]);\n\t}\n}\n\nexport interface NativeEnumLike {\n\t[key: string]: string | number;\n\t[key: number]: string;\n}\n","import { ExpectedConstraintError } from '../lib/errors/ExpectedConstraintError';\nimport { Result } from '../lib/Result';\nimport type { IConstraint } from './base/IConstraint';\nimport { Comparator, equal, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, notEqual } from './util/operators';\nimport type { TypedArray } from './util/typedArray';\n\nexport type TypedArrayConstraintName = `s.typedArray(T).${'byteLength' | 'length'}${\n\t| 'LessThan'\n\t| 'LessThanOrEqual'\n\t| 'GreaterThan'\n\t| 'GreaterThanOrEqual'\n\t| 'Equal'\n\t| 'NotEqual'\n\t| 'Range'\n\t| 'RangeInclusive'\n\t| 'RangeExclusive'}`;\n\nfunction typedArrayByteLengthComparator(\n\tcomparator: Comparator,\n\tname: TypedArrayConstraintName,\n\texpected: string,\n\tlength: number\n): IConstraint {\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn comparator(input.byteLength, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Typed Array byte length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.byteLength < ${value}`;\n\treturn typedArrayByteLengthComparator(lessThan, 's.typedArray(T).byteLengthLessThan', expected, value);\n}\n\nexport function typedArrayByteLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength <= ${value}`;\n\treturn typedArrayByteLengthComparator(lessThanOrEqual, 's.typedArray(T).byteLengthLessThanOrEqual', expected, value);\n}\n\nexport function typedArrayByteLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.byteLength > ${value}`;\n\treturn typedArrayByteLengthComparator(greaterThan, 's.typedArray(T).byteLengthGreaterThan', expected, value);\n}\n\nexport function typedArrayByteLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength >= ${value}`;\n\treturn typedArrayByteLengthComparator(greaterThanOrEqual, 's.typedArray(T).byteLengthGreaterThanOrEqual', expected, value);\n}\n\nexport function typedArrayByteLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength === ${value}`;\n\treturn typedArrayByteLengthComparator(equal, 's.typedArray(T).byteLengthEqual', expected, value);\n}\n\nexport function typedArrayByteLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.byteLength !== ${value}`;\n\treturn typedArrayByteLengthComparator(notEqual, 's.typedArray(T).byteLengthNotEqual', expected, value);\n}\n\nexport function typedArrayByteLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.byteLength >= ${start} && expected.byteLength < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength >= start && input.byteLength < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).byteLengthRange', 'Invalid Typed Array byte length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthRangeInclusive(start: number, end: number) {\n\tconst expected = `expected.byteLength >= ${start} && expected.byteLength <= ${end}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength >= start && input.byteLength <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError('s.typedArray(T).byteLengthRangeInclusive', 'Invalid Typed Array byte length', input, expected)\n\t\t\t\t );\n\t\t}\n\t};\n}\n\nexport function typedArrayByteLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.byteLength > ${startAfter} && expected.byteLength < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.byteLength > startAfter && input.byteLength < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(\n\t\t\t\t\t\tnew ExpectedConstraintError('s.typedArray(T).byteLengthRangeExclusive', 'Invalid Typed Array byte length', input, expected)\n\t\t\t\t );\n\t\t}\n\t};\n}\n\nfunction typedArrayLengthComparator(\n\tcomparator: Comparator,\n\tname: TypedArrayConstraintName,\n\texpected: string,\n\tlength: number\n): IConstraint {\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn comparator(input.length, length) //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError(name, 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthLessThan(value: number): IConstraint {\n\tconst expected = `expected.length < ${value}`;\n\treturn typedArrayLengthComparator(lessThan, 's.typedArray(T).lengthLessThan', expected, value);\n}\n\nexport function typedArrayLengthLessThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length <= ${value}`;\n\treturn typedArrayLengthComparator(lessThanOrEqual, 's.typedArray(T).lengthLessThanOrEqual', expected, value);\n}\n\nexport function typedArrayLengthGreaterThan(value: number): IConstraint {\n\tconst expected = `expected.length > ${value}`;\n\treturn typedArrayLengthComparator(greaterThan, 's.typedArray(T).lengthGreaterThan', expected, value);\n}\n\nexport function typedArrayLengthGreaterThanOrEqual(value: number): IConstraint {\n\tconst expected = `expected.length >= ${value}`;\n\treturn typedArrayLengthComparator(greaterThanOrEqual, 's.typedArray(T).lengthGreaterThanOrEqual', expected, value);\n}\n\nexport function typedArrayLengthEqual(value: number): IConstraint {\n\tconst expected = `expected.length === ${value}`;\n\treturn typedArrayLengthComparator(equal, 's.typedArray(T).lengthEqual', expected, value);\n}\n\nexport function typedArrayLengthNotEqual(value: number): IConstraint {\n\tconst expected = `expected.length !== ${value}`;\n\treturn typedArrayLengthComparator(notEqual, 's.typedArray(T).lengthNotEqual', expected, value);\n}\n\nexport function typedArrayLengthRange(start: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length >= start && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRange', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthRangeInclusive(start: number, end: number): IConstraint {\n\tconst expected = `expected.length >= ${start} && expected.length <= ${end}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length >= start && input.length <= end //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRangeInclusive', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n\nexport function typedArrayLengthRangeExclusive(startAfter: number, endBefore: number): IConstraint {\n\tconst expected = `expected.length > ${startAfter} && expected.length < ${endBefore}`;\n\treturn {\n\t\trun(input: T) {\n\t\t\treturn input.length > startAfter && input.length < endBefore //\n\t\t\t\t? Result.ok(input)\n\t\t\t\t: Result.err(new ExpectedConstraintError('s.typedArray(T).lengthRangeExclusive', 'Invalid Typed Array length', input, expected));\n\t\t}\n\t};\n}\n","const vowels = ['a', 'e', 'i', 'o', 'u'];\n\nexport const aOrAn = (word: string) => {\n\treturn `${vowels.includes(word[0].toLowerCase()) ? 'an' : 'a'} ${word}`;\n};\n","export type TypedArray =\n\t| Int8Array\n\t| Uint8Array\n\t| Uint8ClampedArray\n\t| Int16Array\n\t| Uint16Array\n\t| Int32Array\n\t| Uint32Array\n\t| Float32Array\n\t| Float64Array\n\t| BigInt64Array\n\t| BigUint64Array;\n\nexport const TypedArrays = {\n\tInt8Array: (x: unknown): x is Int8Array => x instanceof Int8Array,\n\tUint8Array: (x: unknown): x is Uint8Array => x instanceof Uint8Array,\n\tUint8ClampedArray: (x: unknown): x is Uint8ClampedArray => x instanceof Uint8ClampedArray,\n\tInt16Array: (x: unknown): x is Int16Array => x instanceof Int16Array,\n\tUint16Array: (x: unknown): x is Uint16Array => x instanceof Uint16Array,\n\tInt32Array: (x: unknown): x is Int32Array => x instanceof Int32Array,\n\tUint32Array: (x: unknown): x is Uint32Array => x instanceof Uint32Array,\n\tFloat32Array: (x: unknown): x is Float32Array => x instanceof Float32Array,\n\tFloat64Array: (x: unknown): x is Float64Array => x instanceof Float64Array,\n\tBigInt64Array: (x: unknown): x is BigInt64Array => x instanceof BigInt64Array,\n\tBigUint64Array: (x: unknown): x is BigUint64Array => x instanceof BigUint64Array,\n\tTypedArray: (x: unknown): x is TypedArray => ArrayBuffer.isView(x) && !(x instanceof DataView)\n} as const;\n\nexport type TypedArrayName = keyof typeof TypedArrays;\n","import type { IConstraint } from '../constraints/base/IConstraint';\nimport {\n\ttypedArrayByteLengthEqual,\n\ttypedArrayByteLengthGreaterThan,\n\ttypedArrayByteLengthGreaterThanOrEqual,\n\ttypedArrayByteLengthLessThan,\n\ttypedArrayByteLengthLessThanOrEqual,\n\ttypedArrayByteLengthNotEqual,\n\ttypedArrayByteLengthRange,\n\ttypedArrayByteLengthRangeExclusive,\n\ttypedArrayByteLengthRangeInclusive,\n\ttypedArrayLengthEqual,\n\ttypedArrayLengthGreaterThan,\n\ttypedArrayLengthGreaterThanOrEqual,\n\ttypedArrayLengthLessThan,\n\ttypedArrayLengthLessThanOrEqual,\n\ttypedArrayLengthNotEqual,\n\ttypedArrayLengthRange,\n\ttypedArrayLengthRangeExclusive,\n\ttypedArrayLengthRangeInclusive\n} from '../constraints/TypedArrayLengthConstraints';\nimport { aOrAn } from '../constraints/util/common/vowels';\nimport { TypedArray, TypedArrayName, TypedArrays } from '../constraints/util/typedArray';\nimport { ValidationError } from '../lib/errors/ValidationError';\nimport { Result } from '../lib/Result';\nimport { BaseValidator } from './imports';\n\nexport class TypedArrayValidator extends BaseValidator {\n\tprivate readonly type: TypedArrayName;\n\n\tpublic constructor(type: TypedArrayName, constraints: readonly IConstraint[] = []) {\n\t\tsuper(constraints);\n\t\tthis.type = type;\n\t}\n\n\tpublic byteLengthLessThan(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthLessThan(length));\n\t}\n\n\tpublic byteLengthLessThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthLessThanOrEqual(length));\n\t}\n\n\tpublic byteLengthGreaterThan(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthGreaterThan(length));\n\t}\n\n\tpublic byteLengthGreaterThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthGreaterThanOrEqual(length));\n\t}\n\n\tpublic byteLengthEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthEqual(length));\n\t}\n\n\tpublic byteLengthNotEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthNotEqual(length));\n\t}\n\n\tpublic byteLengthRange(start: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRange(start, endBefore));\n\t}\n\n\tpublic byteLengthRangeInclusive(startAt: number, endAt: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRangeInclusive(startAt, endAt) as IConstraint);\n\t}\n\n\tpublic byteLengthRangeExclusive(startAfter: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayByteLengthRangeExclusive(startAfter, endBefore));\n\t}\n\n\tpublic lengthLessThan(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthLessThan(length));\n\t}\n\n\tpublic lengthLessThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthLessThanOrEqual(length));\n\t}\n\n\tpublic lengthGreaterThan(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthGreaterThan(length));\n\t}\n\n\tpublic lengthGreaterThanOrEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthGreaterThanOrEqual(length));\n\t}\n\n\tpublic lengthEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthEqual(length));\n\t}\n\n\tpublic lengthNotEqual(length: number) {\n\t\treturn this.addConstraint(typedArrayLengthNotEqual(length));\n\t}\n\n\tpublic lengthRange(start: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayLengthRange(start, endBefore));\n\t}\n\n\tpublic lengthRangeInclusive(startAt: number, endAt: number) {\n\t\treturn this.addConstraint(typedArrayLengthRangeInclusive(startAt, endAt));\n\t}\n\n\tpublic lengthRangeExclusive(startAfter: number, endBefore: number) {\n\t\treturn this.addConstraint(typedArrayLengthRangeExclusive(startAfter, endBefore));\n\t}\n\n\tprotected override clone(): this {\n\t\treturn Reflect.construct(this.constructor, [this.type, this.constraints]);\n\t}\n\n\tprotected handle(value: unknown): Result {\n\t\treturn TypedArrays[this.type](value)\n\t\t\t? Result.ok(value as T)\n\t\t\t: Result.err(new ValidationError('s.typedArray', `Expected ${aOrAn(this.type)}`, value));\n\t}\n}\n","import type { TypedArray, TypedArrayName } from '../constraints/util/typedArray';\nimport type { Unwrap, UnwrapTuple } from '../lib/util-types';\nimport {\n\tArrayValidator,\n\tBaseValidator,\n\tBigIntValidator,\n\tBooleanValidator,\n\tDateValidator,\n\tInstanceValidator,\n\tLiteralValidator,\n\tMapValidator,\n\tNeverValidator,\n\tNullishValidator,\n\tNumberValidator,\n\tObjectValidator,\n\tPassthroughValidator,\n\tRecordValidator,\n\tSetValidator,\n\tStringValidator,\n\tTupleValidator,\n\tUnionValidator\n} from '../validators/imports';\nimport { LazyValidator } from '../validators/LazyValidator';\nimport { NativeEnumLike, NativeEnumValidator } from '../validators/NativeEnumValidator';\nimport { TypedArrayValidator } from '../validators/TypedArrayValidator';\nimport type { Constructor, MappedObjectValidator } from './util-types';\n\nexport class Shapes {\n\tpublic get string() {\n\t\treturn new StringValidator();\n\t}\n\n\tpublic get number() {\n\t\treturn new NumberValidator();\n\t}\n\n\tpublic get bigint() {\n\t\treturn new BigIntValidator();\n\t}\n\n\tpublic get boolean() {\n\t\treturn new BooleanValidator();\n\t}\n\n\tpublic get date() {\n\t\treturn new DateValidator();\n\t}\n\n\tpublic object(shape: MappedObjectValidator) {\n\t\treturn new ObjectValidator(shape);\n\t}\n\n\tpublic get undefined() {\n\t\treturn this.literal(undefined);\n\t}\n\n\tpublic get null() {\n\t\treturn this.literal(null);\n\t}\n\n\tpublic get nullish() {\n\t\treturn new NullishValidator();\n\t}\n\n\tpublic get any() {\n\t\treturn new PassthroughValidator();\n\t}\n\n\tpublic get unknown() {\n\t\treturn new PassthroughValidator();\n\t}\n\n\tpublic get never() {\n\t\treturn new NeverValidator();\n\t}\n\n\tpublic enum(...values: readonly T[]) {\n\t\treturn this.union(...values.map((value) => this.literal(value)));\n\t}\n\n\tpublic nativeEnum(enumShape: T): NativeEnumValidator {\n\t\treturn new NativeEnumValidator(enumShape);\n\t}\n\n\tpublic literal(value: T): BaseValidator {\n\t\tif (value instanceof Date) return this.date.equal(value) as unknown as BaseValidator;\n\t\treturn new LiteralValidator(value);\n\t}\n\n\tpublic instance(expected: Constructor): InstanceValidator {\n\t\treturn new InstanceValidator(expected);\n\t}\n\n\tpublic union[]]>(...validators: [...T]): UnionValidator> {\n\t\treturn new UnionValidator(validators);\n\t}\n\n\tpublic array(validator: BaseValidator): ArrayValidator;\n\tpublic array(validator: BaseValidator): ArrayValidator;\n\tpublic array(validator: BaseValidator) {\n\t\treturn new ArrayValidator(validator);\n\t}\n\n\tpublic typedArray(type: TypedArrayName = 'TypedArray') {\n\t\treturn new TypedArrayValidator(type);\n\t}\n\n\tpublic get int8Array() {\n\t\treturn this.typedArray('Int8Array');\n\t}\n\n\tpublic get uint8Array() {\n\t\treturn this.typedArray('Uint8Array');\n\t}\n\n\tpublic get uint8ClampedArray() {\n\t\treturn this.typedArray('Uint8ClampedArray');\n\t}\n\n\tpublic get int16Array() {\n\t\treturn this.typedArray('Int16Array');\n\t}\n\n\tpublic get uint16Array() {\n\t\treturn this.typedArray('Uint16Array');\n\t}\n\n\tpublic get int32Array() {\n\t\treturn this.typedArray('Int32Array');\n\t}\n\n\tpublic get uint32Array() {\n\t\treturn this.typedArray('Uint32Array');\n\t}\n\n\tpublic get float32Array() {\n\t\treturn this.typedArray('Float32Array');\n\t}\n\n\tpublic get float64Array() {\n\t\treturn this.typedArray('Float64Array');\n\t}\n\n\tpublic get bigInt64Array() {\n\t\treturn this.typedArray('BigInt64Array');\n\t}\n\n\tpublic get bigUint64Array() {\n\t\treturn this.typedArray('BigUint64Array');\n\t}\n\n\tpublic tuple[]]>(validators: [...T]): TupleValidator> {\n\t\treturn new TupleValidator(validators);\n\t}\n\n\tpublic set(validator: BaseValidator) {\n\t\treturn new SetValidator(validator);\n\t}\n\n\tpublic record(validator: BaseValidator) {\n\t\treturn new RecordValidator(validator);\n\t}\n\n\tpublic map(keyValidator: BaseValidator, valueValidator: BaseValidator) {\n\t\treturn new MapValidator(keyValidator, valueValidator);\n\t}\n\n\tpublic lazy>(validator: (value: unknown) => T) {\n\t\treturn new LazyValidator(validator);\n\t}\n}\n","import { Shapes } from './lib/Shapes';\n\nexport const s = new Shapes();\n\nexport * from './lib/configs';\nexport * from './lib/errors/BaseError';\nexport * from './lib/errors/CombinedError';\nexport * from './lib/errors/CombinedPropertyError';\nexport * from './lib/errors/ExpectedConstraintError';\nexport * from './lib/errors/ExpectedValidationError';\nexport * from './lib/errors/MissingPropertyError';\nexport * from './lib/errors/MultiplePossibilitiesConstraintError';\nexport * from './lib/errors/UnknownEnumValueError';\nexport * from './lib/errors/UnknownPropertyError';\nexport * from './lib/errors/ValidationError';\nexport * from './lib/Result';\nexport * from './type-exports';\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/shapeshift/package.json b/node_modules/@sapphire/shapeshift/package.json new file mode 100644 index 0000000..85012f9 --- /dev/null +++ b/node_modules/@sapphire/shapeshift/package.json @@ -0,0 +1,127 @@ +{ + "name": "@sapphire/shapeshift", + "version": "3.8.1", + "description": "Blazing fast input validation and transformation ⚡", + "author": "@sapphire", + "license": "MIT", + "main": "dist/index.js", + "module": "dist/index.mjs", + "browser": "dist/index.global.js", + "unpkg": "dist/index.global.js", + "types": "dist/index.d.ts", + "exports": { + "import": "./dist/index.mjs", + "require": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "sideEffects": false, + "homepage": "https://www.sapphirejs.dev", + "scripts": { + "lint": "eslint src tests --ext ts --fix", + "format": "prettier --write \"{src,tests}/**/*.ts\"", + "docs": "typedoc-json-parser", + "test": "vitest run", + "test:watch": "vitest", + "update": "yarn upgrade-interactive", + "build": "tsup", + "clean": "node scripts/clean.mjs", + "typecheck": "tsc -p tsconfig.eslint.json", + "bump": "cliff-jumper", + "check-update": "cliff-jumper --dry-run", + "_postinstall": "husky install .github/husky", + "prepack": "yarn build && pinst --disable", + "postpack": "pinst --enable" + }, + "devDependencies": { + "@commitlint/cli": "^17.3.0", + "@commitlint/config-conventional": "^17.3.0", + "@favware/cliff-jumper": "^1.9.0", + "@favware/npm-deprecate": "^1.0.7", + "@sapphire/eslint-config": "^4.3.8", + "@sapphire/prettier-config": "^1.4.4", + "@sapphire/ts-config": "^3.3.4", + "@types/jsdom": "^20.0.1", + "@types/lodash": "^4.14.191", + "@types/node": "^18.11.13", + "@typescript-eslint/eslint-plugin": "^5.46.0", + "@typescript-eslint/parser": "^5.46.0", + "@vitest/coverage-c8": "^0.25.7", + "cz-conventional-changelog": "^3.3.0", + "esbuild-plugins-node-modules-polyfill": "^1.0.7", + "eslint": "^8.29.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-prettier": "^4.2.1", + "husky": "^8.0.2", + "jsdom": "^20.0.3", + "lint-staged": "^13.1.0", + "pinst": "^3.0.0", + "prettier": "^2.8.1", + "pretty-quick": "^3.1.3", + "ts-node": "^10.9.1", + "tsup": "^6.5.0", + "typedoc": "^0.23.22", + "typedoc-json-parser": "^7.0.2", + "typescript": "^4.9.4", + "vite": "^4.0.0", + "vitest": "^0.25.7" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sapphiredev/shapeshift.git" + }, + "files": [ + "dist/**/*.js*", + "dist/**/*.mjs*", + "dist/**/*.d*" + ], + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + }, + "keywords": [ + "@sapphire/shapeshift", + "shapeshift", + "bot", + "typescript", + "ts", + "yarn", + "sapphire", + "schema", + "validation", + "type-checking", + "checking", + "input-validation", + "runtime-validation", + "ow", + "type-validation", + "zod" + ], + "bugs": { + "url": "https://github.com/sapphiredev/shapeshift/issues" + }, + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "lint-staged": { + "*.{mjs,js,ts}": "eslint --fix --ext mjs,js,ts" + }, + "config": { + "commitizen": { + "path": "./node_modules/cz-conventional-changelog" + } + }, + "publishConfig": { + "access": "public" + }, + "resolutions": { + "ansi-regex": "^5.0.1", + "minimist": "^1.2.7" + }, + "packageManager": "yarn@3.3.0", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + } +} \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/CHANGELOG.md b/node_modules/@sapphire/snowflake/CHANGELOG.md new file mode 100644 index 0000000..42792aa --- /dev/null +++ b/node_modules/@sapphire/snowflake/CHANGELOG.md @@ -0,0 +1,263 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@sapphire/snowflake@3.4.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.3.0...@sapphire/snowflake@3.4.0) - (2022-12-27) + +## 🐛 Bug Fixes + +- **deps:** Update all non-major dependencies (#532) ([8033d1f](https://github.com/sapphiredev/utilities/commit/8033d1ff7a5a1974134c61f424f171cccb2915e1)) + +## 📝 Documentation + +- Add @06000208 as a contributor ([fa3349e](https://github.com/sapphiredev/utilities/commit/fa3349e55ce4ad008785211dec7bf8e2b5d933df)) + +## 🚀 Features + +- **snowflake:** Added `Snowflake.compare` (#531) ([6accd6d](https://github.com/sapphiredev/utilities/commit/6accd6d15eab12e312034f8ef43cff032835c972)) + +# [@sapphire/snowflake@3.3.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.2.2...@sapphire/snowflake@3.3.0) - (2022-12-03) + +## 🏠 Refactor + +- Split `@sapphire/time-utilities` into 4 sub-packages (#462) ([574299a](https://github.com/sapphiredev/utilities/commit/574299a99e658f6500a2a7efa587a0919b2d1313)) + +## 🐛 Bug Fixes + +- **snowflake:** TwitterSnowflake using incorrect epoch (#522) ([4ad4117](https://github.com/sapphiredev/utilities/commit/4ad41170488161b2998bd72da5a8b7fea10539a0)) +- **deps:** Update all non-major dependencies (#514) ([21b07d5](https://github.com/sapphiredev/utilities/commit/21b07d5db529a0d982647a60de98e46f36f1ac93)) +- **deps:** Update all non-major dependencies (#505) ([6178296](https://github.com/sapphiredev/utilities/commit/617829649e1e4deeee02b14533b5377cd5bc1fb3)) +- **deps:** Update all non-major dependencies (#466) ([dc08606](https://github.com/sapphiredev/utilities/commit/dc08606a97154e47c65536123ac5f8b1262f7bd2)) +- **deps:** Update all non-major dependencies ([e20f299](https://github.com/sapphiredev/utilities/commit/e20f29906e83cee000aaba9c6827e3bec5173d28)) +- **deps:** Update all non-major dependencies ([2308bd7](https://github.com/sapphiredev/utilities/commit/2308bd74356b6b2e0c12995b25f4d8ade4803fe9)) +- **deps:** Update all non-major dependencies ([84af0db](https://github.com/sapphiredev/utilities/commit/84af0db2db749223b036aa99fe19a2e9af5681c6)) +- **deps:** Update all non-major dependencies ([50cd8de](https://github.com/sapphiredev/utilities/commit/50cd8dea593b6f5ae75571209456b3421e2ca59a)) + +## 📝 Documentation + +- Add @didinele as a contributor ([42ef7b6](https://github.com/sapphiredev/utilities/commit/42ef7b656c48fd0e720119db1d622c8bba2791e9)) +- Add @goestav as a contributor ([0e56a92](https://github.com/sapphiredev/utilities/commit/0e56a92a4e2d0942bfa207f81a8cb03b32312034)) +- Add @CitTheDev as a contributor ([34169ea](https://github.com/sapphiredev/utilities/commit/34169eae1dc0476ccf5a6c4f36e28602a204829e)) +- Add @legendhimslef as a contributor ([059b6f1](https://github.com/sapphiredev/utilities/commit/059b6f1ab5362d46d58624d06c1aa39192b0716f)) +- Add @r-priyam as a contributor ([fb278ba](https://github.com/sapphiredev/utilities/commit/fb278bacf627ec6fc88752eafeb12df5f3177a2c)) +- Change name of @kyranet (#451) ([df4fdef](https://github.com/sapphiredev/utilities/commit/df4fdefce18659975a4ebc224723638507d02d35)) +- Update @RealShadowNova as a contributor ([a869ba0](https://github.com/sapphiredev/utilities/commit/a869ba0abfad041610b9115187d426aebe671af6)) +- Add @muchnameless as a contributor ([a1221fe](https://github.com/sapphiredev/utilities/commit/a1221fea68506e99591d5d00ec552a07c26833f9)) +- Add @enxg as a contributor ([d2382f0](https://github.com/sapphiredev/utilities/commit/d2382f04e3909cb4ad11798a0a10e683f6cf5383)) +- Add @EvolutionX-10 as a contributor ([efc3a32](https://github.com/sapphiredev/utilities/commit/efc3a320a72ae258996dd62866d206c33f8d4961)) +- Add @MajesticString as a contributor ([295b3e9](https://github.com/sapphiredev/utilities/commit/295b3e9849a4b0fe64074bae02f6426378a303c3)) +- Add @Mzato0001 as a contributor ([c790ef2](https://github.com/sapphiredev/utilities/commit/c790ef25df2d7e22888fa9f8169167aa555e9e19)) + +## 🚀 Features + +- **utilities:** Add possibility to import single functions by appending them to the import path. (#454) ([374c145](https://github.com/sapphiredev/utilities/commit/374c145a5dd329cfc1a867ed6720abf408683a88)) + +## 🧪 Testing + +- Migrate to vitest (#380) ([075ec73](https://github.com/sapphiredev/utilities/commit/075ec73c7a8e3374fad3ada612d37eb4ac36ec8d)) + +# [@sapphire/snowflake@3.2.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.2.1...@sapphire/snowflake@3.2.2) - (2022-04-24) + +## Bug Fixes + +- Fix typo (#333) ([ae2f257](https://github.com/sapphiredev/utilities/commit/ae2f25766d5985735f2d9b257eebd27cdc8a7c52)) + +## Documentation + +- Add @NotKaskus as a contributor ([00da8f1](https://github.com/sapphiredev/utilities/commit/00da8f199137b9277119823f322d1f2d168d928a)) +- Add @imranbarbhuiya as a contributor ([fb674c2](https://github.com/sapphiredev/utilities/commit/fb674c2c5594d41e71662263553dcb4bac9e37f4)) +- Add @axisiscool as a contributor ([ce1aa31](https://github.com/sapphiredev/utilities/commit/ce1aa316871a88d3663efbdf2a42d3d8dfe6a27f)) +- Add @dhruv-kaushikk as a contributor ([ebbf43f](https://github.com/sapphiredev/utilities/commit/ebbf43f63617daba96e72c50a234bf8b64f6ddc4)) +- Add @Commandtechno as a contributor ([f1d69fa](https://github.com/sapphiredev/utilities/commit/f1d69fabe1ee0abe4be08b19e63dbec03102f7ce)) +- Fix typedoc causing OOM crashes ([63ba41c](https://github.com/sapphiredev/utilities/commit/63ba41c4b6678554b1c7043a22d3296db4f59360)) + +## [3.2.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.2.0...@sapphire/snowflake@3.2.1) (2022-04-01) + +**Note:** Version bump only for package @sapphire/snowflake + +# [3.2.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.1.0...@sapphire/snowflake@3.2.0) (2022-03-06) + +### Bug Fixes + +- **snowflake:** fixed the examples for `DiscordSnowflake` and `TwitterSnowflake` ([#282](https://github.com/sapphiredev/utilities/issues/282)) ([2e5ed7f](https://github.com/sapphiredev/utilities/commit/2e5ed7fdadccf261967c45f73d0dc78e2497eed3)) + +### Features + +- allow module: NodeNext ([#306](https://github.com/sapphiredev/utilities/issues/306)) ([9dc6dd6](https://github.com/sapphiredev/utilities/commit/9dc6dd619efab879bb2b0b3c9e64304e10a67ed6)) +- **ts-config:** add multi-config structure ([#281](https://github.com/sapphiredev/utilities/issues/281)) ([b5191d7](https://github.com/sapphiredev/utilities/commit/b5191d7f2416dc5838590c4ff221454925553e37)) + +# [3.1.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.0.1...@sapphire/snowflake@3.1.0) (2022-01-28) + +### Features + +- change build system to tsup ([#270](https://github.com/sapphiredev/utilities/issues/270)) ([365a53a](https://github.com/sapphiredev/utilities/commit/365a53a5517a01a0926cf28a83c96b63f32ed9f8)) + +## [3.0.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@3.0.0...@sapphire/snowflake@3.0.1) (2022-01-10) + +**Note:** Version bump only for package @sapphire/snowflake + +# [3.0.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.4...@sapphire/snowflake@3.0.0) (2021-12-08) + +### Bug Fixes + +- **snowflake:** remove env-based defaults ([#232](https://github.com/sapphiredev/utilities/issues/232)) ([10408e4](https://github.com/sapphiredev/utilities/commit/10408e4d3677e91490d967c3d89bf9575946090b)) + +### Features + +- **Snowflake:** rework entire package ([#231](https://github.com/sapphiredev/utilities/issues/231)) ([1d02f1a](https://github.com/sapphiredev/utilities/commit/1d02f1a2f520efcbc194c3992af593d0e493873b)) + +### BREAKING CHANGES + +- **Snowflake:** Renamed `processID` to `processId` +- **Snowflake:** Renamed `workerID` to `workerId` +- **Snowflake:** `workerId` now defaults to 0n instead of 1n +- **Snowflake:** `DiscordSnowflake` is not longer a class, but a constructed Snowflake +- **Snowflake:** `TwitterSnowflake` is not longer a class, but a constructed Snowflake + +## [2.1.4](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.3...@sapphire/snowflake@2.1.4) (2021-11-06) + +**Note:** Version bump only for package @sapphire/snowflake + +## [2.1.3](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.2...@sapphire/snowflake@2.1.3) (2021-10-26) + +**Note:** Version bump only for package @sapphire/snowflake + +## [2.1.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.1...@sapphire/snowflake@2.1.2) (2021-10-17) + +### Bug Fixes + +- allow more node & npm versions in engines field ([5977d2a](https://github.com/sapphiredev/utilities/commit/5977d2a30a4b2cfdf84aff3f33af03ffde1bbec5)) + +## [2.1.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.1.0...@sapphire/snowflake@2.1.1) (2021-10-11) + +**Note:** Version bump only for package @sapphire/snowflake + +# [2.1.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@2.0.0...@sapphire/snowflake@2.1.0) (2021-10-04) + +### Bug Fixes + +- **snowflake:** fixed snowflake generating duplicate IDs ([#166](https://github.com/sapphiredev/utilities/issues/166)) ([f0cf4ad](https://github.com/sapphiredev/utilities/commit/f0cf4ad6bc0b8b2447499ca36581d2b453e52715)) + +### Features + +- **snowflake:** set minimum NodeJS to v14 ([11a61c7](https://github.com/sapphiredev/utilities/commit/11a61c72bc29e683f9a4492815db3db094103bbc)) + +# [2.0.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.6...@sapphire/snowflake@2.0.0) (2021-07-17) + +### Code Refactoring + +- **rateLimits:** rewrite all of it ([#130](https://github.com/sapphiredev/utilities/issues/130)) ([320778c](https://github.com/sapphiredev/utilities/commit/320778ca65cbf3591bd1ce0b1f2eb430693eef9a)) + +### BREAKING CHANGES + +- **rateLimits:** Removed `Bucket` + +## [1.3.6](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.5...@sapphire/snowflake@1.3.6) (2021-07-11) + +**Note:** Version bump only for package @sapphire/snowflake + +## [1.3.5](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.4...@sapphire/snowflake@1.3.5) (2021-06-27) + +**Note:** Version bump only for package @sapphire/snowflake + +## [1.3.4](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.3...@sapphire/snowflake@1.3.4) (2021-06-19) + +### Bug Fixes + +- **doc:** change `[@link](https://github.com/link)` to `[@linkplain](https://github.com/linkplain)` for support in VSCode IntelliSense ([703d460](https://github.com/sapphiredev/utilities/commit/703d4605b547a8787aff62d6f1054ea26dfd9d1c)) +- **docs:** update-tsdoc-for-vscode-may-2021 ([#126](https://github.com/sapphiredev/utilities/issues/126)) ([f8581bf](https://github.com/sapphiredev/utilities/commit/f8581bfe97a1b2f8aac3a3d3ed342d8ba92d730b)) + +## [1.3.3](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.2...@sapphire/snowflake@1.3.3) (2021-06-06) + +### Bug Fixes + +- remove peer deps, update dev deps, update READMEs ([#124](https://github.com/sapphiredev/utilities/issues/124)) ([67256ed](https://github.com/sapphiredev/utilities/commit/67256ed43b915b02a8b5c68230ba82d6210c5032)) +- **snowflake:** fixed parsing for timestamps as Date objects ([c17a515](https://github.com/sapphiredev/utilities/commit/c17a515b02931cf778ca69913132e8d4558504a1)) + +## [1.3.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.1...@sapphire/snowflake@1.3.2) (2021-05-20) + +### Bug Fixes + +- **snowflake:** mark package as side effect free ([6a9bafc](https://github.com/sapphiredev/utilities/commit/6a9bafc24caba4b0ebbdd6896ac245ae6d60dede)) + +## [1.3.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.3.0...@sapphire/snowflake@1.3.1) (2021-05-02) + +### Bug Fixes + +- drop the `www.` from the SapphireJS URL ([494d89f](https://github.com/sapphiredev/utilities/commit/494d89ffa04f78c195b93d7905b3232884f7d7e2)) +- update all the SapphireJS URLs from `.com` to `.dev` ([f59b46d](https://github.com/sapphiredev/utilities/commit/f59b46d1a0ebd39cad17b17d71cd3b9da808d5fd)) + +# [1.3.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.8...@sapphire/snowflake@1.3.0) (2021-04-21) + +### Features + +- add @sapphire/embed-jsx ([#100](https://github.com/sapphiredev/utilities/issues/100)) ([7277a23](https://github.com/sapphiredev/utilities/commit/7277a236015236ed8e81b7882875410facc4ce17)) + +## [1.2.8](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.7...@sapphire/snowflake@1.2.8) (2021-04-19) + +### Bug Fixes + +- change all Sapphire URLs from "project"->"community" & use our domain where applicable 👨‍🌾🚜 ([#102](https://github.com/sapphiredev/utilities/issues/102)) ([835b408](https://github.com/sapphiredev/utilities/commit/835b408e8e57130c3787aca2e32613346ff23e4d)) + +## [1.2.7](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.6...@sapphire/snowflake@1.2.7) (2021-04-03) + +**Note:** Version bump only for package @sapphire/snowflake + +## [1.2.6](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.5...@sapphire/snowflake@1.2.6) (2021-03-16) + +### Bug Fixes + +- remove terser from all packages ([#79](https://github.com/sapphiredev/utilities/issues/79)) ([1cfe4e7](https://github.com/sapphiredev/utilities/commit/1cfe4e7c804e62c142495686d2b83b81d0026c02)) + +## [1.2.5](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.4...@sapphire/snowflake@1.2.5) (2021-02-16) + +**Note:** Version bump only for package @sapphire/snowflake + +## [1.2.4](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.3...@sapphire/snowflake@1.2.4) (2021-01-16) + +**Note:** Version bump only for package @sapphire/snowflake + +## [1.2.3](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.2...@sapphire/snowflake@1.2.3) (2021-01-01) + +**Note:** Version bump only for package @sapphire/snowflake + +## [1.2.2](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.1...@sapphire/snowflake@1.2.2) (2020-12-26) + +**Note:** Version bump only for package @sapphire/snowflake + +## [1.2.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.2.0...@sapphire/snowflake@1.2.1) (2020-12-22) + +**Note:** Version bump only for package @sapphire/snowflake + +# [1.2.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.1.0...@sapphire/snowflake@1.2.0) (2020-11-15) + +### Bug Fixes + +- **snowflake:** pass keep_classnames to terser ([76ea062](https://github.com/sapphiredev/utilities/commit/76ea062d07000b169d9781f1a199b85ad3db0ba6)) +- **snowflake:** pass keep_fnames to terser ([b52aa76](https://github.com/sapphiredev/utilities/commit/b52aa764d8b02535496e0ceea3204a37552ce3d1)) + +### Features + +- added time-utilities package ([#26](https://github.com/sapphiredev/utilities/issues/26)) ([f17a333](https://github.com/sapphiredev/utilities/commit/f17a3339667a452e8745fad7884272176e5d65e8)) + +# [1.1.0](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.0.1...@sapphire/snowflake@1.1.0) (2020-11-04) + +### Bug Fixes + +- **ratelimits,snowflake,utilities:** fixed esm output target ([9fdab3f](https://github.com/sapphiredev/utilities/commit/9fdab3fca283c8c0b47cc32661c5cf8e0a5e583c)) +- **snowflake:** properly specify ESM and CommonJS exports ([e3278e6](https://github.com/sapphiredev/utilities/commit/e3278e6868a4f31d5b2a100710bcbce2b79bc218)) + +### Features + +- added ratelimits package ([#15](https://github.com/sapphiredev/utilities/issues/15)) ([e0ae18c](https://github.com/sapphiredev/utilities/commit/e0ae18c5e1d0ae4e68a982829f1cf251fddfc80d)) + +## [1.0.1](https://github.com/sapphiredev/utilities/compare/@sapphire/snowflake@1.0.0...@sapphire/snowflake@1.0.1) (2020-09-20) + +**Note:** Version bump only for package @sapphire/snowflake + +# 1.0.0 (2020-09-05) + +### Features + +- implement snowflake ([5ba4e2d](https://github.com/sapphiredev/utilities/commit/5ba4e2d82557dd4ff60ffe891a7b46e46373bea2)) +- **decorators:** add decorators package ([#4](https://github.com/sapphiredev/utilities/issues/4)) ([677b3e5](https://github.com/sapphiredev/utilities/commit/677b3e59d5c6160cbe6fb410821cadd7c0f00e3c)) diff --git a/node_modules/@sapphire/snowflake/README.md b/node_modules/@sapphire/snowflake/README.md new file mode 100644 index 0000000..e8d3089 --- /dev/null +++ b/node_modules/@sapphire/snowflake/README.md @@ -0,0 +1,234 @@ +

+ +**Table of Contents** + +- [Description](#description) +- [Features](#features) +- [Installation](#installation) +- [Usage](#usage) + - [Constructing snowflakes](#constructing-snowflakes) + - [Snowflakes with custom epoch](#snowflakes-with-custom-epoch) + - [Snowflake with Discord epoch constant](#snowflake-with-discord-epoch-constant) + - [Snowflake with Twitter epoch constant](#snowflake-with-twitter-epoch-constant) + - [Deconstructing snowflakes](#deconstructing-snowflakes) + - [Snowflakes with custom epoch](#snowflakes-with-custom-epoch-1) + - [Snowflake with Discord epoch constant](#snowflake-with-discord-epoch-constant-1) + - [Snowflake with Twitter epoch constant](#snowflake-with-twitter-epoch-constant-1) +- [Buy us some doughnuts](#buy-us-some-doughnuts) +- [Contributors ✨](#contributors-%E2%9C%A8) + +## Description + +There is often a need to get a unique ID for entities, be that for Discord messages/channels/servers, keys in a database or many other similar examples. There are many ways to get such a unique ID, and one of those is using a so-called "snowflake". You can read more about snowflake IDs in [this Medium article](https://medium.com/better-programming/uuid-generation-snowflake-identifiers-unique-2aed8b1771bc). + +## Features + +- Written in TypeScript +- Bundled with esbuild so it can be used in NodeJS and browsers +- Offers CommonJS, ESM and UMD bundles +- Offers predefined epochs for Discord and Twitter +- Fully tested + +## Installation + +You can use the following command to install this package, or replace `npm install` with your package manager of choice. + +```sh +npm install @sapphire/snowflake +``` + +## Usage + +**Note:** While this section uses `require`, the imports match 1:1 with ESM imports. For example `const { Snowflake } = require('@sapphire/snowflake')` equals `import { Snowflake } from '@sapphire/snowflake'`. + +### Constructing snowflakes + +#### Snowflakes with custom epoch + +```typescript +// Import the Snowflake class +const { Snowflake } = require('@sapphire/snowflake'); + +// Define a custom epoch +const epoch = new Date('2000-01-01T00:00:00.000Z'); + +// Create an instance of Snowflake +const snowflake = new Snowflake(epoch); + +// Generate a snowflake with the given epoch +const uniqueId = snowflake.generate(); +``` + +#### Snowflake with Discord epoch constant + +```typescript +// Import the Snowflake class +const { DiscordSnowflake } = require('@sapphire/snowflake'); + +// Generate a snowflake with Discord's epoch +const uniqueId = DiscordSnowflake.generate(); + +// Alternatively, you can use the method directly +const uniqueId = DiscordSnowflake.generate(); +``` + +#### Snowflake with Twitter epoch constant + +```typescript +// Import the Snowflake class +const { TwitterSnowflake } = require('@sapphire/snowflake'); + +// Generate a snowflake with Twitter's epoch +const uniqueId = TwitterSnowflake.generate(); + +// Alternatively, you can use the method directly +const uniqueId = TwitterSnowflake.generate(); +``` + +### Deconstructing snowflakes + +#### Snowflakes with custom epoch + +```typescript +// Import the Snowflake class +const { Snowflake } = require('@sapphire/snowflake'); + +// Define a custom epoch +const epoch = new Date('2000-01-01T00:00:00.000Z'); + +// Create an instance of Snowflake +const snowflake = new Snowflake(epoch); + +// Deconstruct a snowflake with the given epoch +const uniqueId = snowflake.deconstruct('3971046231244935168'); +``` + +#### Snowflake with Discord epoch constant + +```typescript +// Import the Snowflake class +const { DiscordSnowflake } = require('@sapphire/snowflake'); + +// Deconstruct a snowflake with Discord's epoch +const uniqueId = DiscordSnowflake.deconstruct('3971046231244935168'); + +// Alternatively, you can use the method directly +const uniqueId = DiscordSnowflake.deconstruct('3971046231244935168'); +``` + +#### Snowflake with Twitter epoch constant + +```typescript +// Import the Snowflake class +const { TwitterSnowflake } = require('@sapphire/snowflake'); + +// Deconstruct a snowflake with Twitter's epoch +const uniqueId = TwitterSnowflake.deconstruct('3971046231244935168'); + +// Alternatively, you can use the method directly +const uniqueId = TwitterSnowflake.deconstruct('3971046231244935168'); +``` + +--- + +## Buy us some doughnuts + +Sapphire Community is and always will be open source, even if we don't get donations. That being said, we know there are amazing people who may still want to donate just to show their appreciation. Thank you very much in advance! + +We accept donations through Open Collective, Ko-fi, PayPal, Patreon and GitHub Sponsorships. You can use the buttons below to donate through your method of choice. + +| Donate With | Address | +| :-------------: | :-------------------------------------------------: | +| Open Collective | [Click Here](https://sapphirejs.dev/opencollective) | +| Ko-fi | [Click Here](https://sapphirejs.dev/kofi) | +| Patreon | [Click Here](https://sapphirejs.dev/patreon) | +| PayPal | [Click Here](https://sapphirejs.dev/paypal) | + +## Contributors ✨ + +Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Jeroen Claassens

💻 🚇 📆 📖 ⚠️

Aura Román

💻 📆 👀 ⚠️

Gryffon Bellish

💻 👀 ⚠️

Vlad Frangu

💻 🐛 👀 📓 ⚠️

Stitch07

💻 📆 ⚠️

depfu[bot]

🚧

allcontributors[bot]

📖

Tyler J Russell

📖

Ivan Lieder

💻 🐛

Hezekiah Hendry

💻 🔧

Vetlix

💻

Ethan Mitchell

📖

Elliot

💻

Jurien Hamaker

💻

Charalampos Fanoulis

📖

dependabot[bot]

🚧

Kaname

💻

nandhagk

🐛

megatank58

💻

UndiedGamer

💻

Lioness100

📖 💻

David

💻

renovate[bot]

🚧

WhiteSource Renovate

🚧

FC

💻

Jérémy de Saint Denis

💻

MrCube

💻

bitomic

💻

c43721

💻

Commandtechno

💻

Aura

💻

Jonathan

💻

Parbez

🚧

Paul Andrew

📖

Mzato

💻 🐛

Harry Allen

📖

Evo

💻

Enes Genç

💻

muchnameless

💻

Priyam

💻

Voxelli

💻

Cit The Dev

💻

Goestav

💻

DD

💻

amber

💻
+ + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! diff --git a/node_modules/@sapphire/snowflake/dist/index.d.ts b/node_modules/@sapphire/snowflake/dist/index.d.ts new file mode 100644 index 0000000..398d957 --- /dev/null +++ b/node_modules/@sapphire/snowflake/dist/index.d.ts @@ -0,0 +1,149 @@ +/** + * A class for generating and deconstructing Twitter snowflakes. + * + * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake} + * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value. + * + * If we have a snowflake `266241948824764416` we can represent it as binary: + * ``` + * 64 22 17 12 0 + * 000000111011000111100001101001000101000000 00001 00000 000000000000 + * number of ms since epoch worker pid increment + * ``` + */ +declare class Snowflake { + #private; + /** + * Alias for {@link deconstruct} + */ + decode: (id: string | bigint) => DeconstructedSnowflake; + /** + * @param epoch the epoch to use + */ + constructor(epoch: number | bigint | Date); + /** + * The epoch for this snowflake. + */ + get epoch(): bigint; + /** + * Generates a snowflake given an epoch and optionally a timestamp + * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions} + * + * **note** when `increment` is not provided it defaults to the private `increment` of the instance + * @example + * ```typescript + * const epoch = new Date('2000-01-01T00:00:00.000Z'); + * const snowflake = new Snowflake(epoch).generate(); + * ``` + * @returns A unique snowflake + */ + generate({ increment, timestamp, workerId, processId }?: SnowflakeGenerateOptions): bigint; + /** + * Deconstructs a snowflake given a snowflake ID + * @param id the snowflake to deconstruct + * @returns a deconstructed snowflake + * @example + * ```typescript + * const epoch = new Date('2000-01-01T00:00:00.000Z'); + * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168'); + * ``` + */ + deconstruct(id: string | bigint): DeconstructedSnowflake; + /** + * Retrieves the timestamp field's value from a snowflake. + * @param id The snowflake to get the timestamp value from. + * @returns The UNIX timestamp that is stored in `id`. + */ + timestampFrom(id: string | bigint): number; + /** + * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given + * snowflake in sort order. + * @param a The first snowflake to compare. + * @param b The second snowflake to compare. + * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`. + * @example Sort snowflakes in ascending order + * ```typescript + * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944']; + * console.log(ids.sort((a, b) => Snowflake.compare(a, b))); + * // → ['254360814063058944', '737141877803057244', '1056191128120082432']; + * ``` + * @example Sort snowflakes in descending order + * ```typescript + * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944']; + * console.log(ids.sort((a, b) => -Snowflake.compare(a, b))); + * // → ['1056191128120082432', '737141877803057244', '254360814063058944']; + * ``` + */ + static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1; +} +/** + * Options for Snowflake#generate + */ +interface SnowflakeGenerateOptions { + /** + * Timestamp or date of the snowflake to generate + * @default Date.now() + */ + timestamp?: number | bigint | Date; + /** + * The increment to use + * @default 0n + * @remark keep in mind that this bigint is auto-incremented between generate calls + */ + increment?: bigint; + /** + * The worker ID to use, will be truncated to 5 bits (0-31) + * @default 0n + */ + workerId?: bigint; + /** + * The process ID to use, will be truncated to 5 bits (0-31) + * @default 1n + */ + processId?: bigint; +} +/** + * Object returned by Snowflake#deconstruct + */ +interface DeconstructedSnowflake { + /** + * The id in BigInt form + */ + id: bigint; + /** + * The timestamp stored in the snowflake + */ + timestamp: bigint; + /** + * The worker id stored in the snowflake + */ + workerId: bigint; + /** + * The process id stored in the snowflake + */ + processId: bigint; + /** + * The increment stored in the snowflake + */ + increment: bigint; + /** + * The epoch to use in the snowflake + */ + epoch: bigint; +} + +/** + * A class for parsing snowflake ids using Discord's snowflake epoch + * + * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes} + */ +declare const DiscordSnowflake: Snowflake; + +/** + * A class for parsing snowflake ids using Twitter's snowflake epoch + * + * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25} + */ +declare const TwitterSnowflake: Snowflake; + +export { DeconstructedSnowflake, DiscordSnowflake, Snowflake, SnowflakeGenerateOptions, TwitterSnowflake }; diff --git a/node_modules/@sapphire/snowflake/dist/index.global.js b/node_modules/@sapphire/snowflake/dist/index.global.js new file mode 100644 index 0000000..bb4b1c1 --- /dev/null +++ b/node_modules/@sapphire/snowflake/dist/index.global.js @@ -0,0 +1,112 @@ +var SapphireSnowflake = (function (exports) { + 'use strict'; + + 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 __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; + }; + var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); + }; + var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); + }; + var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); + }; + var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; + }; + var __privateWrapper = (obj, member, setter, getter) => ({ + set _(value) { + __privateSet(obj, member, value, setter); + }, + get _() { + return __privateGet(obj, member, getter); + } + }); + + // src/lib/Snowflake.ts + var ProcessId = 1n; + var WorkerId = 0n; + var _increment, _epoch; + var Snowflake = class { + constructor(epoch) { + __publicField(this, "decode", this.deconstruct); + __privateAdd(this, _increment, 0n); + __privateAdd(this, _epoch, void 0); + __privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch)); + } + get epoch() { + return __privateGet(this, _epoch); + } + generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) { + if (timestamp instanceof Date) + timestamp = BigInt(timestamp.getTime()); + else if (typeof timestamp === "number") + timestamp = BigInt(timestamp); + else if (typeof timestamp !== "bigint") { + throw new TypeError(`"timestamp" argument must be a number, bigint, or Date (received ${typeof timestamp})`); + } + if (typeof increment === "bigint" && increment >= 4095n) + increment = 0n; + else { + increment = __privateWrapper(this, _increment)._++; + if (__privateGet(this, _increment) >= 4095n) + __privateSet(this, _increment, 0n); + } + return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment; + } + deconstruct(id) { + const bigIntId = BigInt(id); + return { + id: bigIntId, + timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch), + workerId: bigIntId >> 17n & 0b11111n, + processId: bigIntId >> 12n & 0b11111n, + increment: bigIntId & 0b111111111111n, + epoch: __privateGet(this, _epoch) + }; + } + timestampFrom(id) { + return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch)); + } + static compare(a, b) { + if (typeof a === "bigint" || typeof b === "bigint") { + if (typeof a === "string") + a = BigInt(a); + else if (typeof b === "string") + b = BigInt(b); + return a === b ? 0 : a < b ? -1 : 1; + } + return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1; + } + }; + __name(Snowflake, "Snowflake"); + _increment = new WeakMap(); + _epoch = new WeakMap(); + + // src/lib/DiscordSnowflake.ts + var DiscordSnowflake = new Snowflake(1420070400000n); + + // src/lib/TwitterSnowflake.ts + var TwitterSnowflake = new Snowflake(1288834974657n); + + exports.DiscordSnowflake = DiscordSnowflake; + exports.Snowflake = Snowflake; + exports.TwitterSnowflake = TwitterSnowflake; + + return exports; + +})({}); +//# sourceMappingURL=out.js.map +//# sourceMappingURL=index.global.js.map \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/dist/index.global.js.map b/node_modules/@sapphire/snowflake/dist/index.global.js.map new file mode 100644 index 0000000..3a05a29 --- /dev/null +++ b/node_modules/@sapphire/snowflake/dist/index.global.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAM,YAAY;AAClB,IAAM,WAAW;AADjB;AAgBO,IAAM,YAAN,MAAgB;AAAA,EAsBf,YAAY,OAA+B;AAjBlD,wBAAO,UAAS,KAAK;AAMrB,mCAAa;AAMb;AAMC,uBAAK,QAAS,OAAO,iBAAiB,OAAO,MAAM,QAAQ,IAAI,KAAK;AAAA,EACrE;AAAA,EAKA,IAAW,QAAgB;AAC1B,WAAO,mBAAK;AAAA,EACb;AAAA,EAcO,SAAS,EAAE,WAAW,YAAY,KAAK,IAAI,GAAG,WAAW,UAAU,YAAY,UAAU,IAA8B,CAAC,GAAG;AACjI,QAAI,qBAAqB;AAAM,kBAAY,OAAO,UAAU,QAAQ,CAAC;AAA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;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\t#increment = 0n;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\t#epoch: bigint;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis.#epoch = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake.\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this.#epoch;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId }: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment === 'bigint' && increment >= 4095n) increment = 0n;\n\t\telse {\n\t\t\tincrement = this.#increment++;\n\t\t\tif (this.#increment >= 4095n) this.#increment = 0n;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn ((timestamp - this.#epoch) << 22n) | ((workerId & 0b11111n) << 17n) | ((processId & 0b11111n) << 12n) | increment;\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + this.#epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & 0b11111n,\n\t\t\tprocessId: (bigIntId >> 12n) & 0b11111n,\n\t\t\tincrement: bigIntId & 0b111111111111n,\n\t\t\tepoch: this.#epoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this.#epoch);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tif (typeof a === 'bigint' || typeof b === 'bigint') {\n\t\t\tif (typeof a === 'string') a = BigInt(a);\n\t\t\telse if (typeof b === 'string') b = BigInt(b);\n\t\t\treturn a === b ? 0 : a < b ? -1 : 1;\n\t\t}\n\n\t\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n\t}\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/dist/index.js b/node_modules/@sapphire/snowflake/dist/index.js new file mode 100644 index 0000000..fd76743 --- /dev/null +++ b/node_modules/@sapphire/snowflake/dist/index.js @@ -0,0 +1,107 @@ +'use strict'; + +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 __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; +var __privateWrapper = (obj, member, setter, getter) => ({ + set _(value) { + __privateSet(obj, member, value, setter); + }, + get _() { + return __privateGet(obj, member, getter); + } +}); + +// src/lib/Snowflake.ts +var ProcessId = 1n; +var WorkerId = 0n; +var _increment, _epoch; +var Snowflake = class { + constructor(epoch) { + __publicField(this, "decode", this.deconstruct); + __privateAdd(this, _increment, 0n); + __privateAdd(this, _epoch, void 0); + __privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch)); + } + get epoch() { + return __privateGet(this, _epoch); + } + generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) { + if (timestamp instanceof Date) + timestamp = BigInt(timestamp.getTime()); + else if (typeof timestamp === "number") + timestamp = BigInt(timestamp); + else if (typeof timestamp !== "bigint") { + throw new TypeError(`"timestamp" argument must be a number, bigint, or Date (received ${typeof timestamp})`); + } + if (typeof increment === "bigint" && increment >= 4095n) + increment = 0n; + else { + increment = __privateWrapper(this, _increment)._++; + if (__privateGet(this, _increment) >= 4095n) + __privateSet(this, _increment, 0n); + } + return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment; + } + deconstruct(id) { + const bigIntId = BigInt(id); + return { + id: bigIntId, + timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch), + workerId: bigIntId >> 17n & 0b11111n, + processId: bigIntId >> 12n & 0b11111n, + increment: bigIntId & 0b111111111111n, + epoch: __privateGet(this, _epoch) + }; + } + timestampFrom(id) { + return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch)); + } + static compare(a, b) { + if (typeof a === "bigint" || typeof b === "bigint") { + if (typeof a === "string") + a = BigInt(a); + else if (typeof b === "string") + b = BigInt(b); + return a === b ? 0 : a < b ? -1 : 1; + } + return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1; + } +}; +__name(Snowflake, "Snowflake"); +_increment = new WeakMap(); +_epoch = new WeakMap(); + +// src/lib/DiscordSnowflake.ts +var DiscordSnowflake = new Snowflake(1420070400000n); + +// src/lib/TwitterSnowflake.ts +var TwitterSnowflake = new Snowflake(1288834974657n); + +exports.DiscordSnowflake = DiscordSnowflake; +exports.Snowflake = Snowflake; +exports.TwitterSnowflake = TwitterSnowflake; +//# sourceMappingURL=out.js.map +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/dist/index.js.map b/node_modules/@sapphire/snowflake/dist/index.js.map new file mode 100644 index 0000000..3a05a29 --- /dev/null +++ b/node_modules/@sapphire/snowflake/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAM,YAAY;AAClB,IAAM,WAAW;AADjB;AAgBO,IAAM,YAAN,MAAgB;AAAA,EAsBf,YAAY,OAA+B;AAjBlD,wBAAO,UAAS,KAAK;AAMrB,mCAAa;AAMb;AAMC,uBAAK,QAAS,OAAO,iBAAiB,OAAO,MAAM,QAAQ,IAAI,KAAK;AAAA,EACrE;AAAA,EAKA,IAAW,QAAgB;AAC1B,WAAO,mBAAK;AAAA,EACb;AAAA,EAcO,SAAS,EAAE,WAAW,YAAY,KAAK,IAAI,GAAG,WAAW,UAAU,YAAY,UAAU,IAA8B,CAAC,GAAG;AACjI,QAAI,qBAAqB;AAAM,kBAAY,OAAO,UAAU,QAAQ,CAAC;AAAA,aAC5D,OAAO,cAAc;AAAU,kBAAY,OAAO,SAAS;AAAA,aAC3D,OAAO,cAAc,UAAU;AACvC,YAAM,IAAI,UAAU,oEAAoE,OAAO,YAAY;AAAA,IAC5G;AAEA,QAAI,OAAO,cAAc,YAAY,aAAa;AAAO,kBAAY;AAAA,SAChE;AACJ,kBAAY,uBAAK,YAAL;AACZ,UAAI,mBAAK,eAAc;AAAO,2BAAK,YAAa;AAAA,IACjD;AAGA,WAAS,YAAY,mBAAK,WAAW,OAAS,WAAW,aAAa,OAAS,YAAY,aAAa,MAAO;AAAA,EAChH;AAAA,EAYO,YAAY,IAA6C;AAC/D,UAAM,WAAW,OAAO,EAAE;AAC1B,WAAO;AAAA,MACN,IAAI;AAAA,MACJ,YAAY,YAAY,OAAO,mBAAK;AAAA,MACpC,UAAW,YAAY,MAAO;AAAA,MAC9B,WAAY,YAAY,MAAO;AAAA,MAC/B,WAAW,WAAW;AAAA,MACtB,OAAO,mBAAK;AAAA,IACb;AAAA,EACD;AAAA,EAOO,cAAc,IAA6B;AACjD,WAAO,QAAQ,OAAO,EAAE,KAAK,OAAO,mBAAK,OAAM;AAAA,EAChD;AAAA,EAqBA,OAAc,QAAQ,GAAoB,GAAgC;AACzE,QAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU;AACnD,UAAI,OAAO,MAAM;AAAU,YAAI,OAAO,CAAC;AAAA,eAC9B,OAAO,MAAM;AAAU,YAAI,OAAO,CAAC;AAC5C,aAAO,MAAM,IAAI,IAAI,IAAI,IAAI,KAAK;AAAA,IACnC;AAEA,WAAO,MAAM,IAAI,IAAI,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,IAAI,IAAI,KAAK;AAAA,EACxF;AACD;AAzHa;AAWZ;AAMA;;;AC1BM,IAAM,mBAAmB,IAAI,UAAU,cAAc;;;ACArD,IAAM,mBAAmB,IAAI,UAAU,cAAc","sourcesContent":["const ProcessId = 1n;\nconst WorkerId = 0n;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\t#increment = 0n;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\t#epoch: bigint;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis.#epoch = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake.\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this.#epoch;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId }: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment === 'bigint' && increment >= 4095n) increment = 0n;\n\t\telse {\n\t\t\tincrement = this.#increment++;\n\t\t\tif (this.#increment >= 4095n) this.#increment = 0n;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn ((timestamp - this.#epoch) << 22n) | ((workerId & 0b11111n) << 17n) | ((processId & 0b11111n) << 12n) | increment;\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + this.#epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & 0b11111n,\n\t\t\tprocessId: (bigIntId >> 12n) & 0b11111n,\n\t\t\tincrement: bigIntId & 0b111111111111n,\n\t\t\tepoch: this.#epoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this.#epoch);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tif (typeof a === 'bigint' || typeof b === 'bigint') {\n\t\t\tif (typeof a === 'string') a = BigInt(a);\n\t\t\telse if (typeof b === 'string') b = BigInt(b);\n\t\t\treturn a === b ? 0 : a < b ? -1 : 1;\n\t\t}\n\n\t\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n\t}\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/dist/index.mjs b/node_modules/@sapphire/snowflake/dist/index.mjs new file mode 100644 index 0000000..cdef2f9 --- /dev/null +++ b/node_modules/@sapphire/snowflake/dist/index.mjs @@ -0,0 +1,103 @@ +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 __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; +var __privateWrapper = (obj, member, setter, getter) => ({ + set _(value) { + __privateSet(obj, member, value, setter); + }, + get _() { + return __privateGet(obj, member, getter); + } +}); + +// src/lib/Snowflake.ts +var ProcessId = 1n; +var WorkerId = 0n; +var _increment, _epoch; +var Snowflake = class { + constructor(epoch) { + __publicField(this, "decode", this.deconstruct); + __privateAdd(this, _increment, 0n); + __privateAdd(this, _epoch, void 0); + __privateSet(this, _epoch, BigInt(epoch instanceof Date ? epoch.getTime() : epoch)); + } + get epoch() { + return __privateGet(this, _epoch); + } + generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId } = {}) { + if (timestamp instanceof Date) + timestamp = BigInt(timestamp.getTime()); + else if (typeof timestamp === "number") + timestamp = BigInt(timestamp); + else if (typeof timestamp !== "bigint") { + throw new TypeError(`"timestamp" argument must be a number, bigint, or Date (received ${typeof timestamp})`); + } + if (typeof increment === "bigint" && increment >= 4095n) + increment = 0n; + else { + increment = __privateWrapper(this, _increment)._++; + if (__privateGet(this, _increment) >= 4095n) + __privateSet(this, _increment, 0n); + } + return timestamp - __privateGet(this, _epoch) << 22n | (workerId & 0b11111n) << 17n | (processId & 0b11111n) << 12n | increment; + } + deconstruct(id) { + const bigIntId = BigInt(id); + return { + id: bigIntId, + timestamp: (bigIntId >> 22n) + __privateGet(this, _epoch), + workerId: bigIntId >> 17n & 0b11111n, + processId: bigIntId >> 12n & 0b11111n, + increment: bigIntId & 0b111111111111n, + epoch: __privateGet(this, _epoch) + }; + } + timestampFrom(id) { + return Number((BigInt(id) >> 22n) + __privateGet(this, _epoch)); + } + static compare(a, b) { + if (typeof a === "bigint" || typeof b === "bigint") { + if (typeof a === "string") + a = BigInt(a); + else if (typeof b === "string") + b = BigInt(b); + return a === b ? 0 : a < b ? -1 : 1; + } + return a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1; + } +}; +__name(Snowflake, "Snowflake"); +_increment = new WeakMap(); +_epoch = new WeakMap(); + +// src/lib/DiscordSnowflake.ts +var DiscordSnowflake = new Snowflake(1420070400000n); + +// src/lib/TwitterSnowflake.ts +var TwitterSnowflake = new Snowflake(1288834974657n); + +export { DiscordSnowflake, Snowflake, TwitterSnowflake }; +//# sourceMappingURL=out.js.map +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/dist/index.mjs.map b/node_modules/@sapphire/snowflake/dist/index.mjs.map new file mode 100644 index 0000000..3a05a29 --- /dev/null +++ b/node_modules/@sapphire/snowflake/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/lib/Snowflake.ts","../src/lib/DiscordSnowflake.ts","../src/lib/TwitterSnowflake.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAM,YAAY;AAClB,IAAM,WAAW;AADjB;AAgBO,IAAM,YAAN,MAAgB;AA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,OAAO,MAAM;AAAU,YAAI,OAAO,CAAC;AAC5C,aAAO,MAAM,IAAI,IAAI,IAAI,IAAI,KAAK;AAAA,IACnC;AAEA,WAAO,MAAM,IAAI,IAAI,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,IAAI,IAAI,KAAK;AAAA,EACxF;AACD;AAzHa;AAWZ;AAMA;;;AC1BM,IAAM,mBAAmB,IAAI,UAAU,cAAc;;;ACArD,IAAM,mBAAmB,IAAI,UAAU,cAAc","sourcesContent":["const ProcessId = 1n;\nconst WorkerId = 0n;\n\n/**\n * A class for generating and deconstructing Twitter snowflakes.\n *\n * A {@link https://developer.twitter.com/en/docs/twitter-ids Twitter snowflake}\n * is a 64-bit unsigned integer with 4 fields that have a fixed epoch value.\n *\n * If we have a snowflake `266241948824764416` we can represent it as binary:\n * ```\n * 64 22 17 12 0\n * 000000111011000111100001101001000101000000 00001 00000 000000000000\n * number of ms since epoch worker pid increment\n * ```\n */\nexport class Snowflake {\n\t/**\n\t * Alias for {@link deconstruct}\n\t */\n\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\tpublic decode = this.deconstruct;\n\n\t/**\n\t * Internal incrementor for generating snowflakes\n\t * @internal\n\t */\n\t#increment = 0n;\n\n\t/**\n\t * Internal reference of the epoch passed in the constructor\n\t * @internal\n\t */\n\t#epoch: bigint;\n\n\t/**\n\t * @param epoch the epoch to use\n\t */\n\tpublic constructor(epoch: number | bigint | Date) {\n\t\tthis.#epoch = BigInt(epoch instanceof Date ? epoch.getTime() : epoch);\n\t}\n\n\t/**\n\t * The epoch for this snowflake.\n\t */\n\tpublic get epoch(): bigint {\n\t\treturn this.#epoch;\n\t}\n\n\t/**\n\t * Generates a snowflake given an epoch and optionally a timestamp\n\t * @param options options to pass into the generator, see {@link SnowflakeGenerateOptions}\n\t *\n\t * **note** when `increment` is not provided it defaults to the private `increment` of the instance\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).generate();\n\t * ```\n\t * @returns A unique snowflake\n\t */\n\tpublic generate({ increment, timestamp = Date.now(), workerId = WorkerId, processId = ProcessId }: SnowflakeGenerateOptions = {}) {\n\t\tif (timestamp instanceof Date) timestamp = BigInt(timestamp.getTime());\n\t\telse if (typeof timestamp === 'number') timestamp = BigInt(timestamp);\n\t\telse if (typeof timestamp !== 'bigint') {\n\t\t\tthrow new TypeError(`\"timestamp\" argument must be a number, bigint, or Date (received ${typeof timestamp})`);\n\t\t}\n\n\t\tif (typeof increment === 'bigint' && increment >= 4095n) increment = 0n;\n\t\telse {\n\t\t\tincrement = this.#increment++;\n\t\t\tif (this.#increment >= 4095n) this.#increment = 0n;\n\t\t}\n\n\t\t// timestamp, workerId, processId, increment\n\t\treturn ((timestamp - this.#epoch) << 22n) | ((workerId & 0b11111n) << 17n) | ((processId & 0b11111n) << 12n) | increment;\n\t}\n\n\t/**\n\t * Deconstructs a snowflake given a snowflake ID\n\t * @param id the snowflake to deconstruct\n\t * @returns a deconstructed snowflake\n\t * @example\n\t * ```typescript\n\t * const epoch = new Date('2000-01-01T00:00:00.000Z');\n\t * const snowflake = new Snowflake(epoch).deconstruct('3971046231244935168');\n\t * ```\n\t */\n\tpublic deconstruct(id: string | bigint): DeconstructedSnowflake {\n\t\tconst bigIntId = BigInt(id);\n\t\treturn {\n\t\t\tid: bigIntId,\n\t\t\ttimestamp: (bigIntId >> 22n) + this.#epoch,\n\t\t\tworkerId: (bigIntId >> 17n) & 0b11111n,\n\t\t\tprocessId: (bigIntId >> 12n) & 0b11111n,\n\t\t\tincrement: bigIntId & 0b111111111111n,\n\t\t\tepoch: this.#epoch\n\t\t};\n\t}\n\n\t/**\n\t * Retrieves the timestamp field's value from a snowflake.\n\t * @param id The snowflake to get the timestamp value from.\n\t * @returns The UNIX timestamp that is stored in `id`.\n\t */\n\tpublic timestampFrom(id: string | bigint): number {\n\t\treturn Number((BigInt(id) >> 22n) + this.#epoch);\n\t}\n\n\t/**\n\t * Returns a number indicating whether a reference snowflake comes before, or after, or is same as the given\n\t * snowflake in sort order.\n\t * @param a The first snowflake to compare.\n\t * @param b The second snowflake to compare.\n\t * @returns `-1` if `a` is older than `b`, `0` if `a` and `b` are equals, `1` if `a` is newer than `b`.\n\t * @example Sort snowflakes in ascending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => Snowflake.compare(a, b)));\n\t * // → ['254360814063058944', '737141877803057244', '1056191128120082432'];\n\t * ```\n\t * @example Sort snowflakes in descending order\n\t * ```typescript\n\t * const ids = ['737141877803057244', '1056191128120082432', '254360814063058944'];\n\t * console.log(ids.sort((a, b) => -Snowflake.compare(a, b)));\n\t * // → ['1056191128120082432', '737141877803057244', '254360814063058944'];\n\t * ```\n\t */\n\tpublic static compare(a: string | bigint, b: string | bigint): -1 | 0 | 1 {\n\t\tif (typeof a === 'bigint' || typeof b === 'bigint') {\n\t\t\tif (typeof a === 'string') a = BigInt(a);\n\t\t\telse if (typeof b === 'string') b = BigInt(b);\n\t\t\treturn a === b ? 0 : a < b ? -1 : 1;\n\t\t}\n\n\t\treturn a === b ? 0 : a.length < b.length ? -1 : a.length > b.length ? 1 : a < b ? -1 : 1;\n\t}\n}\n\n/**\n * Options for Snowflake#generate\n */\nexport interface SnowflakeGenerateOptions {\n\t/**\n\t * Timestamp or date of the snowflake to generate\n\t * @default Date.now()\n\t */\n\ttimestamp?: number | bigint | Date;\n\n\t/**\n\t * The increment to use\n\t * @default 0n\n\t * @remark keep in mind that this bigint is auto-incremented between generate calls\n\t */\n\tincrement?: bigint;\n\n\t/**\n\t * The worker ID to use, will be truncated to 5 bits (0-31)\n\t * @default 0n\n\t */\n\tworkerId?: bigint;\n\n\t/**\n\t * The process ID to use, will be truncated to 5 bits (0-31)\n\t * @default 1n\n\t */\n\tprocessId?: bigint;\n}\n\n/**\n * Object returned by Snowflake#deconstruct\n */\nexport interface DeconstructedSnowflake {\n\t/**\n\t * The id in BigInt form\n\t */\n\tid: bigint;\n\n\t/**\n\t * The timestamp stored in the snowflake\n\t */\n\ttimestamp: bigint;\n\n\t/**\n\t * The worker id stored in the snowflake\n\t */\n\tworkerId: bigint;\n\n\t/**\n\t * The process id stored in the snowflake\n\t */\n\tprocessId: bigint;\n\n\t/**\n\t * The increment stored in the snowflake\n\t */\n\tincrement: bigint;\n\n\t/**\n\t * The epoch to use in the snowflake\n\t */\n\tepoch: bigint;\n}\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Discord's snowflake epoch\n *\n * Which is 2015-01-01 at 00:00:00.000 UTC+0, {@linkplain https://discord.com/developers/docs/reference#snowflakes}\n */\nexport const DiscordSnowflake = new Snowflake(1420070400000n);\n","import { Snowflake } from './Snowflake';\n\n/**\n * A class for parsing snowflake ids using Twitter's snowflake epoch\n *\n * Which is 2010-11-04 at 01:42:54.657 UTC+0, found in the archived snowflake repository {@linkplain https://github.com/twitter-archive/snowflake/blob/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231/src/main/scala/com/twitter/service/snowflake/IdWorker.scala#L25}\n */\nexport const TwitterSnowflake = new Snowflake(1288834974657n);\n"]} \ No newline at end of file diff --git a/node_modules/@sapphire/snowflake/package.json b/node_modules/@sapphire/snowflake/package.json new file mode 100644 index 0000000..de47d22 --- /dev/null +++ b/node_modules/@sapphire/snowflake/package.json @@ -0,0 +1,67 @@ +{ + "name": "@sapphire/snowflake", + "version": "3.4.0", + "description": "Deconstructs and generates snowflake IDs using BigInts", + "author": "@sapphire", + "license": "MIT", + "main": "dist/index.js", + "module": "dist/index.mjs", + "browser": "dist/index.global.js", + "unpkg": "dist/index.global.js", + "types": "dist/index.d.ts", + "exports": { + "import": "./dist/index.mjs", + "require": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "sideEffects": false, + "homepage": "https://github.com/sapphiredev/utilities/tree/main/packages/snowflake", + "scripts": { + "test": "vitest run", + "lint": "eslint src tests --ext ts --fix -c ../../.eslintrc", + "build": "tsup", + "docs": "typedoc-json-parser", + "prepack": "yarn build", + "bump": "cliff-jumper", + "check-update": "cliff-jumper --dry-run" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sapphiredev/utilities.git", + "directory": "packages/snowflake" + }, + "files": [ + "dist/**/*.js*", + "dist/**/*.mjs*", + "dist/**/*.d*" + ], + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + }, + "keywords": [ + "@sapphire/snowflake", + "bot", + "typescript", + "ts", + "yarn", + "discord", + "sapphire", + "standalone" + ], + "bugs": { + "url": "https://github.com/sapphiredev/utilities/issues" + }, + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@favware/cliff-jumper": "^1.9.0", + "@vitest/coverage-c8": "^0.26.2", + "tsup": "^6.5.0", + "typedoc": "^0.23.23", + "typedoc-json-parser": "^7.0.2", + "typescript": "^4.9.4", + "vitest": "^0.26.2" + } +} \ No newline at end of file diff --git a/node_modules/@sindresorhus/is/dist/index.d.ts b/node_modules/@sindresorhus/is/dist/index.d.ts new file mode 100644 index 0000000..e94d30b --- /dev/null +++ b/node_modules/@sindresorhus/is/dist/index.d.ts @@ -0,0 +1,132 @@ +/// +/// +/// +/// +/// +declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +declare type Primitive = null | undefined | string | number | boolean | Symbol; +export interface ArrayLike { + length: number; +} +export interface Class { + new (...args: any[]): T; +} +declare type DomElement = object & { + nodeType: 1; + nodeName: string; +}; +declare type NodeStream = object & { + pipe: Function; +}; +export declare const enum TypeName { + null = "null", + boolean = "boolean", + undefined = "undefined", + string = "string", + number = "number", + symbol = "symbol", + Function = "Function", + GeneratorFunction = "GeneratorFunction", + AsyncFunction = "AsyncFunction", + Observable = "Observable", + Array = "Array", + Buffer = "Buffer", + Object = "Object", + RegExp = "RegExp", + Date = "Date", + Error = "Error", + Map = "Map", + Set = "Set", + WeakMap = "WeakMap", + WeakSet = "WeakSet", + Int8Array = "Int8Array", + Uint8Array = "Uint8Array", + Uint8ClampedArray = "Uint8ClampedArray", + Int16Array = "Int16Array", + Uint16Array = "Uint16Array", + Int32Array = "Int32Array", + Uint32Array = "Uint32Array", + Float32Array = "Float32Array", + Float64Array = "Float64Array", + ArrayBuffer = "ArrayBuffer", + SharedArrayBuffer = "SharedArrayBuffer", + DataView = "DataView", + Promise = "Promise", + URL = "URL" +} +declare function is(value: unknown): TypeName; +declare namespace is { + const undefined: (value: unknown) => value is undefined; + const string: (value: unknown) => value is string; + const number: (value: unknown) => value is number; + const function_: (value: unknown) => value is Function; + const null_: (value: unknown) => value is null; + const class_: (value: unknown) => value is Class; + const boolean: (value: unknown) => value is boolean; + const symbol: (value: unknown) => value is Symbol; + const numericString: (value: unknown) => boolean; + const array: (arg: any) => arg is any[]; + const buffer: (input: unknown) => input is Buffer; + const nullOrUndefined: (value: unknown) => value is null | undefined; + const object: (value: unknown) => value is object; + const iterable: (value: unknown) => value is IterableIterator; + const asyncIterable: (value: unknown) => value is AsyncIterableIterator; + const generator: (value: unknown) => value is Generator; + const nativePromise: (value: unknown) => value is Promise; + const promise: (value: unknown) => value is Promise; + const generatorFunction: (value: unknown) => value is GeneratorFunction; + const asyncFunction: (value: unknown) => value is Function; + const boundFunction: (value: unknown) => value is Function; + const regExp: (value: unknown) => value is RegExp; + const date: (value: unknown) => value is Date; + const error: (value: unknown) => value is Error; + const map: (value: unknown) => value is Map; + const set: (value: unknown) => value is Set; + const weakMap: (value: unknown) => value is WeakMap; + const weakSet: (value: unknown) => value is WeakSet; + const int8Array: (value: unknown) => value is Int8Array; + const uint8Array: (value: unknown) => value is Uint8Array; + const uint8ClampedArray: (value: unknown) => value is Uint8ClampedArray; + const int16Array: (value: unknown) => value is Int16Array; + const uint16Array: (value: unknown) => value is Uint16Array; + const int32Array: (value: unknown) => value is Int32Array; + const uint32Array: (value: unknown) => value is Uint32Array; + const float32Array: (value: unknown) => value is Float32Array; + const float64Array: (value: unknown) => value is Float64Array; + const arrayBuffer: (value: unknown) => value is ArrayBuffer; + const sharedArrayBuffer: (value: unknown) => value is SharedArrayBuffer; + const dataView: (value: unknown) => value is DataView; + const directInstanceOf: (instance: unknown, klass: Class) => instance is T; + const urlInstance: (value: unknown) => value is URL; + const urlString: (value: unknown) => boolean; + const truthy: (value: unknown) => boolean; + const falsy: (value: unknown) => boolean; + const nan: (value: unknown) => boolean; + const primitive: (value: unknown) => value is Primitive; + const integer: (value: unknown) => value is number; + const safeInteger: (value: unknown) => value is number; + const plainObject: (value: unknown) => boolean; + const typedArray: (value: unknown) => value is TypedArray; + const arrayLike: (value: unknown) => value is ArrayLike; + const inRange: (value: number, range: number | number[]) => boolean; + const domElement: (value: unknown) => value is DomElement; + const observable: (value: unknown) => boolean; + const nodeStream: (value: unknown) => value is NodeStream; + const infinite: (value: unknown) => boolean; + const even: (value: number) => boolean; + const odd: (value: number) => boolean; + const emptyArray: (value: unknown) => boolean; + const nonEmptyArray: (value: unknown) => boolean; + const emptyString: (value: unknown) => boolean; + const nonEmptyString: (value: unknown) => boolean; + const emptyStringOrWhitespace: (value: unknown) => boolean; + const emptyObject: (value: unknown) => boolean; + const nonEmptyObject: (value: unknown) => boolean; + const emptySet: (value: unknown) => boolean; + const nonEmptySet: (value: unknown) => boolean; + const emptyMap: (value: unknown) => boolean; + const nonEmptyMap: (value: unknown) => boolean; + const any: (predicate: unknown, ...values: unknown[]) => boolean; + const all: (predicate: unknown, ...values: unknown[]) => boolean; +} +export default is; diff --git a/node_modules/@sindresorhus/is/dist/index.js b/node_modules/@sindresorhus/is/dist/index.js new file mode 100644 index 0000000..3cbafae --- /dev/null +++ b/node_modules/@sindresorhus/is/dist/index.js @@ -0,0 +1,245 @@ +"use strict"; +/// +/// +/// +/// +Object.defineProperty(exports, "__esModule", { value: true }); +// TODO: Use the `URL` global when targeting Node.js 10 +// tslint:disable-next-line +const URLGlobal = typeof URL === 'undefined' ? require('url').URL : URL; +const toString = Object.prototype.toString; +const isOfType = (type) => (value) => typeof value === type; +const isBuffer = (input) => !is.nullOrUndefined(input) && !is.nullOrUndefined(input.constructor) && is.function_(input.constructor.isBuffer) && input.constructor.isBuffer(input); +const getObjectType = (value) => { + const objectName = toString.call(value).slice(8, -1); + if (objectName) { + return objectName; + } + return null; +}; +const isObjectOfType = (type) => (value) => getObjectType(value) === type; +function is(value) { + switch (value) { + case null: + return "null" /* null */; + case true: + case false: + return "boolean" /* boolean */; + default: + } + switch (typeof value) { + case 'undefined': + return "undefined" /* undefined */; + case 'string': + return "string" /* string */; + case 'number': + return "number" /* number */; + case 'symbol': + return "symbol" /* symbol */; + default: + } + if (is.function_(value)) { + return "Function" /* Function */; + } + if (is.observable(value)) { + return "Observable" /* Observable */; + } + if (Array.isArray(value)) { + return "Array" /* Array */; + } + if (isBuffer(value)) { + return "Buffer" /* Buffer */; + } + const tagType = getObjectType(value); + if (tagType) { + return tagType; + } + if (value instanceof String || value instanceof Boolean || value instanceof Number) { + throw new TypeError('Please don\'t use object wrappers for primitive types'); + } + return "Object" /* Object */; +} +(function (is) { + // tslint:disable-next-line:strict-type-predicates + const isObject = (value) => typeof value === 'object'; + // tslint:disable:variable-name + is.undefined = isOfType('undefined'); + is.string = isOfType('string'); + is.number = isOfType('number'); + is.function_ = isOfType('function'); + // tslint:disable-next-line:strict-type-predicates + is.null_ = (value) => value === null; + is.class_ = (value) => is.function_(value) && value.toString().startsWith('class '); + is.boolean = (value) => value === true || value === false; + is.symbol = isOfType('symbol'); + // tslint:enable:variable-name + is.numericString = (value) => is.string(value) && value.length > 0 && !Number.isNaN(Number(value)); + is.array = Array.isArray; + is.buffer = isBuffer; + is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value); + is.object = (value) => !is.nullOrUndefined(value) && (is.function_(value) || isObject(value)); + is.iterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.iterator]); + is.asyncIterable = (value) => !is.nullOrUndefined(value) && is.function_(value[Symbol.asyncIterator]); + is.generator = (value) => is.iterable(value) && is.function_(value.next) && is.function_(value.throw); + is.nativePromise = (value) => isObjectOfType("Promise" /* Promise */)(value); + const hasPromiseAPI = (value) => !is.null_(value) && + isObject(value) && + is.function_(value.then) && + is.function_(value.catch); + is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value); + is.generatorFunction = isObjectOfType("GeneratorFunction" /* GeneratorFunction */); + is.asyncFunction = isObjectOfType("AsyncFunction" /* AsyncFunction */); + is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype'); + is.regExp = isObjectOfType("RegExp" /* RegExp */); + is.date = isObjectOfType("Date" /* Date */); + is.error = isObjectOfType("Error" /* Error */); + is.map = (value) => isObjectOfType("Map" /* Map */)(value); + is.set = (value) => isObjectOfType("Set" /* Set */)(value); + is.weakMap = (value) => isObjectOfType("WeakMap" /* WeakMap */)(value); + is.weakSet = (value) => isObjectOfType("WeakSet" /* WeakSet */)(value); + is.int8Array = isObjectOfType("Int8Array" /* Int8Array */); + is.uint8Array = isObjectOfType("Uint8Array" /* Uint8Array */); + is.uint8ClampedArray = isObjectOfType("Uint8ClampedArray" /* Uint8ClampedArray */); + is.int16Array = isObjectOfType("Int16Array" /* Int16Array */); + is.uint16Array = isObjectOfType("Uint16Array" /* Uint16Array */); + is.int32Array = isObjectOfType("Int32Array" /* Int32Array */); + is.uint32Array = isObjectOfType("Uint32Array" /* Uint32Array */); + is.float32Array = isObjectOfType("Float32Array" /* Float32Array */); + is.float64Array = isObjectOfType("Float64Array" /* Float64Array */); + is.arrayBuffer = isObjectOfType("ArrayBuffer" /* ArrayBuffer */); + is.sharedArrayBuffer = isObjectOfType("SharedArrayBuffer" /* SharedArrayBuffer */); + is.dataView = isObjectOfType("DataView" /* DataView */); + is.directInstanceOf = (instance, klass) => Object.getPrototypeOf(instance) === klass.prototype; + is.urlInstance = (value) => isObjectOfType("URL" /* URL */)(value); + is.urlString = (value) => { + if (!is.string(value)) { + return false; + } + try { + new URLGlobal(value); // tslint:disable-line no-unused-expression + return true; + } + catch (_a) { + return false; + } + }; + is.truthy = (value) => Boolean(value); + is.falsy = (value) => !value; + is.nan = (value) => Number.isNaN(value); + const primitiveTypes = new Set([ + 'undefined', + 'string', + 'number', + 'boolean', + 'symbol' + ]); + is.primitive = (value) => is.null_(value) || primitiveTypes.has(typeof value); + is.integer = (value) => Number.isInteger(value); + is.safeInteger = (value) => Number.isSafeInteger(value); + is.plainObject = (value) => { + // From: https://github.com/sindresorhus/is-plain-obj/blob/master/index.js + let prototype; + return getObjectType(value) === "Object" /* Object */ && + (prototype = Object.getPrototypeOf(value), prototype === null || // tslint:disable-line:ban-comma-operator + prototype === Object.getPrototypeOf({})); + }; + const typedArrayTypes = new Set([ + "Int8Array" /* Int8Array */, + "Uint8Array" /* Uint8Array */, + "Uint8ClampedArray" /* Uint8ClampedArray */, + "Int16Array" /* Int16Array */, + "Uint16Array" /* Uint16Array */, + "Int32Array" /* Int32Array */, + "Uint32Array" /* Uint32Array */, + "Float32Array" /* Float32Array */, + "Float64Array" /* Float64Array */ + ]); + is.typedArray = (value) => { + const objectType = getObjectType(value); + if (objectType === null) { + return false; + } + return typedArrayTypes.has(objectType); + }; + const isValidLength = (value) => is.safeInteger(value) && value > -1; + is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length); + is.inRange = (value, range) => { + if (is.number(range)) { + return value >= Math.min(0, range) && value <= Math.max(range, 0); + } + if (is.array(range) && range.length === 2) { + return value >= Math.min(...range) && value <= Math.max(...range); + } + throw new TypeError(`Invalid range: ${JSON.stringify(range)}`); + }; + const NODE_TYPE_ELEMENT = 1; + const DOM_PROPERTIES_TO_CHECK = [ + 'innerHTML', + 'ownerDocument', + 'style', + 'attributes', + 'nodeValue' + ]; + is.domElement = (value) => is.object(value) && value.nodeType === NODE_TYPE_ELEMENT && is.string(value.nodeName) && + !is.plainObject(value) && DOM_PROPERTIES_TO_CHECK.every(property => property in value); + is.observable = (value) => { + if (!value) { + return false; + } + if (value[Symbol.observable] && value === value[Symbol.observable]()) { + return true; + } + if (value['@@observable'] && value === value['@@observable']()) { + return true; + } + return false; + }; + is.nodeStream = (value) => !is.nullOrUndefined(value) && isObject(value) && is.function_(value.pipe) && !is.observable(value); + is.infinite = (value) => value === Infinity || value === -Infinity; + const isAbsoluteMod2 = (rem) => (value) => is.integer(value) && Math.abs(value % 2) === rem; + is.even = isAbsoluteMod2(0); + is.odd = isAbsoluteMod2(1); + const isWhiteSpaceString = (value) => is.string(value) && /\S/.test(value) === false; + is.emptyArray = (value) => is.array(value) && value.length === 0; + is.nonEmptyArray = (value) => is.array(value) && value.length > 0; + is.emptyString = (value) => is.string(value) && value.length === 0; + is.nonEmptyString = (value) => is.string(value) && value.length > 0; + is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value); + is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0; + is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0; + is.emptySet = (value) => is.set(value) && value.size === 0; + is.nonEmptySet = (value) => is.set(value) && value.size > 0; + is.emptyMap = (value) => is.map(value) && value.size === 0; + is.nonEmptyMap = (value) => is.map(value) && value.size > 0; + const predicateOnArray = (method, predicate, values) => { + if (is.function_(predicate) === false) { + throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`); + } + if (values.length === 0) { + throw new TypeError('Invalid number of values'); + } + return method.call(values, predicate); + }; + // tslint:disable variable-name + is.any = (predicate, ...values) => predicateOnArray(Array.prototype.some, predicate, values); + is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values); + // tslint:enable variable-name +})(is || (is = {})); +// Some few keywords are reserved, but we'll populate them for Node.js users +// See https://github.com/Microsoft/TypeScript/issues/2536 +Object.defineProperties(is, { + class: { + value: is.class_ + }, + function: { + value: is.function_ + }, + null: { + value: is.null_ + } +}); +exports.default = is; +// For CommonJS default export support +module.exports = is; +module.exports.default = is; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@sindresorhus/is/dist/index.js.map b/node_modules/@sindresorhus/is/dist/index.js.map new file mode 100644 index 0000000..cd827fc --- /dev/null +++ b/node_modules/@sindresorhus/is/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../source/index.ts"],"names":[],"mappings":";AAAA,6BAA6B;AAC7B,0CAA0C;AAC1C,2CAA2C;AAC3C,0BAA0B;;AAE1B,uDAAuD;AACvD,2BAA2B;AAC3B,MAAM,SAAS,GAAG,OAAO,GAAG,KAAK,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;AAqDxE,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC;AAC3C,MAAM,QAAQ,GAAG,CAAI,IAAY,EAAE,EAAE,CAAC,CAAC,KAAc,EAAc,EAAE,CAAC,OAAO,KAAK,KAAK,IAAI,CAAC;AAC5F,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAmB,EAAE,CAAC,CAAC,EAAE,CAAC,eAAe,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,eAAe,CAAE,KAAgB,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,SAAS,CAAE,KAAgB,CAAC,WAAW,CAAC,QAAQ,CAAC,IAAK,KAAgB,CAAC,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAEhP,MAAM,aAAa,GAAG,CAAC,KAAc,EAAmB,EAAE;IACzD,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAErD,IAAI,UAAU,EAAE;QACf,OAAO,UAAsB,CAAC;KAC9B;IAED,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,cAAc,GAAG,CA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CAAC,EAAE,EAAE;IAC3B,KAAK,EAAE;QACN,KAAK,EAAE,EAAE,CAAC,MAAM;KAChB;IACD,QAAQ,EAAE;QACT,KAAK,EAAE,EAAE,CAAC,SAAS;KACnB;IACD,IAAI,EAAE;QACL,KAAK,EAAE,EAAE,CAAC,KAAK;KACf;CACD,CAAC,CAAC;AAEH,kBAAe,EAAE,CAAC;AAElB,sCAAsC;AACtC,MAAM,CAAC,OAAO,GAAG,EAAE,CAAC;AACpB,MAAM,CAAC,OAAO,CAAC,OAAO,GAAG,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@sindresorhus/is/license b/node_modules/@sindresorhus/is/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/@sindresorhus/is/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/@sindresorhus/is/package.json b/node_modules/@sindresorhus/is/package.json new file mode 100644 index 0000000..14454ac --- /dev/null +++ b/node_modules/@sindresorhus/is/package.json @@ -0,0 +1,99 @@ +{ + "_args": [ + [ + "@sindresorhus/is@0.14.0", + "/home/other/discord_bot" + ] + ], + "_from": "@sindresorhus/is@0.14.0", + "_id": "@sindresorhus/is@0.14.0", + "_inBundle": false, + "_integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==", + "_location": "/@sindresorhus/is", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@sindresorhus/is@0.14.0", + "name": "@sindresorhus/is", + "escapedName": "@sindresorhus%2fis", + "scope": "@sindresorhus", + "rawSpec": "0.14.0", + "saveSpec": null, + "fetchSpec": "0.14.0" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", + "_spec": "0.14.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/is/issues" + }, + "description": "Type check values: `is.string('🦄') //=> true`", + "devDependencies": { + "@sindresorhus/tsconfig": "^0.1.0", + "@types/jsdom": "^11.12.0", + "@types/node": "^10.12.10", + "@types/tempy": "^0.2.0", + "@types/zen-observable": "^0.8.0", + "ava": "^0.25.0", + "del-cli": "^1.1.0", + "jsdom": "^11.6.2", + "rxjs": "^6.3.3", + "tempy": "^0.2.1", + "tslint": "^5.9.1", + "tslint-xo": "^0.10.0", + "typescript": "^3.2.1", + "zen-observable": "^0.8.8" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "dist" + ], + "homepage": "https://github.com/sindresorhus/is#readme", + "keywords": [ + "type", + "types", + "is", + "check", + "checking", + "validate", + "validation", + "utility", + "util", + "typeof", + "instanceof", + "object", + "assert", + "assertion", + "test", + "kind", + "primitive", + "verify", + "compare" + ], + "license": "MIT", + "main": "dist/index.js", + "name": "@sindresorhus/is", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/is.git" + }, + "scripts": { + "build": "del dist && tsc", + "lint": "tslint --format stylish --project .", + "prepublish": "npm run build && del dist/tests", + "test": "npm run lint && npm run build && ava dist/tests" + }, + "types": "dist/index.d.ts", + "version": "0.14.0" +} diff --git a/node_modules/@sindresorhus/is/readme.md b/node_modules/@sindresorhus/is/readme.md new file mode 100644 index 0000000..97c023b --- /dev/null +++ b/node_modules/@sindresorhus/is/readme.md @@ -0,0 +1,451 @@ +# is [![Build Status](https://travis-ci.org/sindresorhus/is.svg?branch=master)](https://travis-ci.org/sindresorhus/is) + +> Type check values: `is.string('🦄') //=> true` + + + + +## Install + +``` +$ npm install @sindresorhus/is +``` + + +## Usage + +```js +const is = require('@sindresorhus/is'); + +is('🦄'); +//=> 'string' + +is(new Map()); +//=> 'Map' + +is.number(6); +//=> true +``` + +When using `is` together with TypeScript, [type guards](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) are being used to infer the correct type inside if-else statements. + +```ts +import is from '@sindresorhus/is'; + +const padLeft = (value: string, padding: string | number) => { + if (is.number(padding)) { + // `padding` is typed as `number` + return Array(padding + 1).join(' ') + value; + } + + if (is.string(padding)) { + // `padding` is typed as `string` + return padding + value; + } + + throw new TypeError(`Expected 'padding' to be of type 'string' or 'number', got '${is(padding)}'.`); +} + +padLeft('🦄', 3); +//=> ' 🦄' + +padLeft('🦄', '🌈'); +//=> '🌈🦄' +``` + + +## API + +### is(value) + +Returns the type of `value`. + +Primitives are lowercase and object types are camelcase. + +Example: + +- `'undefined'` +- `'null'` +- `'string'` +- `'symbol'` +- `'Array'` +- `'Function'` +- `'Object'` + +Note: It will throw an error if you try to feed it object-wrapped primitives, as that's a bad practice. For example `new String('foo')`. + +### is.{method} + +All the below methods accept a value and returns a boolean for whether the value is of the desired type. + +#### Primitives + +##### .undefined(value) +##### .null(value) +##### .string(value) +##### .number(value) +##### .boolean(value) +##### .symbol(value) + +#### Built-in types + +##### .array(value) +##### .function(value) +##### .buffer(value) +##### .object(value) + +Keep in mind that [functions are objects too](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions). + +##### .numericString(value) + +Returns `true` for a string that represents a number. For example, `'42'` and `'-8'`. + +Note: `'NaN'` returns `false`, but `'Infinity'` and `'-Infinity'` return `true`. + +##### .regExp(value) +##### .date(value) +##### .error(value) +##### .nativePromise(value) +##### .promise(value) + +Returns `true` for any object with a `.then()` and `.catch()` method. Prefer this one over `.nativePromise()` as you usually want to allow userland promise implementations too. + +##### .generator(value) + +Returns `true` for any object that implements its own `.next()` and `.throw()` methods and has a function definition for `Symbol.iterator`. + +##### .generatorFunction(value) + +##### .asyncFunction(value) + +Returns `true` for any `async` function that can be called with the `await` operator. + +```js +is.asyncFunction(async () => {}); +// => true + +is.asyncFunction(() => {}); +// => false +``` + +##### .boundFunction(value) + +Returns `true` for any `bound` function. + +```js +is.boundFunction(() => {}); +// => true + +is.boundFunction(function () {}.bind(null)); +// => true + +is.boundFunction(function () {}); +// => false +``` + +##### .map(value) +##### .set(value) +##### .weakMap(value) +##### .weakSet(value) + +#### Typed arrays + +##### .int8Array(value) +##### .uint8Array(value) +##### .uint8ClampedArray(value) +##### .int16Array(value) +##### .uint16Array(value) +##### .int32Array(value) +##### .uint32Array(value) +##### .float32Array(value) +##### .float64Array(value) + +#### Structured data + +##### .arrayBuffer(value) +##### .sharedArrayBuffer(value) +##### .dataView(value) + +#### Emptiness + +##### .emptyString(value) + +Returns `true` if the value is a `string` and the `.length` is 0. + +##### .nonEmptyString(value) + +Returns `true` if the value is a `string` and the `.length` is more than 0. + +##### .emptyStringOrWhitespace(value) + +Returns `true` if `is.emptyString(value)` or if it's a `string` that is all whitespace. + +##### .emptyArray(value) + +Returns `true` if the value is an `Array` and the `.length` is 0. + +##### .nonEmptyArray(value) + +Returns `true` if the value is an `Array` and the `.length` is more than 0. + +##### .emptyObject(value) + +Returns `true` if the value is an `Object` and `Object.keys(value).length` is 0. + +Please note that `Object.keys` returns only own enumerable properties. Hence something like this can happen: + +```js +const object1 = {}; + +Object.defineProperty(object1, 'property1', { + value: 42, + writable: true, + enumerable: false, + configurable: true +}); + +is.emptyObject(object1); +// => true +``` + +##### .nonEmptyObject(value) + +Returns `true` if the value is an `Object` and `Object.keys(value).length` is more than 0. + +##### .emptySet(value) + +Returns `true` if the value is a `Set` and the `.size` is 0. + +##### .nonEmptySet(Value) + +Returns `true` if the value is a `Set` and the `.size` is more than 0. + +##### .emptyMap(value) + +Returns `true` if the value is a `Map` and the `.size` is 0. + +##### .nonEmptyMap(value) + +Returns `true` if the value is a `Map` and the `.size` is more than 0. + +#### Miscellaneous + +##### .directInstanceOf(value, class) + +Returns `true` if `value` is a direct instance of `class`. + +```js +is.directInstanceOf(new Error(), Error); +//=> true + +class UnicornError extends Error {} + +is.directInstanceOf(new UnicornError(), Error); +//=> false +``` + +##### .urlInstance(value) + +Returns `true` if `value` is an instance of the [`URL` class](https://developer.mozilla.org/en-US/docs/Web/API/URL). + +```js +const url = new URL('https://example.com'); + +is.urlInstance(url); +//=> true +``` + +### .url(value) + +Returns `true` if `value` is a URL string. + +Note: this only does basic checking using the [`URL` class](https://developer.mozilla.org/en-US/docs/Web/API/URL) constructor. + +```js +const url = 'https://example.com'; + +is.url(url); +//=> true + +is.url(new URL(url)); +//=> false +``` + +##### .truthy(value) + +Returns `true` for all values that evaluate to true in a boolean context: + +```js +is.truthy('🦄'); +//=> true + +is.truthy(undefined); +//=> false +``` + +##### .falsy(value) + +Returns `true` if `value` is one of: `false`, `0`, `''`, `null`, `undefined`, `NaN`. + +##### .nan(value) +##### .nullOrUndefined(value) +##### .primitive(value) + +JavaScript primitives are as follows: `null`, `undefined`, `string`, `number`, `boolean`, `symbol`. + +##### .integer(value) + +##### .safeInteger(value) + +Returns `true` if `value` is a [safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + +##### .plainObject(value) + +An object is plain if it's created by either `{}`, `new Object()`, or `Object.create(null)`. + +##### .iterable(value) +##### .asyncIterable(value) +##### .class(value) + +Returns `true` for instances created by a class. + +##### .typedArray(value) + +##### .arrayLike(value) + +A `value` is array-like if it is not a function and has a `value.length` that is a safe integer greater than or equal to 0. + +```js +is.arrayLike(document.forms); +//=> true + +function foo() { + is.arrayLike(arguments); + //=> true +} +foo(); +``` + +##### .inRange(value, range) + +Check if `value` (number) is in the given `range`. The range is an array of two values, lower bound and upper bound, in no specific order. + +```js +is.inRange(3, [0, 5]); +is.inRange(3, [5, 0]); +is.inRange(0, [-2, 2]); +``` + +##### .inRange(value, upperBound) + +Check if `value` (number) is in the range of `0` to `upperBound`. + +```js +is.inRange(3, 10); +``` + +##### .domElement(value) + +Returns `true` if `value` is a DOM Element. + +##### .nodeStream(value) + +Returns `true` if `value` is a Node.js [stream](https://nodejs.org/api/stream.html). + +```js +const fs = require('fs'); + +is.nodeStream(fs.createReadStream('unicorn.png')); +//=> true +``` + +##### .observable(value) + +Returns `true` if `value` is an `Observable`. + +```js +const {Observable} = require('rxjs'); + +is.observable(new Observable()); +//=> true +``` + +##### .infinite(value) + +Check if `value` is `Infinity` or `-Infinity`. + +##### .even(value) + +Returns `true` if `value` is an even integer. + +##### .odd(value) + +Returns `true` if `value` is an odd integer. + +##### .any(predicate, ...values) + +Returns `true` if **any** of the input `values` returns true in the `predicate`: + +```js +is.any(is.string, {}, true, '🦄'); +//=> true + +is.any(is.boolean, 'unicorns', [], new Map()); +//=> false +``` + +##### .all(predicate, ...values) + +Returns `true` if **all** of the input `values` returns true in the `predicate`: + +```js +is.all(is.object, {}, new Map(), new Set()); +//=> true + +is.all(is.string, '🦄', [], 'unicorns'); +//=> false +``` + + +## FAQ + +### Why yet another type checking module? + +There are hundreds of type checking modules on npm, unfortunately, I couldn't find any that fit my needs: + +- Includes both type methods and ability to get the type +- Types of primitives returned as lowercase and object types as camelcase +- Covers all built-ins +- Unsurprising behavior +- Well-maintained +- Comprehensive test suite + +For the ones I found, pick 3 of these. + +The most common mistakes I noticed in these modules was using `instanceof` for type checking, forgetting that functions are objects, and omitting `symbol` as a primitive. + + +## Related + +- [ow](https://github.com/sindresorhus/ow) - Function argument validation for humans +- [is-stream](https://github.com/sindresorhus/is-stream) - Check if something is a Node.js stream +- [is-observable](https://github.com/sindresorhus/is-observable) - Check if a value is an Observable +- [file-type](https://github.com/sindresorhus/file-type) - Detect the file type of a Buffer/Uint8Array +- [is-ip](https://github.com/sindresorhus/is-ip) - Check if a string is an IP address +- [is-array-sorted](https://github.com/sindresorhus/is-array-sorted) - Check if an Array is sorted +- [is-error-constructor](https://github.com/sindresorhus/is-error-constructor) - Check if a value is an error constructor +- [is-empty-iterable](https://github.com/sindresorhus/is-empty-iterable) - Check if an Iterable is empty +- [is-blob](https://github.com/sindresorhus/is-blob) - Check if a value is a Blob - File-like object of immutable, raw data +- [has-emoji](https://github.com/sindresorhus/has-emoji) - Check whether a string has any emoji + + +## Created by + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Giora Guttsait](https://github.com/gioragutt) +- [Brandon Smith](https://github.com/brandon93s) + + +## License + +MIT diff --git a/node_modules/@szmarczak/http-timer/LICENSE b/node_modules/@szmarczak/http-timer/LICENSE new file mode 100755 index 0000000..15ad2e8 --- /dev/null +++ b/node_modules/@szmarczak/http-timer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Szymon Marczak + +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/@szmarczak/http-timer/README.md b/node_modules/@szmarczak/http-timer/README.md new file mode 100755 index 0000000..13279ed --- /dev/null +++ b/node_modules/@szmarczak/http-timer/README.md @@ -0,0 +1,70 @@ +# http-timer +> Timings for HTTP requests + +[![Build Status](https://travis-ci.org/szmarczak/http-timer.svg?branch=master)](https://travis-ci.org/szmarczak/http-timer) +[![Coverage Status](https://coveralls.io/repos/github/szmarczak/http-timer/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/http-timer?branch=master) +[![install size](https://packagephobia.now.sh/badge?p=@szmarczak/http-timer)](https://packagephobia.now.sh/result?p=@szmarczak/http-timer) + +Inspired by the [`request` package](https://github.com/request/request). + +## Usage +```js +'use strict'; +const https = require('https'); +const timer = require('@szmarczak/http-timer'); + +const request = https.get('https://httpbin.org/anything'); +const timings = timer(request); + +request.on('response', response => { + response.on('data', () => {}); // Consume the data somehow + response.on('end', () => { + console.log(timings); + }); +}); + +// { start: 1535708511443, +// socket: 1535708511444, +// lookup: 1535708511444, +// connect: 1535708511582, +// upload: 1535708511887, +// response: 1535708512037, +// end: 1535708512040, +// phases: +// { wait: 1, +// dns: 0, +// tcp: 138, +// request: 305, +// firstByte: 150, +// download: 3, +// total: 597 } } +``` + +## API + +### timer(request) + +Returns: `Object` + +- `start` - Time when the request started. +- `socket` - Time when a socket was assigned to the request. +- `lookup` - Time when the DNS lookup finished. +- `connect` - Time when the socket successfully connected. +- `upload` - Time when the request finished uploading. +- `response` - Time when the request fired the `response` event. +- `end` - Time when the response fired the `end` event. +- `error` - Time when the request fired the `error` event. +- `phases` + - `wait` - `timings.socket - timings.start` + - `dns` - `timings.lookup - timings.socket` + - `tcp` - `timings.connect - timings.lookup` + - `request` - `timings.upload - timings.connect` + - `firstByte` - `timings.response - timings.upload` + - `download` - `timings.end - timings.response` + - `total` - `timings.end - timings.start` or `timings.error - timings.start` + +**Note**: The time is a `number` representing the milliseconds elapsed since the UNIX epoch. + +## License + +MIT diff --git a/node_modules/@szmarczak/http-timer/package.json b/node_modules/@szmarczak/http-timer/package.json new file mode 100755 index 0000000..3d98bb7 --- /dev/null +++ b/node_modules/@szmarczak/http-timer/package.json @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "@szmarczak/http-timer@1.1.2", + "/home/other/discord_bot" + ] + ], + "_from": "@szmarczak/http-timer@1.1.2", + "_id": "@szmarczak/http-timer@1.1.2", + "_inBundle": false, + "_integrity": "sha512-XIB2XbzHTN6ieIjfIMV9hlVcfPU26s2vafYWQcZHWXHOxiaRZYEDKEwdl129Zyg50+foYV2jCgtrqSA6qNuNSA==", + "_location": "/@szmarczak/http-timer", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@szmarczak/http-timer@1.1.2", + "name": "@szmarczak/http-timer", + "escapedName": "@szmarczak%2fhttp-timer", + "scope": "@szmarczak", + "rawSpec": "1.1.2", + "saveSpec": null, + "fetchSpec": "1.1.2" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-1.1.2.tgz", + "_spec": "1.1.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "Szymon Marczak" + }, + "bugs": { + "url": "https://github.com/szmarczak/http-timer/issues" + }, + "dependencies": { + "defer-to-connect": "^1.0.1" + }, + "description": "Timings for HTTP requests", + "devDependencies": { + "ava": "^0.25.0", + "coveralls": "^3.0.2", + "nyc": "^12.0.2", + "p-event": "^2.1.0", + "xo": "^0.22.0" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "source" + ], + "homepage": "https://github.com/szmarczak/http-timer#readme", + "keywords": [ + "http", + "https", + "timer", + "timings" + ], + "license": "MIT", + "main": "source", + "name": "@szmarczak/http-timer", + "repository": { + "type": "git", + "url": "git+https://github.com/szmarczak/http-timer.git" + }, + "scripts": { + "coveralls": "nyc report --reporter=text-lcov | coveralls", + "test": "xo && nyc ava" + }, + "version": "1.1.2", + "xo": { + "rules": { + "unicorn/filename-case": "camelCase" + } + } +} diff --git a/node_modules/@szmarczak/http-timer/source/index.js b/node_modules/@szmarczak/http-timer/source/index.js new file mode 100755 index 0000000..e294580 --- /dev/null +++ b/node_modules/@szmarczak/http-timer/source/index.js @@ -0,0 +1,99 @@ +'use strict'; +const deferToConnect = require('defer-to-connect'); + +module.exports = request => { + const timings = { + start: Date.now(), + socket: null, + lookup: null, + connect: null, + upload: null, + response: null, + end: null, + error: null, + phases: { + wait: null, + dns: null, + tcp: null, + request: null, + firstByte: null, + download: null, + total: null + } + }; + + const handleError = origin => { + const emit = origin.emit.bind(origin); + origin.emit = (event, ...args) => { + // Catches the `error` event + if (event === 'error') { + timings.error = Date.now(); + timings.phases.total = timings.error - timings.start; + + origin.emit = emit; + } + + // Saves the original behavior + return emit(event, ...args); + }; + }; + + let uploadFinished = false; + const onUpload = () => { + timings.upload = Date.now(); + timings.phases.request = timings.upload - timings.connect; + }; + + handleError(request); + + request.once('socket', socket => { + timings.socket = Date.now(); + timings.phases.wait = timings.socket - timings.start; + + const lookupListener = () => { + timings.lookup = Date.now(); + timings.phases.dns = timings.lookup - timings.socket; + }; + + socket.once('lookup', lookupListener); + + deferToConnect(socket, () => { + timings.connect = Date.now(); + + if (timings.lookup === null) { + socket.removeListener('lookup', lookupListener); + timings.lookup = timings.connect; + timings.phases.dns = timings.lookup - timings.socket; + } + + timings.phases.tcp = timings.connect - timings.lookup; + + if (uploadFinished && !timings.upload) { + onUpload(); + } + }); + }); + + request.once('finish', () => { + uploadFinished = true; + + if (timings.connect) { + onUpload(); + } + }); + + request.once('response', response => { + timings.response = Date.now(); + timings.phases.firstByte = timings.response - timings.upload; + + handleError(response); + + response.once('end', () => { + timings.end = Date.now(); + timings.phases.download = timings.end - timings.response; + timings.phases.total = timings.end - timings.start; + }); + }); + + return timings; +}; diff --git a/node_modules/@tokenizer/token/README.md b/node_modules/@tokenizer/token/README.md new file mode 100644 index 0000000..4116049 --- /dev/null +++ b/node_modules/@tokenizer/token/README.md @@ -0,0 +1,19 @@ +[![npm version](https://badge.fury.io/js/%40tokenizer%2Ftoken.svg)](https://www.npmjs.com/package/@tokenizer/token) +[![npm downloads](http://img.shields.io/npm/dm/@tokenizer/token.svg)](https://npmcharts.com/compare/@tokenizer/token?interval=30) + +# @tokenizer/token + +TypeScript definition of an [strtok3](https://github.com/Borewit/strtok3) token. + +## Licence + +(The MIT License) + +Copyright (c) 2020 Borewit + +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/@tokenizer/token/index.d.ts b/node_modules/@tokenizer/token/index.d.ts new file mode 100644 index 0000000..3703b77 --- /dev/null +++ b/node_modules/@tokenizer/token/index.d.ts @@ -0,0 +1,30 @@ +/** + * Read-only token + * See https://github.com/Borewit/strtok3 for more information + */ +export interface IGetToken { + + /** + * Length of encoded token in bytes + */ + len: number; + + /** + * Decode value from buffer at offset + * @param array - Uint8Array to read the decoded value from + * @param offset - Decode offset + * @return decoded value + */ + get(array: Array, offset: number): Value; +} + +export interface IToken extends IGetToken { + /** + * Encode value to buffer + * @param array - Uint8Array to write the encoded value to + * @param offset - Buffer write offset + * @param value - Value to decode of type T + * @return offset plus number of bytes written + */ + put(array: Array, offset: number, value: Value): number +} diff --git a/node_modules/@tokenizer/token/package.json b/node_modules/@tokenizer/token/package.json new file mode 100644 index 0000000..4bb38fd --- /dev/null +++ b/node_modules/@tokenizer/token/package.json @@ -0,0 +1,33 @@ +{ + "name": "@tokenizer/token", + "version": "0.3.0", + "description": "TypeScript definition for strtok3 token", + "main": "", + "types": "index.d.ts", + "files": [ + "index.d.ts" + ], + "keywords": [ + "token", + "interface", + "tokenizer", + "TypeScript" + ], + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/Borewit/tokenizer-token.git" + }, + "bugs": { + "url": "https://github.com/Borewit/tokenizer-token/issues" + }, + "typeScriptVersion": "3.0", + "dependencies": {}, + "devDependencies": { + "@types/node": "^13.1.0" + } +} diff --git a/node_modules/@types/jsonwebtoken/LICENSE b/node_modules/@types/jsonwebtoken/LICENSE new file mode 100755 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/jsonwebtoken/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/@types/jsonwebtoken/README.md b/node_modules/@types/jsonwebtoken/README.md new file mode 100755 index 0000000..cd019a8 --- /dev/null +++ b/node_modules/@types/jsonwebtoken/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/jsonwebtoken` + +# Summary +This package contains type definitions for jsonwebtoken (https://github.com/auth0/node-jsonwebtoken). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jsonwebtoken. + +### Additional Details + * Last updated: Tue, 06 Jul 2021 21:33:49 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + * Global values: none + +# Credits +These definitions were written by [Maxime LUCE](https://github.com/SomaticIT), [Daniel Heim](https://github.com/danielheim), [Brice BERNARD](https://github.com/brikou), [Veli-Pekka Kestilä](https://github.com/vpk), [Daniel Parker](https://github.com/rlgod), [Kjell Dießel](https://github.com/kettil), [Robert Gajda](https://github.com/RunAge), [Nico Flaig](https://github.com/nflaig), [Linus Unnebäck](https://github.com/LinusU), [Ivan Sieder](https://github.com/ivansieder), [Piotr Błażejewicz](https://github.com/peterblazejewicz), and [Nandor Kraszlan](https://github.com/nandi95). diff --git a/node_modules/@types/jsonwebtoken/index.d.ts b/node_modules/@types/jsonwebtoken/index.d.ts new file mode 100755 index 0000000..de17ba3 --- /dev/null +++ b/node_modules/@types/jsonwebtoken/index.d.ts @@ -0,0 +1,243 @@ +// Type definitions for jsonwebtoken 8.5 +// Project: https://github.com/auth0/node-jsonwebtoken +// Definitions by: Maxime LUCE , +// Daniel Heim , +// Brice BERNARD , +// Veli-Pekka Kestilä , +// Daniel Parker , +// Kjell Dießel , +// Robert Gajda , +// Nico Flaig , +// Linus Unnebäck +// Ivan Sieder +// Piotr Błażejewicz +// Nandor Kraszlan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export class JsonWebTokenError extends Error { + inner: Error; + + constructor(message: string, error?: Error); +} + +export class TokenExpiredError extends JsonWebTokenError { + expiredAt: Date; + + constructor(message: string, expiredAt: Date); +} + +/** + * Thrown if current time is before the nbf claim. + */ +export class NotBeforeError extends JsonWebTokenError { + date: Date; + + constructor(message: string, date: Date); +} + +export interface SignOptions { + /** + * Signature algorithm. Could be one of these values : + * - HS256: HMAC using SHA-256 hash algorithm (default) + * - HS384: HMAC using SHA-384 hash algorithm + * - HS512: HMAC using SHA-512 hash algorithm + * - RS256: RSASSA using SHA-256 hash algorithm + * - RS384: RSASSA using SHA-384 hash algorithm + * - RS512: RSASSA using SHA-512 hash algorithm + * - ES256: ECDSA using P-256 curve and SHA-256 hash algorithm + * - ES384: ECDSA using P-384 curve and SHA-384 hash algorithm + * - ES512: ECDSA using P-521 curve and SHA-512 hash algorithm + * - none: No digital signature or MAC value included + */ + algorithm?: Algorithm | undefined; + keyid?: string | undefined; + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + expiresIn?: string | number | undefined; + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + notBefore?: string | number | undefined; + audience?: string | string[] | undefined; + subject?: string | undefined; + issuer?: string | undefined; + jwtid?: string | undefined; + mutatePayload?: boolean | undefined; + noTimestamp?: boolean | undefined; + header?: JwtHeader | undefined; + encoding?: string | undefined; +} + +export interface VerifyOptions { + algorithms?: Algorithm[] | undefined; + audience?: string | RegExp | Array | undefined; + clockTimestamp?: number | undefined; + clockTolerance?: number | undefined; + /** return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload. */ + complete?: boolean | undefined; + issuer?: string | string[] | undefined; + ignoreExpiration?: boolean | undefined; + ignoreNotBefore?: boolean | undefined; + jwtid?: string | undefined; + /** + * If you want to check `nonce` claim, provide a string value here. + * It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes)) + */ + nonce?: string | undefined; + subject?: string | undefined; + /** + * @deprecated + * Max age of token + */ + maxAge?: string | undefined; +} + +export interface DecodeOptions { + complete?: boolean | undefined; + json?: boolean | undefined; +} +export type VerifyErrors = + | JsonWebTokenError + | NotBeforeError + | TokenExpiredError; +export type VerifyCallback = ( + err: VerifyErrors | null, + decoded: T | undefined, +) => void; + +export type SignCallback = ( + err: Error | null, encoded: string | undefined +) => void; + +// standard names https://www.rfc-editor.org/rfc/rfc7515.html#section-4.1 +export interface JwtHeader { + alg: string | Algorithm; + typ?: string | undefined; + cty?: string | undefined; + crit?: Array> | undefined; + kid?: string | undefined; + jku?: string | undefined; + x5u?: string | string[] | undefined; + 'x5t#S256'?: string | undefined; + x5t?: string | undefined; + x5c?: string | string[] | undefined; +} + +// standard claims https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 +export interface JwtPayload { + [key: string]: any; + iss?: string | undefined; + sub?: string | undefined; + aud?: string | string[] | undefined; + exp?: number | undefined; + nbf?: number | undefined; + iat?: number | undefined; + jti?: string | undefined; +} + +export interface Jwt { + header: JwtHeader; + payload: JwtPayload; + signature: string; +} + +// https://github.com/auth0/node-jsonwebtoken#algorithms-supported +export type Algorithm = + "HS256" | "HS384" | "HS512" | + "RS256" | "RS384" | "RS512" | + "ES256" | "ES384" | "ES512" | + "PS256" | "PS384" | "PS512" | + "none"; + +export type SigningKeyCallback = ( + err: any, + signingKey?: Secret, +) => void; + +export type GetPublicKeyOrSecret = ( + header: JwtHeader, + callback: SigningKeyCallback +) => void; + +export type Secret = + | string + | Buffer + | { key: string | Buffer; passphrase: string }; + +/** + * Synchronously sign the given payload into a JSON Web Token string + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * returns - The JSON Web Token string + */ +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + options?: SignOptions, +): string; + +/** + * Sign the given payload into a JSON Web Token string + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * callback - Callback to get the encoded token on + */ +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + callback: SignCallback, +): void; +export function sign( + payload: string | Buffer | object, + secretOrPrivateKey: Secret, + options: SignOptions, + callback: SignCallback, +): void; + +/** + * Synchronously verify given token using a secret or a public key to get a decoded token + * token - JWT string to verify + * secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * [options] - Options for the verification + * returns - The decoded token. + */ +export function verify(token: string, secretOrPublicKey: Secret, options: VerifyOptions & { complete: true }): Jwt | string; +export function verify(token: string, secretOrPublicKey: Secret, options?: VerifyOptions): JwtPayload | string; + +/** + * Asynchronously verify given token using a secret or a public key to get a decoded token + * token - JWT string to verify + * secretOrPublicKey - A string or buffer containing either the secret for HMAC algorithms, + * or the PEM encoded public key for RSA and ECDSA. If jwt.verify is called asynchronous, + * secretOrPublicKey can be a function that should fetch the secret or public key + * [options] - Options for the verification + * callback - Callback to get the decoded token on + */ +export function verify( + token: string, + secretOrPublicKey: Secret | GetPublicKeyOrSecret, + callback?: VerifyCallback, +): void; +export function verify( + token: string, + secretOrPublicKey: Secret | GetPublicKeyOrSecret, + options?: VerifyOptions & { complete: true }, + callback?: VerifyCallback, +): void; +export function verify( + token: string, + secretOrPublicKey: Secret | GetPublicKeyOrSecret, + options?: VerifyOptions, + callback?: VerifyCallback, +): void; + +/** + * Returns the decoded payload without verifying if the signature is valid. + * token - JWT string to decode + * [options] - Options for decoding + * returns - The decoded Token + */ +export function decode(token: string, options: DecodeOptions & { complete: true }): null | Jwt; +export function decode(token: string, options: DecodeOptions & { json: true }): null | JwtPayload; +export function decode(token: string, options?: DecodeOptions): null | JwtPayload | string; diff --git a/node_modules/@types/jsonwebtoken/package.json b/node_modules/@types/jsonwebtoken/package.json new file mode 100755 index 0000000..0bbca20 --- /dev/null +++ b/node_modules/@types/jsonwebtoken/package.json @@ -0,0 +1,102 @@ +{ + "_args": [ + [ + "@types/jsonwebtoken@8.5.4", + "/home/other/discord_bot" + ] + ], + "_from": "@types/jsonwebtoken@8.5.4", + "_id": "@types/jsonwebtoken@8.5.4", + "_inBundle": false, + "_integrity": "sha512-4L8msWK31oXwdtC81RmRBAULd0ShnAHjBuKT9MRQpjP0piNrZdXyTRcKY9/UIfhGeKIT4PvF5amOOUbbT/9Wpg==", + "_location": "/@types/jsonwebtoken", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@types/jsonwebtoken@8.5.4", + "name": "@types/jsonwebtoken", + "escapedName": "@types%2fjsonwebtoken", + "scope": "@types", + "rawSpec": "8.5.4", + "saveSpec": null, + "fetchSpec": "8.5.4" + }, + "_requiredBy": [ + "/getstream" + ], + "_resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-8.5.4.tgz", + "_spec": "8.5.4", + "_where": "/home/other/discord_bot", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "contributors": [ + { + "name": "Maxime LUCE", + "url": "https://github.com/SomaticIT" + }, + { + "name": "Daniel Heim", + "url": "https://github.com/danielheim" + }, + { + "name": "Brice BERNARD", + "url": "https://github.com/brikou" + }, + { + "name": "Veli-Pekka Kestilä", + "url": "https://github.com/vpk" + }, + { + "name": "Daniel Parker", + "url": "https://github.com/rlgod" + }, + { + "name": "Kjell Dießel", + "url": "https://github.com/kettil" + }, + { + "name": "Robert Gajda", + "url": "https://github.com/RunAge" + }, + { + "name": "Nico Flaig", + "url": "https://github.com/nflaig" + }, + { + "name": "Linus Unnebäck", + "url": "https://github.com/LinusU" + }, + { + "name": "Ivan Sieder", + "url": "https://github.com/ivansieder" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Nandor Kraszlan", + "url": "https://github.com/nandi95" + } + ], + "dependencies": { + "@types/node": "*" + }, + "description": "TypeScript definitions for jsonwebtoken", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jsonwebtoken", + "license": "MIT", + "main": "", + "name": "@types/jsonwebtoken", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/jsonwebtoken" + }, + "scripts": {}, + "typeScriptVersion": "3.6", + "types": "index.d.ts", + "typesPublisherContentHash": "58925f3bde0aa9e2a8a501c23b2e2c764ea25d09e5a171b8ed259b5a4d0038ef", + "version": "8.5.4" +} diff --git a/node_modules/@types/jwt-decode/LICENSE b/node_modules/@types/jwt-decode/LICENSE new file mode 100644 index 0000000..2107107 --- /dev/null +++ b/node_modules/@types/jwt-decode/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. All rights reserved. + + 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/@types/jwt-decode/README.md b/node_modules/@types/jwt-decode/README.md new file mode 100644 index 0000000..1aebe7e --- /dev/null +++ b/node_modules/@types/jwt-decode/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/jwt-decode` + +# Summary +This package contains type definitions for jwt-decode (https://github.com/auth0/jwt-decode). + +# Details +Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jwt-decode + +Additional Details + * Last updated: Tue, 20 Jun 2017 20:20:01 GMT + * Dependencies: none + * Global values: jwt_decode + +# Credits +These definitions were written by Giedrius Grabauskas , Mads Madsen . diff --git a/node_modules/@types/jwt-decode/index.d.ts b/node_modules/@types/jwt-decode/index.d.ts new file mode 100644 index 0000000..73dacb3 --- /dev/null +++ b/node_modules/@types/jwt-decode/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for jwt-decode 2.2 +// Project: https://github.com/auth0/jwt-decode +// Definitions by: Giedrius Grabauskas , Mads Madsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace JwtDecode { + interface Options { + header: boolean; + } +} + +declare function JwtDecode(token: string, options?: JwtDecode.Options): TTokenDto; + +export = JwtDecode; +export as namespace jwt_decode; diff --git a/node_modules/@types/jwt-decode/package.json b/node_modules/@types/jwt-decode/package.json new file mode 100644 index 0000000..4696193 --- /dev/null +++ b/node_modules/@types/jwt-decode/package.json @@ -0,0 +1,59 @@ +{ + "_args": [ + [ + "@types/jwt-decode@2.2.1", + "/home/other/discord_bot" + ] + ], + "_from": "@types/jwt-decode@2.2.1", + "_id": "@types/jwt-decode@2.2.1", + "_inBundle": false, + "_integrity": "sha512-aWw2YTtAdT7CskFyxEX2K21/zSDStuf/ikI3yBqmwpwJF0pS+/IX5DWv+1UFffZIbruP6cnT9/LAJV1gFwAT1A==", + "_location": "/@types/jwt-decode", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@types/jwt-decode@2.2.1", + "name": "@types/jwt-decode", + "escapedName": "@types%2fjwt-decode", + "scope": "@types", + "rawSpec": "2.2.1", + "saveSpec": null, + "fetchSpec": "2.2.1" + }, + "_requiredBy": [ + "/getstream" + ], + "_resolved": "https://registry.npmjs.org/@types/jwt-decode/-/jwt-decode-2.2.1.tgz", + "_spec": "2.2.1", + "_where": "/home/other/discord_bot", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "contributors": [ + { + "name": "Giedrius Grabauskas", + "url": "https://github.com/GiedriusGrabauskas" + }, + { + "name": "Mads Madsen", + "url": "https://github.com/madsmadsen" + } + ], + "dependencies": {}, + "description": "TypeScript definitions for jwt-decode", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/jwt-decode", + "peerDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.0", + "typesPublisherContentHash": "1e39f59c1791abeafac1233eca61c2803a96776546dc8e77fd63a556ce80e3a5", + "version": "2.2.1" +} diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100755 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + 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/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100755 index 0000000..8fbf6da --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (http://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Thu, 12 Aug 2021 20:31:25 GMT + * Dependencies: none + * Global values: `AbortController`, `AbortSignal`, `__dirname`, `__filename`, `console`, `exports`, `gc`, `global`, `module`, `process`, `require` + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Hoàng Văn Khải](https://github.com/KSXGitHub), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Minh Son Nguyen](https://github.com/nguymin4), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Surasak Chaisurin](https://github.com/Ryan-Willpower), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Jason Kwok](https://github.com/JasonHK), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), and [Linus Unnebäck](https://github.com/LinusU). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100755 index 0000000..2b75a03 --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,912 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/assert.js) + */ +declare module 'assert' { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * tracker.report(); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return of objects containing information about the wrapper functions returned by `calls`. + */ + report(): CallTrackerReportInformation[]; + /** + * Iterates through the list of functions passed to `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new () => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function + ): never; + /** + * Tests if `value` is truthy. It is equivalent to`assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is `undefined`, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison) ( `==` ). `NaN` is special handled + * and treated as being identical in case both sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default + * error message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [Abstract Equality Comparison](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison)(`!=` ). `NaN` is special handled and treated as + * being identical in case both + * sides are `NaN`. + * + * ```js + * import assert from 'assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message`property set equal to the value of the `message` parameter. If the `message`parameter is undefined, a default error + * message is assigned. If the `message`parameter is an instance of an `Error` then it will be thrown instead of the`AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(obj1); + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a default + * error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by the [SameValue Comparison](https://tc39.github.io/ecma262/#sec-samevalue). + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a`message` property set equal to the value of the `message` parameter. If the`message` parameter is undefined, a + * default error message is assigned. If the`message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the`AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text' + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text' + * } + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * } + * ); + * + * // Using regular expressions to validate error properties: + * throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text' + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i + * } + * ); + * + * // Fails due to the different `message` and `name` properties: + * throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/ + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error' + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn`function. + * + * If an error is thrown and it is the same type as that specified by the `error`parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message`parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops' + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for`ifError()` itself. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected`Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases the error + * handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and`name` properties. + * + * If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * } + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for`message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second + * argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously,`assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an `ERR_INVALID_RETURN_VALUE` error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than`string`, an `AssertionError` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: Omit & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module 'node:assert' { + import assert = require('assert'); + export = assert; +} diff --git a/node_modules/@types/node/assert/strict.d.ts b/node_modules/@types/node/assert/strict.d.ts new file mode 100755 index 0000000..b4319b9 --- /dev/null +++ b/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module 'assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} +declare module 'node:assert/strict' { + import { strict } from 'node:assert'; + export = strict; +} diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100755 index 0000000..9f9d22c --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,497 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/async_hooks.js) + */ +declare module 'async_hooks' { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on `promise execution tracking`. + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'fs'; + * import { executionAsyncId, executionAsyncResource } from 'async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * } + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on `promise execution tracking`. + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { } + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func + ): Func & { + asyncResource: AsyncResource; + }; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `async_hooks` module,`AsyncLocalStorage` should be preferred as it is a performant and memory safe + * implementation that involves significant optimizations that are non-obvious to + * implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'http'; + * import { AsyncLocalStorage } from 'async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function or + * the asynchronous operations created within the callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module 'node:async_hooks' { + export * from 'async_hooks'; +} diff --git a/node_modules/@types/node/base.d.ts b/node_modules/@types/node/base.d.ts new file mode 100755 index 0000000..7520541 --- /dev/null +++ b/node_modules/@types/node/base.d.ts @@ -0,0 +1,19 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.7. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.7/base.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// + +// TypeScript 3.7-specific augmentations: +/// diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100755 index 0000000..dd62133 --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,1923 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/buffer.js) + */ +declare module 'buffer' { + import { BinaryLike } from 'node:crypto'; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' | 'binary'; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new (size: number): Buffer; + prototype: Buffer; + }; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0 + * @experimental + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that resolves the contents of the `Blob` decoded as a UTF-8 + * string. + * @since v15.7.0 + */ + text(): Promise; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + global { + // Buffer class + type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new (str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new (arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new (array: ReadonlyArray): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new (buffer: Buffer): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: WithImplicitCoercion, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | ReadonlyArray): Buffer; + from(data: WithImplicitCoercion | string>): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: 'string'): string; + }, + encoding?: BufferEncoding + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: 'Buffer'; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare(target: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This is the same behavior as `buf.subarray()`. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * ``` + * @since v0.3.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in`encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.slice()`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0 + * @deprecated Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.** + * @since v15.13.0 + * @deprecated Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + } +} +declare module 'node:buffer' { + export * from 'buffer'; +} diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100755 index 0000000..cf31751 --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1355 @@ +/** + * The `child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if it is in the `options` object. Otherwise, `process.env.PATH` is + * used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as`PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `child_process` module provides a handful of synchronous + * and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/child_process.js) + */ +declare module 'child_process' { + import { ObjectEncodingOptions } from 'node:fs'; + import { EventEmitter, Abortable } from 'node:events'; + import * as net from 'node:net'; + import { Writable, Readable, Stream, Pipe } from 'node:stream'; + import { URL } from 'node:url'; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server; + interface ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` if the child process could + * not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel currently exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and`subprocess.stdio[2]` are also available as `subprocess.stdin`,`subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ] + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is`false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See[`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if[`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to`'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'] + * } + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the`'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for`'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received + * and buffered in the socket will not be sent to the child. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an`'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `net` module, `dgram`module servers use exactly the same workflow with the exceptions of listening on + * a `'message'` event instead of `'connection'` and using `server.bind()` instead + * of `server.listen()`. This is, however, currently only supported on Unix + * platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the`subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore' + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: 'spawn', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'exit', code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: 'message', message: Serializable, sendHandle: SendHandle): boolean; + emit(event: 'spawn', listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: 'spawn', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: 'spawn', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: 'spawn', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependOnceListener(event: 'message', listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: 'spawn', listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio extends ChildProcess { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = 'overlapped' | 'pipe' | 'ignore' | 'inherit'; + type StdioOptions = IOType | Array; + type SerializationType = 'json' | 'advanced'; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = 'inherit' | 'ignore' | Stream; + type StdioPipeNamed = 'pipe' | 'overlapped'; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given`command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so`process.argv[0]` in a Node.js child process will not match the `argv0`parameter passed to `spawn` from the parent, + * retrieve it with the`process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptionsWithStdioTuple): ChildProcessByStdio; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on[shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments`(error, stdout, stderr)`. On success, `error` will be `null`. On error,`error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0`indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const exec = util.promisify(require('child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: 'buffer' | null; + } & ExecOptions + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = ExecException & NodeJS.ErrnoException; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned`ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('util'); + * const execFile = util.promisify(require('child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile(file: string, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile(file: string, options: ExecFileOptionsWithOtherEncoding, callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptions + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the`options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by`child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: 'buffer' | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | 'buffer' | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: 'buffer' | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM`signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; +} +declare module 'node:child_process' { + export * from 'child_process'; +} diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100755 index 0000000..7e19747 --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,414 @@ +/** + * A single instance of Node.js runs in a single thread. To take advantage of + * multi-core systems, the user will sometimes want to launch a cluster of Node.js + * processes to handle the load. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/cluster.js) + */ +declare module 'cluster' { + import * as child from 'node:child_process'; + import EventEmitter = require('node:events'); + import * as net from 'node:net'; + export interface ClusterSettings { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | 'udp4' | 'udp6'; // 4, 6, -1, "udp4", "udp6" + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the`id`. + * + * While a worker is alive, this is the key that indexes it in`cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using `child_process.fork()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary this sends a message to a specific worker. It is identical to `ChildProcess.send()`. + * + * In a worker this sends a message to the primary. It is identical to`process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, callback?: (error: Error | null) => void): boolean; + send(message: child.Serializable, sendHandle: child.SendHandle, options?: child.MessageOptions, callback?: (error: Error | null) => void): boolean; + /** + * This function will kill the worker. In the primary, it does this + * by disconnecting the `worker.process`, and once disconnected, killing + * with `signal`. In the worker, it does it by disconnecting the channel, + * and then exiting with code `0`. + * + * Because `kill()` attempts to gracefully disconnect the worker process, it is + * susceptible to waiting indefinitely for the disconnect to complete. For example, + * if the worker enters an infinite loop, a graceful disconnect will never occur. + * If the graceful disconnect behavior is not needed, use `worker.process.kill()`. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * This method is aliased as `worker.destroy()` for backward compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is `kill()`. + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call`.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.kill()` or`.disconnect()`. If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'exit', listener: (code: number, signal: string) => void): this; + addListener(event: 'listening', listener: (address: Address) => void): this; + addListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'exit', code: number, signal: string): boolean; + emit(event: 'listening', address: Address): boolean; + emit(event: 'message', message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'exit', listener: (code: number, signal: string) => void): this; + on(event: 'listening', listener: (address: Address) => void): this; + on(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'exit', listener: (code: number, signal: string) => void): this; + once(event: 'listening', listener: (address: Address) => void): this; + once(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependListener(event: 'listening', listener: (address: Address) => void): this; + prependListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'online', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'exit', listener: (code: number, signal: string) => void): this; + prependOnceListener(event: 'listening', listener: (address: Address) => void): this; + prependOnceListener(event: 'message', listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'online', listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'disconnect', listener: (worker: Worker) => void): this; + addListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: 'fork', listener: (worker: Worker) => void): this; + addListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + addListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: 'online', listener: (worker: Worker) => void): this; + addListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'disconnect', worker: Worker): boolean; + emit(event: 'exit', worker: Worker, code: number, signal: string): boolean; + emit(event: 'fork', worker: Worker): boolean; + emit(event: 'listening', worker: Worker, address: Address): boolean; + emit(event: 'message', worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: 'online', worker: Worker): boolean; + emit(event: 'setup', settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'disconnect', listener: (worker: Worker) => void): this; + on(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: 'fork', listener: (worker: Worker) => void): this; + on(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + on(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: 'online', listener: (worker: Worker) => void): this; + on(event: 'setup', listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'disconnect', listener: (worker: Worker) => void): this; + once(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: 'fork', listener: (worker: Worker) => void): this; + once(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + once(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: 'online', listener: (worker: Worker) => void): this; + once(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: 'fork', listener: (worker: Worker) => void): this; + prependListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: 'message', listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void): this; + prependListener(event: 'online', listener: (worker: Worker) => void): this; + prependListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'disconnect', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'exit', listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: 'fork', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'listening', listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: 'message', listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: 'online', listener: (worker: Worker) => void): this; + prependOnceListener(event: 'setup', listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module 'node:cluster' { + export * from 'cluster'; + export { default as default } from 'cluster'; +} diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100755 index 0000000..b0896f6 --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,407 @@ +/** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/console.js) + */ +declare module 'console' { + import console = require('node:console'); + export = console; +} +declare module 'node:console' { + import { InspectOptions } from 'node:util'; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param label The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation`length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See `util.format()` for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can’t be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: ReadonlyArray): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the `note on process I/O` for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | 'auto' | undefined; + inspectOptions?: InspectOptions | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new (stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new (options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100755 index 0000000..208020d --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,18 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module 'constants' { + import { constants as osConstants, SignalConstants } from 'node:os'; + import { constants as cryptoConstants } from 'node:crypto'; + import { constants as fsConstants } from 'node:fs'; + + const exp: typeof osConstants.errno & + typeof osConstants.priority & + SignalConstants & + typeof cryptoConstants & + typeof fsConstants; + export = exp; +} + +declare module 'node:constants' { + import constants = require('constants'); + export = constants; +} diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100755 index 0000000..d5f5d8f --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,3158 @@ +/** + * The `crypto` module provides cryptographic functionality that includes a set of + * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. + * + * ```js + * const { createHmac } = await import('crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/crypto.js) + */ +declare module 'crypto' { + import * as stream from 'node:stream'; + import { PeerCertificate } from 'node:tls'; + interface Certificate { + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + const Certificate: Certificate & { + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + new (): Certificate; + /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */ + (): Certificate; + /** + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + }; + namespace constants { + // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const ALPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms`(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = 'base64' | 'hex'; + type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1'; + type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2'; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid'; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash + * } = await import('crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: stream.TransformOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac + * } = await import('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = 'secret' | 'public' | 'private'; + interface KeyExportOptions { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + interface JwkKeyExportOptions { + format: 'jwk'; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * RSA-PSS parameters, DH, or any future key type details might be exposed via this + * API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<'pem'>): string | Buffer; + export(options?: KeyExportOptions<'der'>): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of[`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an[initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then`inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of[`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms`(`openssl list-cipher-algorithms` for older versions of OpenSSL) will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an[initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike | null, options: CipherCCMOptions): DecipherCCM; + function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike | null, options?: CipherGCMOptions): DecipherGCM; + function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + } + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + } + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined; + passphrase?: string | Buffer | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: 'pkcs1' | 'spki' | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey + * } = await import('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: 'hmac' | 'aes', + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void + ): void; + interface JsonWebKeyInput { + key: JsonWebKey; + format: 'jwk'; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = 'der' | 'ieee-p1363'; + interface SigningOptions { + /** + * @See crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1' + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify + * } = await import('crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, outputFormat: BinaryToTextEncoding): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createDiffieHellman + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `constants`module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in[RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The + * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman + * } = await import('crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellman; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2 + * } = await import('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync + * } = await import('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes + * } = await import('crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 248. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt + * } = await import('crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFillSync } = await import('crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'buffer'; + * const { randomFill } = await import('crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt + * } = await import('crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void; + function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync + * } = await import('crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves + * } = await import('crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * ```js + * const { + * getHashes + * } = await import('crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'assert'; + * + * const { + * createECDH + * } = await import('crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'`format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH + * } = await import('crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: 'latin1' | 'hex' | 'base64', + format?: 'uncompressed' | 'compressed' | 'hybrid' + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or[capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + type KeyType = 'rsa' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; + type KeyFormat = 'pem' | 'der'; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, + * Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync + * } = await import('crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519, + * Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair + * } = await import('crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem' + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret' + * } + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + namespace generateKeyPair { + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'rsa', + options: RSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'dsa', + options: DSAKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ec', + options: ECKeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed25519', + options: ED25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'ed448', + options: ED448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x25519', + options: X25519KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'pem'> + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'pem', 'der'> + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'pem'> + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: 'x448', + options: X448KeyPairOptions<'der', 'der'> + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts'; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `key`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdf + * } = await import('crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param key The secret key. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf(digest: string, key: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `key`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * hkdfSync + * } = await import('crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param key The secret key. It must be at least one byte in length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync(digest: string, key: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) Version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0 + */ + function randomUUID(options?: RandomUUIDOptions): string; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject: 'always' | 'never'; + /** + * @default true + */ + wildcards: boolean; + /** + * @default true + */ + partialWildcards: boolean; + /** + * @default false + */ + multiLabelWildcards: boolean; + /** + * @default false + */ + singleLabelSubdomains: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (ca) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * @since v15.6.0 + */ + readonly subjectAltName: string; + /** + * The information access content of this certificate. + * @since v15.6.0 + */ + readonly infoAccess: string; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * @since v15.6.0 + * @return Returns `name` if the certificate matches, `undefined` if it does not. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [<bigint>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [<ArrayBuffer>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [<bigint>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + namespace webcrypto { + class CryptoKey {} // placeholder + } +} +declare module 'node:crypto' { + export * from 'crypto'; +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100755 index 0000000..60de78c --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,545 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/dgram.js) + */ +declare module 'dgram' { + import { AddressInfo } from 'node:net'; + import * as dns from 'node:dns'; + import { EventEmitter, Abortable } from 'node:events'; + interface RemoteInfo { + address: string; + family: 'IPv4' | 'IPv6'; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = 'udp4' | 'udp6'; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: ((hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void) | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding`AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and`multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the`multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'cluster'; + * import dgram from 'dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family` and `port`properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a`'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a`callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: () => void): void; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): void; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the`IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer`with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise falsy, `'127.0.0.1'` (for `udp4` sockets) or `'::1'`(for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a`callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on`localhost`: + * + * ```js + * import dgram from 'dgram'; + * import { Buffer } from 'buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send(msg: string | Uint8Array | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array | ReadonlyArray, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to[IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): void; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): void; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): void; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no addition effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given`sourceAddress` and `groupAddress`, using the `multicastInterface` with the`IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call`socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given`sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP`socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connect'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'message', msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'message', listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + } +} +declare module 'node:dgram' { + export * from 'dgram'; +} diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100755 index 0000000..5a2a96e --- /dev/null +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,128 @@ +/** + * The `diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/diagnostics_channel.js) + */ +declare module 'diagnostics_channel' { + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string): boolean; + /** + * This is the primary entry-point for anyone wanting to interact with a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @param name The channel name + * @return The named channel object + */ + function channel(name: string): Channel; + type ChannelListener = (name: string, message: unknown) => void; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is use to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + */ + class Channel { + readonly name: string; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + */ + readonly hasSubscribers: boolean; + private constructor(name: string); + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @param onMessage The previous subscribed handler to remove + */ + unsubscribe(onMessage: ChannelListener): void; + } +} +declare module 'node:diagnostics_channel' { + export * from 'diagnostics_channel'; +} diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100755 index 0000000..7375484 --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,639 @@ +/** + * The `dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the `Implementation considerations section` for more information. + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/dns.js) + */ +declare module 'dns' { + import * as dnsPromises from 'node:dns/promises'; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses, and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the `Implementation considerations section` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties. + * @since v0.1.90 + */ + export function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; + export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; + export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On an error, `err` is an `Error` object, where `err.code` is the error code. + * + * ```js + * const dns = require('dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: 'A'; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: 'AAAA'; + } + export interface CaaRecord { + critial: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: 'MX'; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: 'NAPTR'; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: 'SOA'; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: 'SRV'; + } + export interface AnyTxtRecord { + type: 'TXT'; + entries: string[]; + } + export interface AnyNsRecord { + type: 'NS'; + value: string; + } + export interface AnyPtrRecord { + type: 'PTR'; + value: string; + } + export interface AnyCnameRecord { + type: 'CNAME'; + value: string; + } + export type AnyRecord = AnyARecord | AnyAaaaRecord | AnyCnameRecord | AnyMxRecord | AnyNaptrRecord | AnyNsRecord | AnyPtrRecord | AnySoaRecord | AnySrvRecord | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'A', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'AAAA', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'ANY', callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'CNAME', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'MX', callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NAPTR', callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'NS', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'PTR', callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve(hostname: string, rrtype: 'SOA', callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; + export function resolve(hostname: string, rrtype: 'SRV', callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export function resolve(hostname: string, rrtype: 'TXT', callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: 'A' | 'AAAA' | 'CNAME' | 'NS' | 'PTR'): Promise; + function __promisify__(hostname: string, rrtype: 'ANY'): Promise; + function __promisify__(hostname: string, rrtype: 'MX'): Promise; + function __promisify__(hostname: string, rrtype: 'NAPTR'): Promise; + function __promisify__(hostname: string, rrtype: 'SOA'): Promise; + function __promisify__(hostname: string, rrtype: 'SRV'): Promise; + function __promisify__(hostname: string, rrtype: 'TXT'): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0 + */ + export function resolveCaa(hostname: string, callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC + * 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an `Error` object, where `err.code` is + * one of the `DNS error codes`. + * @since v0.1.16 + */ + export function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like[resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of `RFC 5952` formatted addresses + */ + export function setServers(servers: ReadonlyArray): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using `resolver.setServers()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default, and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module 'node:dns' { + export * from 'dns'; +} diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts new file mode 100755 index 0000000..9ce3fd2 --- /dev/null +++ b/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,357 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('dns').promises` or `require('dns/promises')`. + * @since v10.6.0 + */ +declare module 'dns/promises' { + import { + LookupAddress, + LookupOneOptions, + LookupAllOptions, + LookupOptions, + AnyRecord, + CaaRecord, + MxRecord, + NaptrRecord, + SoaRecord, + SrvRecord, + ResolveWithTtlOptions, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + } from 'node:dns'; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses`being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dnsPromises.lookup()` does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses, and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the `Implementation considerations section` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: 'A'): Promise; + function resolve(hostname: string, rrtype: 'AAAA'): Promise; + function resolve(hostname: string, rrtype: 'ANY'): Promise; + function resolve(hostname: string, rrtype: 'CAA'): Promise; + function resolve(hostname: string, rrtype: 'CNAME'): Promise; + function resolve(hostname: string, rrtype: 'MX'): Promise; + function resolve(hostname: string, rrtype: 'NAPTR'): Promise; + function resolve(hostname: string, rrtype: 'NS'): Promise; + function resolve(hostname: string, rrtype: 'PTR'): Promise; + function resolve(hostname: string, rrtype: 'SOA'): Promise; + function resolve(hostname: string, rrtype: 'SRV'): Promise; + function resolve(hostname: string, rrtype: 'TXT'): Promise; + function resolve(hostname: string, rrtype: string): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname`(e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression based records (`NAPTR`records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the`hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an `Error` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like[resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: ReadonlyArray): void; + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module 'node:dns/promises' { + export * from 'dns/promises'; +} diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100755 index 0000000..bbeeb9f --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,169 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should**not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/domain.js) + */ +declare module 'domain' { + import EventEmitter = require('node:events'); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and lowlevel requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('domain'); + * const fs = require('fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module 'node:domain' { + export * from 'domain'; +} diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100755 index 0000000..4fc36f4 --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,444 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * const EventEmitter = require('events'); + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/events.js) + */ +declare module 'events' { + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + interface DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + } + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('events'); + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter { + constructor(options?: EventEmitterOptions); + static once(emitter: NodeEventTarget, eventName: string | symbol, options?: StaticEventEmitterOptions): Promise; + static once(emitter: DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + static on(emitter: NodeJS.EventEmitter, eventName: string, options?: StaticEventEmitterOptions): AsyncIterableIterator; + /** @deprecated since v4.0.0 */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a list listener for a specific emitter event name. + */ + static getEventListener(emitter: DOMEventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` + * events. Listeners installed using this symbol are called before the regular + * `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an + * `'error'` event is emitted, therefore the process will still crash if no + * regular `'error'` listener is installed. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + static defaultMaxListeners: number; + } + import internal = require('node:events'); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + } + global { + namespace NodeJS { + interface EventEmitter { + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds the `listener` function to the end of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The`emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes the specified `listener` from the listener array for the event named`eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any`removeListener()` or `removeAllListeners()` calls _after_ emitting and_before_ the last listener finishes execution will + * not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')`listener is removed: + * + * ```js + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(event?: string | symbol): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to`Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: string | symbol): Function[]; + /** + * Synchronously calls each of the listeners registered for the event named`eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * const EventEmitter = require('events'); + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to the event named `eventName`. + * @since v3.2.0 + * @param eventName The name of the event being listened for + */ + listenerCount(eventName: string | symbol): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName`and `listener` will result in the `listener` being added, and called, multiple + * times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the_beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * const EventEmitter = require('events'); + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array; + } + } + } + export = EventEmitter; +} +declare module 'node:events' { + import events = require('events'); + export = events; +} diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100755 index 0000000..556d745 --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,3653 @@ +/** + * The `fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/fs.js) + */ +declare module 'fs' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import { URL } from 'node:url'; + import * as promises from 'node:fs/promises'; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | 'buffer' + | { + encoding: 'buffer'; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat} and {@link fstat} and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an ``. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `` objects, rather than strings or `` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or {@link romises.opendir}. + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or {@link romises.opendir}. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an ``. + * + * A promise is returned that will be resolved with an ``, or `null`if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an ``. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given ``. Once stopped, the `` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'close', listener: () => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'close', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'close', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + } + /** + * Instances of `` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a ``, then`readStream.path` will be a + * ``. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `` + * + * Instances of `` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a ``, then`writeStream.path` will be a + * ``. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'open', listener: (fd: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'open', listener: (fd: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'open', listener: (fd: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'open', listener: (fd: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'open', listener: (fd: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function stat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: TDescriptor, options?: undefined): Stats; + ( + path: TDescriptor, + options?: StatOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + } + ): Stats | undefined; + ( + path: TDescriptor, + options: StatOptions & { + bigint: true; + throwIfNoEntry: false; + } + ): BigIntStats | undefined; + ( + path: TDescriptor, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Stats; + ( + path: TDescriptor, + options: StatOptions & { + bigint: true; + } + ): BigIntStats; + ( + path: TDescriptor, + options: StatOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + } + ): Stats | BigIntStats; + (path: TDescriptor, options?: StatOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function fstat(fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export const fstatSync: StatSyncFn; + /** + * Retrieves the `` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void + ): void; + export function lstat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + } + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX[`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than a + * possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX[`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If + * the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from 'fs'; + * + * symlink('./mew', './example/mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` in the `example` which points + * to `mew` in the same directory: + * + * ```bash + * $ tree example/ + * example/ + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + */ + export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = 'dir' | 'file' | 'junction'; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `` object. + * @since v0.1.31 + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..` and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode soperations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err, [path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. + * mkdir('/tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs'; + * + * mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from 'fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | 'buffer' + | { + encoding: 'buffer'; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer', + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | 'buffer' + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + } + | BufferEncoding + | null + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by[this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. If `buffer` is a normal object, it + * must have an own `toString` function property. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @return The number of bytes written. + */ + export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; + export type ReadPosition = number | bigint; + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param [buffer=Buffer.alloc(16384)] The buffer that the data will be written to. + * @param [offset=0] The position in `buffer` to write the data to. + * @param [length=buffer.byteLength] The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + } + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null + ): string | Buffer; + export type WriteFileOptions = + | (ObjectEncodingOptions & + Abortable & { + mode?: Mode | undefined; + flag?: string | undefined; + }) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs'; + * import { Buffer } from 'buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; + } + /** + * Returns `undefined`. + * + * If `data` is a plain object, it must have an own (not inherited) `toString`function property. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a ``. + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile(path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a ``. + * + * ```js + * import { appendFileSync } from 'fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync(path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtime` and `prev.mtime`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | { + persistent?: boolean | undefined; + interval?: number | undefined; + } + | undefined, + listener: (curr: Stats, prev: Stats) => void + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | 'buffer' | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = 'rename' | 'change'; + export type WatchListener = (event: WatchEventType, filename: T) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by ``, but it is not the same thing as the `'change'` value of`eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned ``. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer', + listener?: WatchListener + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options?: WatchOptions | BufferEncoding | null, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: WatchOptions | string, listener?: WatchListener): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won’t be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file exists in the current directory, and if it is writable. + * access(file, constants.F_OK | constants.W_OK, (err) => { + * if (err) { + * console.error( + * `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`); + * } else { + * console.log(`${file} exists, and it is writable`); + * } + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. Check `File access constants` for + * possible values of `mode`. It is possible to create a mask consisting of + * the bitwise OR of two or more values + * (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + /** + * @default false + */ + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + } + interface ReadStreamOptions extends StreamOptions { + end?: number | undefined; + } + /** + * Unlike the 16 kb default `highWaterMark` for a readable stream, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by ``. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to ``. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed, like most `Readable` streams. Set the `emitClose` option to`false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option, + * overrides for `open`, `read`, and `close` are required. + * + * ```js + * import { createReadStream } from 'fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + * @return See `Readable Stream`. + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than replacing + * it may require the `flags` option to be set to `r+` rather than the default `w`. + * The `encoding` can be any one of those accepted by ``. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed, like most `Writable` streams. Set the `emitClose` option to`false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for `open`,`close`, and at least one of `write` and `writev` are required. + * + * Like ``, if `fd` is specified, `` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to ``. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + * @return See `Writable Stream`. + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | StreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX[`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX[`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + */ + export function writev(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function writev( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + */ + export function readv(fd: number, buffers: ReadonlyArray, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void; + export function readv( + fd: number, + buffers: ReadonlyArray, + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; + export interface OpenDirOptions { + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an ``, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: string, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an ``, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export namespace opendir { + function __promisify__(path: string, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + throwIfNoEntry?: boolean | undefined; + } +} +declare module 'node:fs' { + export * from 'fs'; +} diff --git a/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts new file mode 100755 index 0000000..a83aa85 --- /dev/null +++ b/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,983 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module 'fs/promises' { + import { Abortable } from 'node:events'; + import { Stream } from 'node:stream'; + import { + Stats, + BigIntStats, + StatOptions, + WriteVResult, + ReadVResult, + PathLike, + RmDirOptions, + RmOptions, + MakeDirectoryOptions, + Dirent, + OpenDirOptions, + Dir, + ObjectEncodingOptions, + BufferEncodingOption, + OpenMode, + Mode, + WatchOptions, + WatchEventType, + } from 'node:fs'; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX[`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fufills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param [offset=0] The location in the buffer at which to start filling. + * @param [length=buffer.byteLength] The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read(buffer: T, offset?: number | null, length?: number | null, position?: number | null): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a`filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + } + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `` then resolves the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a buffer, or an object with an own `toString` function + * property. The promise is resolved with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile(data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode & Abortable) | BufferEncoding | null): Promise; + /** + * Write `buffer` to the file. + * + * If `buffer` is a plain object, it must have an own (not inherited) `toString`function property. + * + * The promise is resolved with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be resolved (or rejected). For this + * scenario, use `fs.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param [offset=0] The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength] The number of bytes from `buffer` to write. + * @param position The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. + * See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [<ArrayBufferView>](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView)s to the file. + * + * The promise is resolved with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be resolved (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param position The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: ReadonlyArray, position?: number): Promise; + /** + * Read from a file and write to an array of [<ArrayBufferView>](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView)s + * @since v13.13.0, v12.17.0 + * @param position The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: ReadonlyArray, position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. Check `File access constants` for possible values + * of `mode`. It is possible to create a mask consisting of the bitwise OR of + * two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`). + * + * If the accessibility check is successful, the promise is resolved with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [<Error>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access } from 'fs/promises'; + * import { constants } from 'fs'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a ``. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by[this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len`bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR`error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + } + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `` objects. + * + * If `options.withFileTypes` is set to `true`, the resolved array will contain `` objects. + * + * ```js + * import { readdir } from 'fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: 'buffer'; + withFileTypes?: false | undefined; + } + | 'buffer' + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + } + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX[`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * resolved with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`,`'file'`, or `'junction'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + } + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + } + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX[`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html)documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + /** + * Determines the actual location of `path` using the same semantics as the`fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory`/tmp`, if the intention is to create a temporary directory _within_`/tmp`, the`prefix` must end with a trailing + * platform-specific path separator + * (`require('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists.`data` can be a string, a ``, or, an object with an own (not inherited)`toString` function property. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * Any specified `` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()`. + * + * It is possible to use an `` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'fs/promises'; + * import { Buffer } from 'buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: string | NodeJS.ArrayBufferView | Iterable | AsyncIterable | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a ``. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `path` may be specified as a `` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: (ObjectEncodingOptions & FlagAndOpenMode) | BufferEncoding | null): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * It is possible to abort an ongoing `readFile` using an ``. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | (ObjectEncodingOptions & + Abortable & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX[`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an ``, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: string, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: 'buffer'; + }) + | 'buffer' + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: WatchOptions | string): AsyncIterable> | AsyncIterable>; +} +declare module 'node:fs/promises' { + export * from 'fs/promises'; +} diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100755 index 0000000..5e359db --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,285 @@ +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + +// For backwards compability +interface NodeRequire extends NodeJS.Require { } +interface RequireResolve extends NodeJS.RequireResolve { } +interface NodeModule extends NodeJS.Module { } + +declare var process: NodeJS.Process; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare var require: NodeRequire; +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +/** + * Only available if `--expose-gc` is passed to the process. + */ +declare var gc: undefined | (() => void); + +//#region borrowed +// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib +/** A controller object that allows you to abort one or more DOM requests as and when desired. */ +interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(): void; +} + +/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ +interface AbortSignal { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +declare var AbortSignal: { + prototype: AbortSignal; + new(): AbortSignal; + // TODO: Add abort() static +}; +//#endregion borrowed + +//#region ArrayLike.at() +interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; +} +interface String extends RelativeIndexable {} +interface Array extends RelativeIndexable {} +interface Int8Array extends RelativeIndexable {} +interface Uint8Array extends RelativeIndexable {} +interface Uint8ClampedArray extends RelativeIndexable {} +interface Int16Array extends RelativeIndexable {} +interface Uint16Array extends RelativeIndexable {} +interface Int32Array extends RelativeIndexable {} +interface Uint32Array extends RelativeIndexable {} +interface Float32Array extends RelativeIndexable {} +interface Float64Array extends RelativeIndexable {} +interface BigInt64Array extends RelativeIndexable {} +interface BigUint64Array extends RelativeIndexable {} +//#endregion ArrayLike.at() end + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + stack?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): void; + end(data: string | Uint8Array, cb?: () => void): void; + end(str: string, encoding?: BufferEncoding, cb?: () => void): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined; }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + '.js': (m: Module, filename: string) => any; + '.json': (m: Module, filename: string) => any; + '.node': (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } +} diff --git a/node_modules/@types/node/globals.global.d.ts b/node_modules/@types/node/globals.global.d.ts new file mode 100755 index 0000000..ef1198c --- /dev/null +++ b/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100755 index 0000000..5cab0d6 --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,1358 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```js + * { 'content-length': '123', + * 'content-type': 'text/plain', + * 'connection': 'keep-alive', + * 'host': 'mysite.com', + * 'accept': '*' } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders`list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'mysite.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/http.js) + */ +declare module 'http' { + import * as stream from 'node:stream'; + import { URL } from 'node:url'; + import { Socket, Server as NetServer } from 'node:net'; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + 'accept-language'?: string | undefined; + 'accept-patch'?: string | undefined; + 'accept-ranges'?: string | undefined; + 'access-control-allow-credentials'?: string | undefined; + 'access-control-allow-headers'?: string | undefined; + 'access-control-allow-methods'?: string | undefined; + 'access-control-allow-origin'?: string | undefined; + 'access-control-expose-headers'?: string | undefined; + 'access-control-max-age'?: string | undefined; + 'access-control-request-headers'?: string | undefined; + 'access-control-request-method'?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + 'alt-svc'?: string | undefined; + authorization?: string | undefined; + 'cache-control'?: string | undefined; + connection?: string | undefined; + 'content-disposition'?: string | undefined; + 'content-encoding'?: string | undefined; + 'content-language'?: string | undefined; + 'content-length'?: string | undefined; + 'content-location'?: string | undefined; + 'content-range'?: string | undefined; + 'content-type'?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + 'if-match'?: string | undefined; + 'if-modified-since'?: string | undefined; + 'if-none-match'?: string | undefined; + 'if-unmodified-since'?: string | undefined; + 'last-modified'?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + 'proxy-authenticate'?: string | undefined; + 'proxy-authorization'?: string | undefined; + 'public-key-pins'?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + 'retry-after'?: string | undefined; + 'sec-websocket-accept'?: string | undefined; + 'sec-websocket-extensions'?: string | undefined; + 'sec-websocket-key'?: string | undefined; + 'sec-websocket-protocol'?: string | undefined; + 'sec-websocket-version'?: string | undefined; + 'set-cookie'?: string[] | undefined; + 'strict-transport-security'?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + 'transfer-encoding'?: string | undefined; + upgrade?: string | undefined; + 'user-agent'?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + 'www-authenticate'?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict {} + interface ClientRequestArgs { + abort?: AbortSignal | undefined; + protocol?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + family?: number | undefined; + port?: number | string | null | undefined; + defaultPort?: number | string | undefined; + localAddress?: string | undefined; + socketPath?: string | undefined; + /** + * @default 8192 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + headers?: OutgoingHttpHeaders | undefined; + auth?: string | null | undefined; + agent?: Agent | boolean | undefined; + _defaultAgent?: Agent | undefined; + timeout?: number | undefined; + setHost?: boolean | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined; + } + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage | undefined; + ServerResponse?: typeof ServerResponse | undefined; + /** + * Optionally overrides the value of + * `--max-http-header-size` for requests received by this server, i.e. + * the maximum length of request headers in bytes. + * @default 8192 + */ + maxHeaderSize?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when true. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + } + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + /** + * @since v0.1.17 + */ + class Server extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * In case of inactivity, the rules defined in `server.timeout` apply. However, + * that inactivity based timeout would still allow the connection to be kept open + * if the headers are being sent very slowly (by default, up to a byte per 2 + * minutes). In order to prevent this, whenever header data arrives an additional + * check is made that more than `server.headersTimeout` milliseconds has not + * passed since the connection was established. If the check fails, a `'timeout'`event is emitted on the server object, and (by default) the socket is destroyed. + * See `server.timeout` for more information on how timeout behavior can be + * customized. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: RequestListener): this; + addListener(event: 'checkExpectation', listener: RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + addListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: RequestListener): this; + addListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'checkExpectation', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; + emit(event: 'connect', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + emit(event: 'request', req: IncomingMessage, res: ServerResponse): boolean; + emit(event: 'upgrade', req: IncomingMessage, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: RequestListener): this; + on(event: 'checkExpectation', listener: RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: RequestListener): this; + once(event: 'checkExpectation', listener: RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + once(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + once(event: 'request', listener: RequestListener): this; + once(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: RequestListener): this; + prependListener(event: 'checkExpectation', listener: RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: IncomingMessage, socket: stream.Duplex, head: Buffer) => void): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract of outgoing message from + * the perspective of the participants of HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: IncomingMessage; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Aliases of `outgoingMessage.socket` + * @since v0.3.0 + * @deprecated Since v15.12.0 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * occurs, Same as binding to the `timeout` event. + * + * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value for the header object. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | ReadonlyArray): this; + /** + * Gets the value of HTTP header with the given name. If such a name doesn't + * exist in message, it will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript Object. This means that + * typical Object methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.0.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array of names of headers of the outgoing outgoingMessage. All + * names are lowercase. + * @since v8.0.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v8.0.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Compulsorily flushes the message headers + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the request. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + constructor(req: IncomingMessage); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends a HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on`Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain' + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0 + */ + getRawHeaderNames(): string[]; + addListener(event: 'abort', listener: () => void): this; + addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'continue', listener: () => void): this; + addListener(event: 'information', listener: (info: InformationEvent) => void): this; + addListener(event: 'response', listener: (response: IncomingMessage) => void): this; + addListener(event: 'socket', listener: (socket: Socket) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: 'abort', listener: () => void): this; + on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'continue', listener: () => void): this; + on(event: 'information', listener: (info: InformationEvent) => void): this; + on(event: 'response', listener: (response: IncomingMessage) => void): this; + on(event: 'socket', listener: (socket: Socket) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'abort', listener: () => void): this; + once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'continue', listener: () => void): this; + once(event: 'information', listener: (info: InformationEvent) => void): this; + once(event: 'response', listener: (response: IncomingMessage) => void): this; + once(event: 'socket', listener: (socket: Socket) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'abort', listener: () => void): this; + prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'continue', listener: () => void): this; + prependListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependListener(event: 'socket', listener: (socket: Socket) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'abort', listener: () => void): this; + prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'continue', listener: () => void): this; + prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; + prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers and data. + * + * Different from its `socket` value which is a subclass of ``, the`IncomingMessage` itself extends `` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST' + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `` class, + * a subclass of ``, unless the user specified a socket + * type other than ``. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with '; '. + * * For all other headers, the values are joined together with ', '. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(request.url, `http://${request.headers.host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.headers.host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.headers.host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): void; + } + interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: 'fifo' | 'lifo' | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * @since v0.3.4 + */ + class Agent { + /** + * By default set to 256\. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * @since v0.1.13 + */ + function createServer(requestListener?: RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const http = require('http'); + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!' + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData) + * } + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the + * request itself. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET and calls `req.end()`automatically. The callback must take care to consume the + * response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!' + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module 'node:http' { + export * from 'http'; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100755 index 0000000..ac304e3 --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2100 @@ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/http2.js) + */ +declare module 'http2' { + import EventEmitter = require('node:events'); + import * as fs from 'node:fs'; + import * as net from 'node:net'; + import * as stream from 'node:stream'; + import * as tls from 'node:tls'; + import * as url from 'node:url'; + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http'; + export { OutgoingHttpHeaders } from 'node:http'; + export interface IncomingHttpStatusHeader { + ':status'?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ':path'?: string | undefined; + ':method'?: string | undefined; + ':authority'?: string | undefined; + ':scheme'?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set the `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session; + /** + * Provides miscellaneous information about the current state of the`Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: 'aborted', listener: () => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'streamClosed', listener: (code: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'wantTrailers', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted'): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'frameError', frameType: number, errorCode: number): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: 'streamClosed', code: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'trailers', trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'wantTrailers'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: () => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: 'streamClosed', listener: (code: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'wantTrailers', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: () => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: 'streamClosed', listener: (code: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'wantTrailers', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: () => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'streamClosed', listener: (code: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'wantTrailers', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: () => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'streamClosed', listener: (code: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'trailers', listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'wantTrailers', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: 'continue', listener: () => {}): this; + addListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'continue'): boolean; + emit(event: 'headers', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: 'push', headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'response', headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'continue', listener: () => {}): this; + on(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'continue', listener: () => {}): this; + once(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'continue', listener: () => {}): this; + prependListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'continue', listener: () => {}): this; + prependOnceListener(event: 'headers', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: 'push', listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'response', listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8' + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.log(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate`304` response: + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: NodeJS.ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + /** + * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings(settings: Settings): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: 'localSettings', listener: (settings: Settings) => void): this; + addListener(event: 'ping', listener: () => void): this; + addListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'frameError', frameType: number, errorCode: number, streamID: number): boolean; + emit(event: 'goaway', errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: 'localSettings', settings: Settings): boolean; + emit(event: 'ping'): boolean; + emit(event: 'remoteSettings', settings: Settings): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: 'localSettings', listener: (settings: Settings) => void): this; + on(event: 'ping', listener: () => void): this; + on(event: 'remoteSettings', listener: (settings: Settings) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: 'localSettings', listener: (settings: Settings) => void): this; + once(event: 'ping', listener: () => void): this; + once(event: 'remoteSettings', listener: (settings: Settings) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'ping', listener: () => void): this; + prependListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'frameError', listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: 'goaway', listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: 'localSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'ping', listener: () => void): this; + prependOnceListener(event: 'remoteSettings', listener: (settings: Settings) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: 'origin', listener: (origins: string[]) => void): this; + addListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'altsvc', alt: string, origin: string, stream: number): boolean; + emit(event: 'origin', origins: ReadonlyArray): boolean; + emit(event: 'connect', session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + on(event: 'origin', listener: (origins: string[]) => void): this; + on(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + once(event: 'origin', listener: (origins: string[]) => void): this; + once(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: 'origin', listener: (origins: string[]) => void): this; + prependListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'altsvc', listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: 'origin', listener: (origins: string[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'connect', session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'connect', listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: 'http:' | 'https:' | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + addListener(event: 'sessionError', listener: (err: Error) => void): this; + addListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: 'timeout', listener: () => void): this; + addListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'checkContinue', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'request', request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: 'session', session: ServerHttp2Session): boolean; + emit(event: 'sessionError', err: Error): boolean; + emit(event: 'stream', stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: 'timeout'): boolean; + emit(event: 'unknownProtocol', socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: 'session', listener: (session: ServerHttp2Session) => void): this; + on(event: 'sessionError', listener: (err: Error) => void): this; + on(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: 'timeout', listener: () => void): this; + on(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: 'session', listener: (session: ServerHttp2Session) => void): this; + once(event: 'sessionError', listener: (err: Error) => void): this; + once(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: 'timeout', listener: () => void): this; + once(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependListener(event: 'sessionError', listener: (err: Error) => void): this; + prependListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'checkContinue', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'request', listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: 'session', listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: 'sessionError', listener: (err: Error) => void): this; + prependOnceListener(event: 'stream', listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: 'unknownProtocol', listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns`'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + readonly url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'aborted', hadError: boolean, code: number): boolean; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: Buffer | string): boolean; + emit(event: 'end'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: Buffer | string) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: Buffer | string) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'aborted', listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 request object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ''; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): void; + end(data: string | Uint8Array, callback?: () => void): void; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): void; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | ReadonlyArray): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses_must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call {@link tream.pushStream} with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (error: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', error: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: stream.Readable): boolean; + emit(event: 'unpipe', src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (error: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: stream.Readable) => void): this; + on(event: 'unpipe', listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (error: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: stream.Readable) => void): this; + once(event: 'unpipe', listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (error: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (error: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session`instances. + * + * Since there are no browsers known that support[unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem') + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200 + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect(authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void + ): ClientHttp2Session; +} +declare module 'node:http2' { + export * from 'http2'; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100755 index 0000000..9e6707d --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,391 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/https.js) + */ +declare module 'https' { + import { Duplex } from 'node:stream'; + import * as tls from 'node:tls'; + import * as http from 'node:http'; + import { URL } from 'node:url'; + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = http.RequestOptions & + tls.SecureContextOptions & { + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor(options: ServerOptions, requestListener?: http.RequestListener); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Duplex) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + addListener(event: 'checkContinue', listener: http.RequestListener): this; + addListener(event: 'checkExpectation', listener: http.RequestListener): this; + addListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + addListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + emit(event: string, ...args: any[]): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: tls.TLSSocket): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Duplex): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + emit(event: 'checkContinue', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'checkExpectation', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'clientError', err: Error, socket: Duplex): boolean; + emit(event: 'connect', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + emit(event: 'request', req: http.IncomingMessage, res: http.ServerResponse): boolean; + emit(event: 'upgrade', req: http.IncomingMessage, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Duplex) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + on(event: 'checkContinue', listener: http.RequestListener): this; + on(event: 'checkExpectation', listener: http.RequestListener): this; + on(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + on(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Duplex) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + once(event: 'checkContinue', listener: http.RequestListener): this; + once(event: 'checkExpectation', listener: http.RequestListener): this; + once(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + once(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependListener(event: 'checkContinue', listener: http.RequestListener): this; + prependListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Duplex) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: 'checkContinue', listener: http.RequestListener): this; + prependOnceListener(event: 'checkExpectation', listener: http.RequestListener): this; + prependOnceListener(event: 'clientError', listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener(event: 'connect', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener(event: 'upgrade', listener: (req: http.IncomingMessage, socket: Duplex, head: Buffer) => void): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('https'); + * const fs = require('fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample' + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer(requestListener?: http.RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted:`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`,`honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`,`secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`,`highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET' + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('tls'); + * const https = require('https'); + * const crypto = require('crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha25 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} +declare module 'node:https' { + export * from 'https'; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100755 index 0000000..a9ab91e --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for non-npm package Node.js 16.6 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Minh Son Nguyen +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Surasak Chaisurin +// Piotr Błażejewicz +// Anna Henningsen +// Jason Kwok +// Victor Perin +// Yongsheng Zhang +// NodeJS Contributors +// Linus Unnebäck +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * 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. + */ + +// NOTE: These definitions support NodeJS and TypeScript 3.7. +// Typically type modifications should be made in base.d.ts instead of here + +/// + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.6/index.d.ts - Definitions specific to TypeScript 3.6 + +// NOTE: Augmentations for TypeScript 3.6 and later should use individual files for overrides +// within the respective ~/ts3.6 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.6, so the older definitions will be found here. diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100755 index 0000000..734e156 --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2738 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +// tslint:disable:max-line-length + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the[Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help see https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help see https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent`Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +declare module 'node:inspector' { + import EventEmitter = require('inspector'); + export = EventEmitter; +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100755 index 0000000..d83aec9 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,114 @@ +/** + * @since v0.3.7 + */ +declare module 'module' { + import { URL } from 'node:url'; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line number and column number in the generated source file, returns + * an object representing the position in the original file. The object returned + * consists of the following keys: + */ + findEntry(line: number, column: number): SourceMapping; + } + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static Module: typeof Module; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + export = Module; +} +declare module 'node:module' { + import module = require('module'); + export = module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100755 index 0000000..a456a0d --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,783 @@ +/** + * > Stability: 2 - Stable + * + * The `net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/net.js) + */ +declare module 'net' { + import * as stream from 'node:stream'; + import { Abortable, EventEmitter } from 'node:events'; + import * as dns from 'node:dns'; + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will_not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`,`socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort: number; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): void; + end(buffer: Uint8Array | string, callback?: () => void): void; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: (hadError: boolean) => void): this; + addListener(event: 'connect', listener: () => void): this; + addListener(event: 'data', listener: (data: Buffer) => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: 'ready', listener: () => void): this; + addListener(event: 'timeout', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close', hadError: boolean): boolean; + emit(event: 'connect'): boolean; + emit(event: 'data', data: Buffer): boolean; + emit(event: 'drain'): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'lookup', err: Error, address: string, family: string | number, host: string): boolean; + emit(event: 'ready'): boolean; + emit(event: 'timeout'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: (hadError: boolean) => void): this; + on(event: 'connect', listener: () => void): this; + on(event: 'data', listener: (data: Buffer) => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: 'ready', listener: () => void): this; + on(event: 'timeout', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: (hadError: boolean) => void): this; + once(event: 'connect', listener: () => void): this; + once(event: 'data', listener: (data: Buffer) => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: 'ready', listener: () => void): this; + once(event: 'timeout', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: (hadError: boolean) => void): this; + prependListener(event: 'connect', listener: () => void): this; + prependListener(event: 'data', listener: (data: Buffer) => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: 'ready', listener: () => void): this; + prependListener(event: 'timeout', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: (hadError: boolean) => void): this; + prependOnceListener(event: 'connect', listener: () => void): this; + prependOnceListener(event: 'data', listener: (data: Buffer) => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'lookup', listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: 'ready', listener: () => void): this; + prependOnceListener(event: 'timeout', listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn`on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.log('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will_not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'connection', listener: (socket: Socket) => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'listening', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'connection', socket: Socket): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'listening'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'connection', listener: (socket: Socket) => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'listening', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'connection', listener: (socket: Socket) => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'listening', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'connection', listener: (socket: Socket) => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'listening', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'connection', listener: (socket: Socket) => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'listening', listener: () => void): this; + } + type IPVersion = 'ipv4' | 'ipv6'; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of an TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```console + * $ telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```console + * $ nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Tests if input is an IP address. Returns `0` for invalid strings, + * returns `4` for IP version 4 addresses, and returns `6` for IP version 6 + * addresses. + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if input is a version 4 IP address, otherwise returns `false`. + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if input is a version 6 IP address, otherwise returns `false`. + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0 + */ + readonly port: number; + /** + * @since v15.14.0 + */ + readonly flowlabel: number; + } +} +declare module 'node:net' { + export * from 'net'; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100755 index 0000000..4876210 --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,455 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/os.js) + */ +declare module 'os' { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: 'IPv4'; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: 'IPv6'; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0 + * } + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20 + * } + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling[`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. + * See[https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a `SystemError` if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: 'buffer' }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling[`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See[https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform. The value is set + * at compile time. Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): 'BE' | 'LE'; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module 'node:os' { + export * from 'os'; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100755 index 0000000..11c02a1 --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,231 @@ +{ + "_args": [ + [ + "@types/node@16.6.1", + "/home/other/discord_bot" + ] + ], + "_from": "@types/node@16.6.1", + "_id": "@types/node@16.6.1", + "_inBundle": false, + "_integrity": "sha512-Sr7BhXEAer9xyGuCN3Ek9eg9xPviCF2gfu9kTfuU2HkTVAMYSDeX40fvpmo72n5nansg3nsBjuQBrsS28r+NUw==", + "_location": "/@types/node", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@types/node@16.6.1", + "name": "@types/node", + "escapedName": "@types%2fnode", + "scope": "@types", + "rawSpec": "16.6.1", + "saveSpec": null, + "fetchSpec": "16.6.1" + }, + "_requiredBy": [ + "/@types/jsonwebtoken" + ], + "_resolved": "https://registry.npmjs.org/@types/node/-/node-16.6.1.tgz", + "_spec": "16.6.1", + "_where": "/home/other/discord_bot", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Hoàng Văn Khải", + "url": "https://github.com/KSXGitHub" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy" + }, + { + "name": "Marcin Kopacz", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "url": "https://github.com/trivikr" + }, + { + "name": "Minh Son Nguyen", + "url": "https://github.com/nguymin4" + }, + { + "name": "Junxiao Shi", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Surasak Chaisurin", + "url": "https://github.com/Ryan-Willpower" + }, + { + "name": "Piotr Błażejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "url": "https://github.com/addaleax" + }, + { + "name": "Jason Kwok", + "url": "https://github.com/JasonHK" + }, + { + "name": "Victor Perin", + "url": "https://github.com/victorperin" + }, + { + "name": "Yongsheng Zhang", + "url": "https://github.com/ZYSzys" + }, + { + "name": "NodeJS Contributors", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "url": "https://github.com/LinusU" + } + ], + "dependencies": {}, + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "main": "", + "name": "@types/node", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "typeScriptVersion": "3.6", + "types": "index.d.ts", + "typesPublisherContentHash": "f633e2ebd950a328c9dc33bbd6c2dc92d346161f794cc2264e0a2f0dc0fbb2c4", + "typesVersions": { + "<=3.6": { + "*": [ + "ts3.6/*" + ] + } + }, + "version": "16.6.1" +} diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100755 index 0000000..4595aed --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,172 @@ +declare module 'path/posix' { + import path = require('path'); + export = path; +} +declare module 'path/win32' { + import path = require('path'); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/path.js) + */ +declare module 'path' { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + isAbsolute(p: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + parse(p: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + format(pP: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module 'node:path' { + import path = require('path'); + export = path; +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100755 index 0000000..c9b4975 --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,555 @@ +/** + * This module provides an implementation of a subset of the W3C[Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * + * ```js + * const { PerformanceObserver, performance } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/perf_hooks.js) + */ +declare module 'perf_hooks' { + import { AsyncResource } from 'node:async_hooks'; + type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly details?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()`. + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using + * `perf_hooks.createHistogram()` that will record runtime durations in + * nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string, options?: MarkOptions): void; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark?: string, endMark?: string): void; + measure(name: string, options: MeasureOptions): void; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `` instance to notifications of new `` instances identified either by `options.entryTypes`or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called three times synchronously. `list` contains one item. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: ReadonlyArray; + } + | { + type: EntryType; + } + ): void; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * + * ## Examples + * @since v15.9.0 + */ + recordDelta(): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a ``. + * @since v15.9.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; +} +declare module 'node:perf_hooks' { + export * from 'perf_hooks'; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100755 index 0000000..be63386 --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,1476 @@ +declare module 'process' { + import * as tty from 'node:tty'; + import { Worker } from 'node:worker_threads'; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'; + type Signals = + | 'SIGABRT' + | 'SIGALRM' + | 'SIGBUS' + | 'SIGCHLD' + | 'SIGCONT' + | 'SIGFPE' + | 'SIGHUP' + | 'SIGILL' + | 'SIGINT' + | 'SIGIO' + | 'SIGIOT' + | 'SIGKILL' + | 'SIGPIPE' + | 'SIGPOLL' + | 'SIGPROF' + | 'SIGPWR' + | 'SIGQUIT' + | 'SIGSEGV' + | 'SIGSTKFLT' + | 'SIGSTOP' + | 'SIGSYS' + | 'SIGTERM' + | 'SIGTRAP' + | 'SIGTSTP' + | 'SIGTTIN' + | 'SIGTTOU' + | 'SIGUNUSED' + | 'SIGURG' + | 'SIGUSR1' + | 'SIGUSR2' + | 'SIGVTALRM' + | 'SIGWINCH' + | 'SIGXCPU' + | 'SIGXFSZ' + | 'SIGBREAK' + | 'SIGLOST' + | 'SIGINFO'; + type MultipleResolveType = 'resolve' | 'reject'; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: unknown) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @defaul false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling`process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + openStdin(): Socket; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, the `options` argument is ignored. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread’s `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and`process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()`explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the`process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit_before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the`process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. + */ + exit(code?: number): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @since v0.11.8 + */ + exitCode?: number | undefined; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid(): number; + /** + * The `process.setgid()` method sets the group identity of the process. (See[`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid(id: number | string): void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid(): number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See[`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid(id: number | string): void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid(): number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid(id: number | string): void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid(): number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid(id: number | string): void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups(): number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups(groups: ReadonlyArray): void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function,`process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `Object` containing the JavaScript + * representation of the configure options used to compile the current Node.js + * executable. This is the same as the `config.gypi` file that was produced when + * running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the`process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ`memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, `'x32'`, and `'x64'`. + * + * ```js + * import { arch } from 'process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: string; + /** + * The `process.platform` property returns a string identifying the operating + * system platform on which the Node.js process is running. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js[is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the`name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential * + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be`undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles.`options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + swallowErrors?: boolean | undefined; + }, + callback?: (error: Error | null) => void + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel,`process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return`true` so long as the IPC + * channel is connected and will return `false` after`process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides`Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g.,`inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The `process.traceDeprecation` property indicates whether the`--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: 'beforeExit', listener: BeforeExitListener): this; + addListener(event: 'disconnect', listener: DisconnectListener): this; + addListener(event: 'exit', listener: ExitListener): this; + addListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + addListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + addListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + addListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + addListener(event: 'warning', listener: WarningListener): this; + addListener(event: 'message', listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + addListener(event: 'worker', listener: WorkerListener): this; + emit(event: 'beforeExit', code: number): boolean; + emit(event: 'disconnect'): boolean; + emit(event: 'exit', code: number): boolean; + emit(event: 'rejectionHandled', promise: Promise): boolean; + emit(event: 'uncaughtException', error: Error): boolean; + emit(event: 'uncaughtExceptionMonitor', error: Error): boolean; + emit(event: 'unhandledRejection', reason: unknown, promise: Promise): boolean; + emit(event: 'warning', warning: Error): boolean; + emit(event: 'message', message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: 'multipleResolves', type: MultipleResolveType, promise: Promise, value: unknown): this; + emit(event: 'worker', listener: WorkerListener): this; + on(event: 'beforeExit', listener: BeforeExitListener): this; + on(event: 'disconnect', listener: DisconnectListener): this; + on(event: 'exit', listener: ExitListener): this; + on(event: 'rejectionHandled', listener: RejectionHandledListener): this; + on(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + on(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + on(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + on(event: 'warning', listener: WarningListener): this; + on(event: 'message', listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: 'multipleResolves', listener: MultipleResolveListener): this; + on(event: 'worker', listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'beforeExit', listener: BeforeExitListener): this; + once(event: 'disconnect', listener: DisconnectListener): this; + once(event: 'exit', listener: ExitListener): this; + once(event: 'rejectionHandled', listener: RejectionHandledListener): this; + once(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + once(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + once(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + once(event: 'warning', listener: WarningListener): this; + once(event: 'message', listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: 'multipleResolves', listener: MultipleResolveListener): this; + once(event: 'worker', listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependListener(event: 'disconnect', listener: DisconnectListener): this; + prependListener(event: 'exit', listener: ExitListener): this; + prependListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependListener(event: 'warning', listener: WarningListener): this; + prependListener(event: 'message', listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependListener(event: 'worker', listener: WorkerListener): this; + prependOnceListener(event: 'beforeExit', listener: BeforeExitListener): this; + prependOnceListener(event: 'disconnect', listener: DisconnectListener): this; + prependOnceListener(event: 'exit', listener: ExitListener): this; + prependOnceListener(event: 'rejectionHandled', listener: RejectionHandledListener): this; + prependOnceListener(event: 'uncaughtException', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'uncaughtExceptionMonitor', listener: UncaughtExceptionListener): this; + prependOnceListener(event: 'unhandledRejection', listener: UnhandledRejectionListener): this; + prependOnceListener(event: 'warning', listener: WarningListener): this; + prependOnceListener(event: 'message', listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: 'multipleResolves', listener: MultipleResolveListener): this; + prependOnceListener(event: 'worker', listener: WorkerListener): this; + listeners(event: 'beforeExit'): BeforeExitListener[]; + listeners(event: 'disconnect'): DisconnectListener[]; + listeners(event: 'exit'): ExitListener[]; + listeners(event: 'rejectionHandled'): RejectionHandledListener[]; + listeners(event: 'uncaughtException'): UncaughtExceptionListener[]; + listeners(event: 'uncaughtExceptionMonitor'): UncaughtExceptionListener[]; + listeners(event: 'unhandledRejection'): UnhandledRejectionListener[]; + listeners(event: 'warning'): WarningListener[]; + listeners(event: 'message'): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: 'multipleResolves'): MultipleResolveListener[]; + listeners(event: 'worker'): WorkerListener[]; + } + } + } + export = process; +} +declare module 'node:process' { + import process = require('process'); + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100755 index 0000000..8ea2c02 --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/punycode.js) + */ +declare module 'punycode' { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a[Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492)encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: ReadonlyArray): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module 'node:punycode' { + export * from 'punycode'; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100755 index 0000000..c29208e --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,131 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('querystring'); + * ``` + * + * The `querystring` API is considered Legacy. While it is still maintained, + * new code should use the `` API instead. + * @deprecated Legacy + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/querystring.js) + */ +declare module 'querystring' { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | null> {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`:[<string>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [<number>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [<bigint>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [<boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [<string\[\]>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [<number\[\]>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [<bigint\[\]>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [<boolean\[\]>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative`encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```js + * { + * foo: 'bar', + * abc: ['xyz', '123'] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given`str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module 'node:querystring' { + export * from 'querystring'; +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100755 index 0000000..00e9af1 --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,542 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time. It can be accessed + * using: + * + * ```js + * const readline = require('readline'); + * ``` + * + * The following simple example illustrates the basic use of the `readline` module. + * + * ```js + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * + * rl.question('What do you think of Node.js? ', (answer) => { + * // TODO: Log the answer in a database + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * }); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/readline.js) + */ +declare module 'readline' { + import { Abortable, EventEmitter } from 'node:events'; + interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' ') + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `readline.Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `readline.Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `readline.Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `readline.Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `readline.Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'history', listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'history', history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'history', listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'history', listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'history', listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'history', listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + type ReadLine = Interface; // type forwarded for backwards compatibility + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; + type CompleterResult = [string[], string]; + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * process.stdin.unref(); + * ``` + * @since v0.1.98 + */ + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * @since v0.7.7 + */ + function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + type Direction = -1 | 0 | 1; + interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given `TTY` stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given `TTY` stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given `TTY` `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given `TTY` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ' + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('fs'); + * const readline = require('readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module 'node:readline' { + export * from 'readline'; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100755 index 0000000..23fb26a --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,424 @@ +/** + * The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that + * is available both as a standalone program or includible in other applications. + * It can be accessed using: + * + * ```js + * const repl = require('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/repl.js) + */ +declare module 'repl' { + import { Interface, Completer, AsyncCompleter } from 'node:readline'; + import { Context } from 'node:vm'; + import { InspectOptions } from 'node:util'; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the`keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * } + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (*without* a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output`and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the`replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'close', listener: () => void): this; + addListener(event: 'line', listener: (input: string) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: 'SIGCONT', listener: () => void): this; + addListener(event: 'SIGINT', listener: () => void): this; + addListener(event: 'SIGTSTP', listener: () => void): this; + addListener(event: 'exit', listener: () => void): this; + addListener(event: 'reset', listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'close'): boolean; + emit(event: 'line', input: string): boolean; + emit(event: 'pause'): boolean; + emit(event: 'resume'): boolean; + emit(event: 'SIGCONT'): boolean; + emit(event: 'SIGINT'): boolean; + emit(event: 'SIGTSTP'): boolean; + emit(event: 'exit'): boolean; + emit(event: 'reset', context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'close', listener: () => void): this; + on(event: 'line', listener: (input: string) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: 'SIGCONT', listener: () => void): this; + on(event: 'SIGINT', listener: () => void): this; + on(event: 'SIGTSTP', listener: () => void): this; + on(event: 'exit', listener: () => void): this; + on(event: 'reset', listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'line', listener: (input: string) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: 'SIGCONT', listener: () => void): this; + once(event: 'SIGINT', listener: () => void): this; + once(event: 'SIGTSTP', listener: () => void): this; + once(event: 'exit', listener: () => void): this; + once(event: 'reset', listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'line', listener: (input: string) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: 'SIGCONT', listener: () => void): this; + prependListener(event: 'SIGINT', listener: () => void): this; + prependListener(event: 'SIGTSTP', listener: () => void): this; + prependListener(event: 'exit', listener: () => void): this; + prependListener(event: 'reset', listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'line', listener: (input: string) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: 'SIGCONT', listener: () => void): this; + prependOnceListener(event: 'SIGINT', listener: () => void): this; + prependOnceListener(event: 'SIGTSTP', listener: () => void): this; + prependOnceListener(event: 'exit', listener: () => void): this; + prependOnceListener(event: 'reset', listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module 'node:repl' { + export * from 'repl'; +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100755 index 0000000..88d7de7 --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1178 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a `request to an HTTP server` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/stream.js) + */ +declare module 'stream' { + import { EventEmitter, Abortable } from 'node:events'; + import * as streamPromises from 'node:stream/promises'; + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + } + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Is `true` if it is safe to call `readable.read()`, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'end'` event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the `Three states` section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method pulls some data out of the internal buffer and + * returns it. If no data available to be read, `null` is returned. By default, + * the data will be returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If`size` bytes are not available to be read, `null` will be returned _unless_the stream has ended, in which + * case all of the data remaining in the internal + * buffer will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the`size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as`Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer`objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'`event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the`Readable`. This is used primarily by the mechanism that underlies the`readable.pipe()` method. In most + * typical cases, there will be no reason to + * use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.match(/\n\n/)) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * } else { + * // Still reading the header. + * header += str; + * } + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode + * streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `stream` module API + * as it is currently defined. (See `Compatibility` for more information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the`readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()`will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): void; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'data', listener: (chunk: any) => void): this; + addListener(event: 'end', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'pause', listener: () => void): this; + addListener(event: 'readable', listener: () => void): this; + addListener(event: 'resume', listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'data', chunk: any): boolean; + emit(event: 'end'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'pause'): boolean; + emit(event: 'readable'): boolean; + emit(event: 'resume'): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'data', listener: (chunk: any) => void): this; + on(event: 'end', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'pause', listener: () => void): this; + on(event: 'readable', listener: () => void): this; + on(event: 'resume', listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'data', listener: (chunk: any) => void): this; + once(event: 'end', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'pause', listener: () => void): this; + once(event: 'readable', listener: () => void): this; + once(event: 'resume', listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'data', listener: (chunk: any) => void): this; + prependListener(event: 'end', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'pause', listener: () => void): this; + prependListener(event: 'readable', listener: () => void): this; + prependListener(event: 'resume', listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'data', listener: (chunk: any) => void): this; + prependOnceListener(event: 'end', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'pause', listener: () => void): this; + prependOnceListener(event: 'readable', listener: () => void): this; + prependOnceListener(event: 'resume', listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'data', listener: (chunk: any) => void): this; + removeListener(event: 'end', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'pause', listener: () => void): this; + removeListener(event: 'readable', listener: () => void): this; + removeListener(event: 'resume', listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?(this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the`highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * It is recommended that once `write()` returns false, no more chunks be written + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any + * JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): void; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()`buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing`writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, it is recommended that calls to `writable.uncork()` be + * deferred using `process.nextTick()`. Doing so allows batching of all`writable.write()` calls that occur within a given Node.js event loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): void; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: 'close', listener: () => void): this; + addListener(event: 'drain', listener: () => void): this; + addListener(event: 'error', listener: (err: Error) => void): this; + addListener(event: 'finish', listener: () => void): this; + addListener(event: 'pipe', listener: (src: Readable) => void): this; + addListener(event: 'unpipe', listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: 'close'): boolean; + emit(event: 'drain'): boolean; + emit(event: 'error', err: Error): boolean; + emit(event: 'finish'): boolean; + emit(event: 'pipe', src: Readable): boolean; + emit(event: 'unpipe', src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'close', listener: () => void): this; + on(event: 'drain', listener: () => void): this; + on(event: 'error', listener: (err: Error) => void): this; + on(event: 'finish', listener: () => void): this; + on(event: 'pipe', listener: (src: Readable) => void): this; + on(event: 'unpipe', listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: 'close', listener: () => void): this; + once(event: 'drain', listener: () => void): this; + once(event: 'error', listener: (err: Error) => void): this; + once(event: 'finish', listener: () => void): this; + once(event: 'pipe', listener: (src: Readable) => void): this; + once(event: 'unpipe', listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: 'close', listener: () => void): this; + prependListener(event: 'drain', listener: () => void): this; + prependListener(event: 'error', listener: (err: Error) => void): this; + prependListener(event: 'finish', listener: () => void): this; + prependListener(event: 'pipe', listener: (src: Readable) => void): this; + prependListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'close', listener: () => void): this; + prependOnceListener(event: 'drain', listener: () => void): this; + prependOnceListener(event: 'error', listener: (err: Error) => void): this; + prependOnceListener(event: 'finish', listener: () => void): this; + prependOnceListener(event: 'pipe', listener: (src: Readable) => void): this; + prependOnceListener(event: 'unpipe', listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: 'close', listener: () => void): this; + removeListener(event: 'drain', listener: () => void): this; + removeListener(event: 'error', listener: (err: Error) => void): this; + removeListener(event: 'finish', listener: () => void): this; + removeListener(event: 'pipe', listener: (src: Readable) => void): this; + removeListener(event: 'unpipe', listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): void; + cork(): void; + uncork(): void; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where`stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`on the stream. + * + * ```js + * const fs = require('fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')) + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream a stream to attach a signal to + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'`or `'finish'`. + * + * The `finished` API provides promise version: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `stream.finished()` leaves dangling event listeners (in particular`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @return A cleanup function which removes all registered listeners. + */ + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | ((source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable : S) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends PipelineTransformSource + ? NodeJS.WritableStream | PipelineDestinationIterableFunction | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends PipelineDestinationPromiseFunction + ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal: AbortSignal; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * } + * ); + * ``` + * + * The `pipeline` API provides a promise version, which can also + * receive an options argument as the last parameter with a`signal` `` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const options = { + * signal: ac.signal, + * }; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * options, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield chunk.toUpperCase(); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback?: PipelineCallback + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, callback?: PipelineCallback): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)> + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function __promisify__(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + const promises: typeof streamPromises; + } + export = internal; +} +declare module 'node:stream' { + import stream = require('stream'); + export = stream; +} diff --git a/node_modules/@types/node/stream/promises.d.ts b/node_modules/@types/node/stream/promises.d.ts new file mode 100755 index 0000000..b427073 --- /dev/null +++ b/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,42 @@ +declare module 'stream/promises' { + import { FinishedOptions, PipelineSource, PipelineTransform, PipelineDestination, PipelinePromise, PipelineOptions } from 'node:stream'; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + function pipeline, B extends PipelineDestination>(source: A, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline, T1 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline, T1 extends PipelineTransform, T2 extends PipelineTransform, B extends PipelineDestination>( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination + >(source: A, transform1: T1, transform2: T2, transform3: T3, transform4: T4, destination: B, options?: PipelineOptions): PipelinePromise; + function pipeline(streams: ReadonlyArray, options?: PipelineOptions): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module 'node:stream/promises' { + export * from 'stream/promises'; +} diff --git a/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts new file mode 100755 index 0000000..c5d1d1a --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,7 @@ +declare module 'stream/web' { + // stub module, pending copy&paste from .d.ts or manual impl +} + +declare module 'node:stream/web' { + export * from 'stream/web'; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100755 index 0000000..759533b --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `string_decoder` module provides an API for decoding `Buffer` objects into + * strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/string_decoder.js) + */ +declare module 'string_decoder' { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module 'node:string_decoder' { + export * from 'string_decoder'; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100755 index 0000000..553b5d6 --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,94 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/timers.js) + */ +declare module 'timers' { + import { Abortable } from 'node:events'; + import { setTimeout as setTimeoutPromise, setImmediate as setImmediatePromise, setInterval as setIntervalPromise } from 'node:timers/promises'; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + interface Immediate extends RefCounted { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + } + interface Timeout extends Timer { + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + } + } + function setTimeout(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timeout; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: TArgs) => void, ms?: number, ...args: TArgs): NodeJS.Timer; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timer; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: TArgs) => void, ...args: TArgs): NodeJS.Immediate; + // util.promisify no rest args compability + // tslint:disable-next-line void-return + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module 'node:timers' { + export * from 'timers'; +} diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts new file mode 100755 index 0000000..fd77888 --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,68 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module 'timers/promises' { + import { TimerOptions } from 'node:timers'; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; +} +declare module 'node:timers/promises' { + export * from 'timers/promises'; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100755 index 0000000..2f1c373 --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1018 @@ +/** + * The `tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/tls.js) + */ +declare module 'tls' { + import { X509Certificate } from 'node:crypto'; + import * as net from 'node:net'; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: NodeJS.Dict; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + fingerprint256: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: TLSSocketOptions); + /** + * Returns `true` if the peer certificate was signed by one of the CAs specified + * when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: boolean; + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string | undefined; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * See[SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html)for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See[SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html)for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * Note: The format of the output is identical to the output of `openssl s_client -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's`SSL_trace()` function, the format is + * undocumented, can change without notice, + * and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + addListener(event: 'secureConnect', listener: () => void): this; + addListener(event: 'session', listener: (session: Buffer) => void): this; + addListener(event: 'keylog', listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'OCSPResponse', response: Buffer): boolean; + emit(event: 'secureConnect'): boolean; + emit(event: 'session', session: Buffer): boolean; + emit(event: 'keylog', line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + on(event: 'secureConnect', listener: () => void): this; + on(event: 'session', listener: (session: Buffer) => void): this; + on(event: 'keylog', listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + once(event: 'secureConnect', listener: () => void): this; + once(event: 'session', listener: (session: Buffer) => void): this; + once(event: 'keylog', listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependListener(event: 'secureConnect', listener: () => void): this; + prependListener(event: 'session', listener: (session: Buffer) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this; + prependOnceListener(event: 'secureConnect', listener: () => void): this; + prependOnceListener(event: 'session', listener: (session: Buffer) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'tlsClientError', err: Error, tlsSocket: TLSSocket): boolean; + emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: 'secureConnection', tlsSocket: TLSSocket): boolean; + emit(event: 'keylog', line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + on(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + once(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + interface SecureContextOptions { + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use + * openssl dhparam to create the parameters. The key length must be + * greater than or equal to 1024 bits or else an error will be thrown. + * Although 1024 bits is permissible, use 2048 bits or larger for + * stronger security. If omitted or invalid, the parameters are + * silently discarded and DHE ciphers will not be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [<Error>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [<undefined>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function can be overwritten by providing alternative function as part of + * the `options.checkServerIdentity` option passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ] + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('tls'); + * const fs = require('fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair(context?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + /** + * {@link createServer} sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * {@link createServer} uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. + * + * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using[Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of {@link createSecureContext}. + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is 'auto'. See tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.createSecureContext(). It can be assigned any of the supported TLS + * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: + * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets + * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the highest maximum + * is used. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.createSecureContext(). + * It can be assigned any of the supported TLS protocol versions, + * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless + * changed using CLI options. Using --tls-min-v1.0 sets the default to + * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using + * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options + * are provided, the lowest minimum is used. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: ReadonlyArray; +} +declare module 'node:tls' { + export * from 'tls'; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100755 index 0000000..584de99 --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,161 @@ +/** + * The `trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed `async_hooks` trace data. + * The `async_hooks` events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()`output. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled`flag to enable trace events. This requirement has been removed. However, the`--trace-events-enabled` flag _may_ still be + * used and will enable the`node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `trace_events` module: + * + * ```js + * const trace_events = require('trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool)tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where`${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in `Worker` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/trace_events.js) + */ +declare module 'trace_events' { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + * @return . + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command`node --trace-event-categories node.perf test.js` will print`'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module 'node:trace_events' { + export * from 'trace_events'; +} diff --git a/node_modules/@types/node/ts3.6/assert.d.ts b/node_modules/@types/node/ts3.6/assert.d.ts new file mode 100755 index 0000000..4643f0a --- /dev/null +++ b/node_modules/@types/node/ts3.6/assert.d.ts @@ -0,0 +1,103 @@ +declare module 'assert' { + /** An alias of `assert.ok()`. */ + function assert(value: unknown, message?: string | Error): void; + namespace assert { + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string; + /** The `actual` property on the error instance. */ + actual?: unknown; + /** The `expected` property on the error instance. */ + expected?: unknown; + /** The `operator` property on the error instance. */ + operator?: string; + /** If provided, the generated stack trace omits frames before this function. */ + // tslint:disable-next-line:ban-types + stackStartFn?: Function; + }); + } + + class CallTracker { + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + report(): CallTrackerReportInformation[]; + verify(): void; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + + type AssertPredicate = RegExp | (new () => object) | ((thrown: unknown) => boolean) | object | Error; + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // tslint:disable-next-line:ban-types + stackStartFn?: Function, + ): never; + function ok(value: unknown, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + function strictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + function deepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + + function ifError(value: unknown): void; + + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + + function match(value: string, regExp: RegExp, message?: string | Error): void; + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + + const strict: typeof assert; + } + + export = assert; +} + +declare module 'node:assert' { + import assert = require('assert'); + export = assert; +} diff --git a/node_modules/@types/node/ts3.6/base.d.ts b/node_modules/@types/node/ts3.6/base.d.ts new file mode 100755 index 0000000..dd304dc --- /dev/null +++ b/node_modules/@types/node/ts3.6/base.d.ts @@ -0,0 +1,68 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.6 and earlier. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 3.7 and above +// - ~/ts3.6/base.d.ts - Definitions specific to TypeScript 3.6 and earlier +// - ~/ts3.6/index.d.ts - Definitions specific to TypeScript 3.6 and earlier with assert pulled in + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +// TypeScript 3.6-specific augmentations: +/// + +// TypeScript 3.6-specific augmentations: +/// diff --git a/node_modules/@types/node/ts3.6/index.d.ts b/node_modules/@types/node/ts3.6/index.d.ts new file mode 100755 index 0000000..1a7d360 --- /dev/null +++ b/node_modules/@types/node/ts3.6/index.d.ts @@ -0,0 +1,7 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.6. +// This is required to enable typing assert in ts3.7 without causing errors +// Typically type modifications should be made in base.d.ts instead of here + +/// + +/// diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100755 index 0000000..a1aa562 --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,206 @@ +/** + * The `tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. + * In most cases, it will not be necessary or possible to use this module directly. + * However, it can be accessed using: + * + * ```js + * const tty = require('tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes. + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/tty.js) + */ +declare module 'tty' { + import * as net from 'node:net'; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. Defaults to `false`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input characters.Ctrl+C will no longer cause a `SIGINT` when in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: 'resize', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'resize'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: 'resize', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: 'resize', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'resize', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'resize', listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 + * + * colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module 'node:tty' { + export * from 'tty'; +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100755 index 0000000..4dcffd5 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,763 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/url.js) + */ +declare module 'url' { + import { ClientRequestArgs } from 'node:http'; + import { ParsedUrlQuery, ParsedUrlQueryInput } from 'node:querystring'; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from`urlObject`. + * + * ```js + * const url = require('url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json' + * } + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//`will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or`file`; + * * If the value of the `urlObject.auth` property is truthy, and either`urlObject.host` or `urlObject.hostname` are not `undefined`, the value of`urlObject.auth` will be coerced into a string + * and appended to `result`followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname`is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to`result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of`urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname`_does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result`followed by the output of calling the + * `querystring` module's `stringify()`method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search`_does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash`_does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a Web browser resolving an anchor tag HREF. + * + * ```js + * const url = require('url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * You can achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @deprecated Legacy: Use the WHATWG URL API instead. + * @param from The Base URL being resolved against. + * @param to The HREF URL being resolved. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from 'url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myUrl)); + * + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject` s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + constructor(input: string, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL`object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError`will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname`property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range`0` to `65535` (inclusive). Setting the value to the default port of the`URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myUrl = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myUrl.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myUrl.searchParams.sort(); + * + * console.log(myUrl.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username`property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a`URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | NodeJS.Dict> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array`is the `name`, the second item of the `Array` is the `value`. + * + * Alias for {@link earchParams[@@iterator]}. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach(callback: (this: TThis, value: string, name: string, searchParams: this) => void, thisArg?: TThis): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to`value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} +declare module 'node:url' { + export * from 'url'; +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100755 index 0000000..039793c --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,1556 @@ +/** + * The `util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/util.js) + */ +declare module 'util' { + import * as types from 'node:util/types'; + export interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean | undefined; + showHidden?: boolean | undefined; + /** + * @default 2 + */ + depth?: number | null | undefined; + colors?: boolean | undefined; + customInspect?: boolean | undefined; + showProxy?: boolean | undefined; + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number | undefined; + sorted?: boolean | ((a: string, b: string) => number) | undefined; + } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`\-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using`util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()`returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result.`util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]) + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same[`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('util'); + * const assert = require('assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]) + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1] + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }) + * ); + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and`extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from`superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('util'); + * const EventEmitter = require('events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @deprecated Legacy: Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a`DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the`process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation`property take precedence over `--trace-deprecation` and`process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise`resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named`reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && err.hasOwnProperty('reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param original An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()`will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + const custom: unique symbol; + } + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/)`TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder('shift_jis'); + * let string = ''; + * let buffer; + * while (buffer = getNextChunkSomehow()) { + * string += decoder.decode(buffer, { stream: true }); + * } + * string += decoder.decode(); // end-of-stream + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + } + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + } + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/)`TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } +} +declare module 'util/types' { + export * from 'util/types'; +} +declare module 'util/types' { + import { KeyObject, webcrypto } from 'node:crypto'; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) + * or[`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)views, such as typed array + * objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent + * to[`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap(object: T | {}): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet(object: T | {}): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in[`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a ``, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a ``, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module 'node:util' { + export * from 'util'; +} +declare module 'node:util/types' { + export * from 'util/types'; +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100755 index 0000000..8314ef1 --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,378 @@ +/** + * The `v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/)built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/v8.js) + */ +declare module 'v8' { + import { Readable } from 'node:stream'; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the`--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8[`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running`node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream containing the V8 heap snapshot + */ + function getHeapSnapshot(): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * ```js + * const { writeHeapSnapshot } = require('v8'); + * const { + * Worker, + * isMainThread, + * parentPort + * } = require('worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string): string; + /** + * Returns an object with the following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794 + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer’s internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before`.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]`with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer’s internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v12.22.0 + */ + function stopCoverage(): void; +} +declare module 'node:v8' { + export * from 'v8'; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100755 index 0000000..e7e6c21 --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,504 @@ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. **The `vm` module is not a security mechanism. Do** + * **not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v16.6.0/lib/vm.js) + */ +declare module 'vm' { + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean | undefined; + timeout?: number | undefined; + cachedData?: Buffer | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: 'afterEvaluate' | undefined; + } + type MeasureMemoryMode = 'summary' | 'detailed'; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + context?: Context | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions); + /** + * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('vm'); + * + * const context = { + * animal: 'cat', + * count: 2 + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but_does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + cachedDataRejected?: boolean | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, + * the `contextObject` will be the global object, retaining all of its existing + * properties but also having the built-in objects and functions any standard[global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables + * will remain unchanged. + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all ` +``` + +Using unpkg CDN: + +```html + +``` + +## Example + +### note: CommonJS usage +In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: + +```js +const axios = require('axios').default; + +// axios. will now provide autocomplete and parameter typings +``` + +Performing a `GET` request + +```js +const axios = require('axios'); + +// Make a request for a user with a given ID +axios.get('/user?ID=12345') + .then(function (response) { + // handle success + console.log(response); + }) + .catch(function (error) { + // handle error + console.log(error); + }) + .then(function () { + // always executed + }); + +// Optionally the request above could also be done as +axios.get('/user', { + params: { + ID: 12345 + } + }) + .then(function (response) { + console.log(response); + }) + .catch(function (error) { + console.log(error); + }) + .then(function () { + // always executed + }); + +// Want to use async/await? Add the `async` keyword to your outer function/method. +async function getUser() { + try { + const response = await axios.get('/user?ID=12345'); + console.log(response); + } catch (error) { + console.error(error); + } +} +``` + +> **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet +> Explorer and older browsers, so use with caution. + +Performing a `POST` request + +```js +axios.post('/user', { + firstName: 'Fred', + lastName: 'Flintstone' + }) + .then(function (response) { + console.log(response); + }) + .catch(function (error) { + console.log(error); + }); +``` + +Performing multiple concurrent requests + +```js +function getUserAccount() { + return axios.get('/user/12345'); +} + +function getUserPermissions() { + return axios.get('/user/12345/permissions'); +} + +Promise.all([getUserAccount(), getUserPermissions()]) + .then(function (results) { + const acct = results[0]; + const perm = results[1]; + }); +``` + +## axios API + +Requests can be made by passing the relevant config to `axios`. + +##### axios(config) + +```js +// Send a POST request +axios({ + method: 'post', + url: '/user/12345', + data: { + firstName: 'Fred', + lastName: 'Flintstone' + } +}); +``` + +```js +// GET request for remote image in node.js +axios({ + method: 'get', + url: 'http://bit.ly/2mTM3nY', + responseType: 'stream' +}) + .then(function (response) { + response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) + }); +``` + +##### axios(url[, config]) + +```js +// Send a GET request (default method) +axios('/user/12345'); +``` + +### Request method aliases + +For convenience aliases have been provided for all supported request methods. + +##### axios.request(config) +##### axios.get(url[, config]) +##### axios.delete(url[, config]) +##### axios.head(url[, config]) +##### axios.options(url[, config]) +##### axios.post(url[, data[, config]]) +##### axios.put(url[, data[, config]]) +##### axios.patch(url[, data[, config]]) + +###### NOTE +When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. + +### Concurrency (Deprecated) +Please use `Promise.all` to replace the below functions. + +Helper functions for dealing with concurrent requests. + +axios.all(iterable) +axios.spread(callback) + +### Creating an instance + +You can create a new instance of axios with a custom config. + +##### axios.create([config]) + +```js +const instance = axios.create({ + baseURL: 'https://some-domain.com/api/', + timeout: 1000, + headers: {'X-Custom-Header': 'foobar'} +}); +``` + +### Instance methods + +The available instance methods are listed below. The specified config will be merged with the instance config. + +##### axios#request(config) +##### axios#get(url[, config]) +##### axios#delete(url[, config]) +##### axios#head(url[, config]) +##### axios#options(url[, config]) +##### axios#post(url[, data[, config]]) +##### axios#put(url[, data[, config]]) +##### axios#patch(url[, data[, config]]) +##### axios#getUri([config]) + +## Request Config + +These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. + +```js +{ + // `url` is the server URL that will be used for the request + url: '/user', + + // `method` is the request method to be used when making the request + method: 'get', // default + + // `baseURL` will be prepended to `url` unless `url` is absolute. + // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs + // to methods of that instance. + baseURL: 'https://some-domain.com/api/', + + // `transformRequest` allows changes to the request data before it is sent to the server + // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' + // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, + // FormData or Stream + // You may modify the headers object. + transformRequest: [function (data, headers) { + // Do whatever you want to transform the data + + return data; + }], + + // `transformResponse` allows changes to the response data to be made before + // it is passed to then/catch + transformResponse: [function (data) { + // Do whatever you want to transform the data + + return data; + }], + + // `headers` are custom headers to be sent + headers: {'X-Requested-With': 'XMLHttpRequest'}, + + // `params` are the URL parameters to be sent with the request + // Must be a plain object or a URLSearchParams object + params: { + ID: 12345 + }, + + // `paramsSerializer` is an optional function in charge of serializing `params` + // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) + paramsSerializer: function (params) { + return Qs.stringify(params, {arrayFormat: 'brackets'}) + }, + + // `data` is the data to be sent as the request body + // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' + // When no `transformRequest` is set, must be of one of the following types: + // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams + // - Browser only: FormData, File, Blob + // - Node only: Stream, Buffer + data: { + firstName: 'Fred' + }, + + // syntax alternative to send data into the body + // method post + // only the value is sent, not the key + data: 'Country=Brasil&City=Belo Horizonte', + + // `timeout` specifies the number of milliseconds before the request times out. + // If the request takes longer than `timeout`, the request will be aborted. + timeout: 1000, // default is `0` (no timeout) + + // `withCredentials` indicates whether or not cross-site Access-Control requests + // should be made using credentials + withCredentials: false, // default + + // `adapter` allows custom handling of requests which makes testing easier. + // Return a promise and supply a valid response (see lib/adapters/README.md). + adapter: function (config) { + /* ... */ + }, + + // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. + // This will set an `Authorization` header, overwriting any existing + // `Authorization` custom headers you have set using `headers`. + // Please note that only HTTP Basic auth is configurable through this parameter. + // For Bearer tokens and such, use `Authorization` custom headers instead. + auth: { + username: 'janedoe', + password: 's00pers3cret' + }, + + // `responseType` indicates the type of data that the server will respond with + // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' + // browser only: 'blob' + responseType: 'json', // default + + // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) + // Note: Ignored for `responseType` of 'stream' or client-side requests + responseEncoding: 'utf8', // default + + // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token + xsrfCookieName: 'XSRF-TOKEN', // default + + // `xsrfHeaderName` is the name of the http header that carries the xsrf token value + xsrfHeaderName: 'X-XSRF-TOKEN', // default + + // `onUploadProgress` allows handling of progress events for uploads + // browser only + onUploadProgress: function (progressEvent) { + // Do whatever you want with the native progress event + }, + + // `onDownloadProgress` allows handling of progress events for downloads + // browser only + onDownloadProgress: function (progressEvent) { + // Do whatever you want with the native progress event + }, + + // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js + maxContentLength: 2000, + + // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed + maxBodyLength: 2000, + + // `validateStatus` defines whether to resolve or reject the promise for a given + // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` + // or `undefined`), the promise will be resolved; otherwise, the promise will be + // rejected. + validateStatus: function (status) { + return status >= 200 && status < 300; // default + }, + + // `maxRedirects` defines the maximum number of redirects to follow in node.js. + // If set to 0, no redirects will be followed. + maxRedirects: 5, // default + + // `socketPath` defines a UNIX Socket to be used in node.js. + // e.g. '/var/run/docker.sock' to send requests to the docker daemon. + // Only either `socketPath` or `proxy` can be specified. + // If both are specified, `socketPath` is used. + socketPath: null, // default + + // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http + // and https requests, respectively, in node.js. This allows options to be added like + // `keepAlive` that are not enabled by default. + httpAgent: new http.Agent({ keepAlive: true }), + httpsAgent: new https.Agent({ keepAlive: true }), + + // `proxy` defines the hostname, port, and protocol of the proxy server. + // You can also define your proxy using the conventional `http_proxy` and + // `https_proxy` environment variables. If you are using environment variables + // for your proxy configuration, you can also define a `no_proxy` environment + // variable as a comma-separated list of domains that should not be proxied. + // Use `false` to disable proxies, ignoring environment variables. + // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and + // supplies credentials. + // This will set an `Proxy-Authorization` header, overwriting any existing + // `Proxy-Authorization` custom headers you have set using `headers`. + // If the proxy server uses HTTPS, then you must set the protocol to `https`. + proxy: { + protocol: 'https', + host: '127.0.0.1', + port: 9000, + auth: { + username: 'mikeymike', + password: 'rapunz3l' + } + }, + + // `cancelToken` specifies a cancel token that can be used to cancel the request + // (see Cancellation section below for details) + cancelToken: new CancelToken(function (cancel) { + }), + + // `decompress` indicates whether or not the response body should be decompressed + // automatically. If set to `true` will also remove the 'content-encoding' header + // from the responses objects of all decompressed responses + // - Node only (XHR cannot turn off decompression) + decompress: true, // default + + // transitional options for backward compatibility that may be removed in the newer versions + transitional: { + // silent JSON parsing mode + // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour) + // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json') + silentJSONParsing: true, // default value for the current Axios version + + // try to parse the response string as JSON even if `responseType` is not 'json' + forcedJSONParsing: true, + + // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts + clarifyTimeoutError: false, + } +} +``` + +## Response Schema + +The response for a request contains the following information. + +```js +{ + // `data` is the response that was provided by the server + data: {}, + + // `status` is the HTTP status code from the server response + status: 200, + + // `statusText` is the HTTP status message from the server response + statusText: 'OK', + + // `headers` the HTTP headers that the server responded with + // All header names are lower cased and can be accessed using the bracket notation. + // Example: `response.headers['content-type']` + headers: {}, + + // `config` is the config that was provided to `axios` for the request + config: {}, + + // `request` is the request that generated this response + // It is the last ClientRequest instance in node.js (in redirects) + // and an XMLHttpRequest instance in the browser + request: {} +} +``` + +When using `then`, you will receive the response as follows: + +```js +axios.get('/user/12345') + .then(function (response) { + console.log(response.data); + console.log(response.status); + console.log(response.statusText); + console.log(response.headers); + console.log(response.config); + }); +``` + +When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. + +## Config Defaults + +You can specify config defaults that will be applied to every request. + +### Global axios defaults + +```js +axios.defaults.baseURL = 'https://api.example.com'; + +// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them. +// See below for an example using Custom instance defaults instead. +axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; + +axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; +``` + +### Custom instance defaults + +```js +// Set config defaults when creating the instance +const instance = axios.create({ + baseURL: 'https://api.example.com' +}); + +// Alter defaults after instance has been created +instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; +``` + +### Config order of precedence + +Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. + +```js +// Create an instance using the config defaults provided by the library +// At this point the timeout config value is `0` as is the default for the library +const instance = axios.create(); + +// Override timeout default for the library +// Now all requests using this instance will wait 2.5 seconds before timing out +instance.defaults.timeout = 2500; + +// Override timeout for this request as it's known to take a long time +instance.get('/longRequest', { + timeout: 5000 +}); +``` + +## Interceptors + +You can intercept requests or responses before they are handled by `then` or `catch`. + +```js +// Add a request interceptor +axios.interceptors.request.use(function (config) { + // Do something before request is sent + return config; + }, function (error) { + // Do something with request error + return Promise.reject(error); + }); + +// Add a response interceptor +axios.interceptors.response.use(function (response) { + // Any status code that lie within the range of 2xx cause this function to trigger + // Do something with response data + return response; + }, function (error) { + // Any status codes that falls outside the range of 2xx cause this function to trigger + // Do something with response error + return Promise.reject(error); + }); +``` + +If you need to remove an interceptor later you can. + +```js +const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); +axios.interceptors.request.eject(myInterceptor); +``` + +You can add interceptors to a custom instance of axios. + +```js +const instance = axios.create(); +instance.interceptors.request.use(function () {/*...*/}); +``` + +When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay +in the execution of your axios request when the main thread is blocked (a promise is created under the hood for +the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag +to the options object that will tell axios to run the code synchronously and avoid any delays in request execution. + +```js +axios.interceptors.request.use(function (config) { + config.headers.test = 'I am only a header!'; + return config; +}, null, { synchronous: true }); +``` + +If you want to execute a particular interceptor based on a runtime check, +you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return +of `runWhen` is `false`. The function will be called with the config +object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an +asynchronous request interceptor that only needs to run at certain times. + +```js +function onGetCall(config) { + return config.method === 'get'; +} +axios.interceptors.request.use(function (config) { + config.headers.test = 'special get headers'; + return config; +}, null, { runWhen: onGetCall }); +``` + +## Handling Errors + +```js +axios.get('/user/12345') + .catch(function (error) { + if (error.response) { + // The request was made and the server responded with a status code + // that falls out of the range of 2xx + console.log(error.response.data); + console.log(error.response.status); + console.log(error.response.headers); + } else if (error.request) { + // The request was made but no response was received + // `error.request` is an instance of XMLHttpRequest in the browser and an instance of + // http.ClientRequest in node.js + console.log(error.request); + } else { + // Something happened in setting up the request that triggered an Error + console.log('Error', error.message); + } + console.log(error.config); + }); +``` + +Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. + +```js +axios.get('/user/12345', { + validateStatus: function (status) { + return status < 500; // Resolve only if the status code is less than 500 + } +}) +``` + +Using `toJSON` you get an object with more information about the HTTP error. + +```js +axios.get('/user/12345') + .catch(function (error) { + console.log(error.toJSON()); + }); +``` + +## Cancellation + +You can cancel a request using a *cancel token*. + +> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). + +You can create a cancel token using the `CancelToken.source` factory as shown below: + +```js +const CancelToken = axios.CancelToken; +const source = CancelToken.source(); + +axios.get('/user/12345', { + cancelToken: source.token +}).catch(function (thrown) { + if (axios.isCancel(thrown)) { + console.log('Request canceled', thrown.message); + } else { + // handle error + } +}); + +axios.post('/user/12345', { + name: 'new name' +}, { + cancelToken: source.token +}) + +// cancel the request (the message parameter is optional) +source.cancel('Operation canceled by the user.'); +``` + +You can also create a cancel token by passing an executor function to the `CancelToken` constructor: + +```js +const CancelToken = axios.CancelToken; +let cancel; + +axios.get('/user/12345', { + cancelToken: new CancelToken(function executor(c) { + // An executor function receives a cancel function as a parameter + cancel = c; + }) +}); + +// cancel the request +cancel(); +``` + +> Note: you can cancel several requests with the same cancel token. +> If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make real request. + +## Using application/x-www-form-urlencoded format + +By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. + +### Browser + +In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: + +```js +const params = new URLSearchParams(); +params.append('param1', 'value1'); +params.append('param2', 'value2'); +axios.post('/foo', params); +``` + +> Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). + +Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: + +```js +const qs = require('qs'); +axios.post('/foo', qs.stringify({ 'bar': 123 })); +``` + +Or in another way (ES6), + +```js +import qs from 'qs'; +const data = { 'bar': 123 }; +const options = { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + data: qs.stringify(data), + url, +}; +axios(options); +``` + +### Node.js + +#### Query string + +In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: + +```js +const querystring = require('querystring'); +axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); +``` + +or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows: + +```js +const url = require('url'); +const params = new url.URLSearchParams({ foo: 'bar' }); +axios.post('http://something.com/', params.toString()); +``` + +You can also use the [`qs`](https://github.com/ljharb/qs) library. + +###### NOTE +The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665). + +#### Form data + +In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows: + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); + +axios.post('https://example.com', form, { headers: form.getHeaders() }) +``` + +Alternatively, use an interceptor: + +```js +axios.interceptors.request.use(config => { + if (config.data instanceof FormData) { + Object.assign(config.headers, config.data.getHeaders()); + } + return config; +}); +``` + +## Semver + +Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. + +## Promises + +axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). +If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). + +## TypeScript + +axios includes [TypeScript](http://typescriptlang.org) definitions and a type guard for axios errors. + +```typescript +let user: User = null; +try { + const { data } = await axios.get('/user?ID=12345'); + user = data.userDetails; +} catch (error) { + if (axios.isAxiosError(error)) { + handleAxiosError(error); + } else { + handleUnexpectedError(error); + } +} +``` + +## Online one-click setup + +You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/master/examples/server.js) + + +## Resources + +* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) +* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) +* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) +* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) +* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) + +## Credits + +axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. + +## License + +[MIT](LICENSE) diff --git a/node_modules/axios/SECURITY.md b/node_modules/axios/SECURITY.md new file mode 100644 index 0000000..353df9a --- /dev/null +++ b/node_modules/axios/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +Please report security issues to jasonsaayman@gmail.com diff --git a/node_modules/axios/UPGRADE_GUIDE.md b/node_modules/axios/UPGRADE_GUIDE.md new file mode 100644 index 0000000..745e804 --- /dev/null +++ b/node_modules/axios/UPGRADE_GUIDE.md @@ -0,0 +1,162 @@ +# Upgrade Guide + +### 0.15.x -> 0.16.0 + +#### `Promise` Type Declarations + +The `Promise` type declarations have been removed from the axios typings in favor of the built-in type declarations. If you use axios in a TypeScript project that targets `ES5`, please make sure to include the `es2015.promise` lib. Please see [this post](https://blog.mariusschulz.com/2016/11/25/typescript-2-0-built-in-type-declarations) for details. + +### 0.13.x -> 0.14.0 + +#### TypeScript Definitions + +The axios TypeScript definitions have been updated to match the axios API and use the ES2015 module syntax. + +Please use the following `import` statement to import axios in TypeScript: + +```typescript +import axios from 'axios'; + +axios.get('/foo') + .then(response => console.log(response)) + .catch(error => console.log(error)); +``` + +#### `agent` Config Option + +The `agent` config option has been replaced with two new options: `httpAgent` and `httpsAgent`. Please use them instead. + +```js +{ + // Define a custom agent for HTTP + httpAgent: new http.Agent({ keepAlive: true }), + // Define a custom agent for HTTPS + httpsAgent: new https.Agent({ keepAlive: true }) +} +``` + +#### `progress` Config Option + +The `progress` config option has been replaced with the `onUploadProgress` and `onDownloadProgress` options. + +```js +{ + // Define a handler for upload progress events + onUploadProgress: function (progressEvent) { + // ... + }, + + // Define a handler for download progress events + onDownloadProgress: function (progressEvent) { + // ... + } +} +``` + +### 0.12.x -> 0.13.0 + +The `0.13.0` release contains several changes to custom adapters and error handling. + +#### Error Handling + +Previous to this release an error could either be a server response with bad status code or an actual `Error`. With this release Promise will always reject with an `Error`. In the case that a response was received, the `Error` will also include the response. + +```js +axios.get('/user/12345') + .catch((error) => { + console.log(error.message); + console.log(error.code); // Not always specified + console.log(error.config); // The config that was used to make the request + console.log(error.response); // Only available if response was received from the server + }); +``` + +#### Request Adapters + +This release changes a few things about how request adapters work. Please take note if you are using your own custom adapter. + +1. Response transformer is now called outside of adapter. +2. Request adapter returns a `Promise`. + +This means that you no longer need to invoke `transformData` on response data. You will also no longer receive `resolve` and `reject` as arguments in your adapter. + +Previous code: + +```js +function myAdapter(resolve, reject, config) { + var response = { + data: transformData( + responseData, + responseHeaders, + config.transformResponse + ), + status: request.status, + statusText: request.statusText, + headers: responseHeaders + }; + settle(resolve, reject, response); +} +``` + +New code: + +```js +function myAdapter(config) { + return new Promise(function (resolve, reject) { + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders + }; + settle(resolve, reject, response); + }); +} +``` + +See the related commits for more details: +- [Response transformers](https://github.com/axios/axios/commit/10eb23865101f9347570552c04e9d6211376e25e) +- [Request adapter Promise](https://github.com/axios/axios/commit/157efd5615890301824e3121cc6c9d2f9b21f94a) + +### 0.5.x -> 0.6.0 + +The `0.6.0` release contains mostly bug fixes, but there are a couple things to be aware of when upgrading. + +#### ES6 Promise Polyfill + +Up until the `0.6.0` release ES6 `Promise` was being polyfilled using [es6-promise](https://github.com/jakearchibald/es6-promise). With this release, the polyfill has been removed, and you will need to supply it yourself if your environment needs it. + +```js +require('es6-promise').polyfill(); +var axios = require('axios'); +``` + +This will polyfill the global environment, and only needs to be done once. + +#### `axios.success`/`axios.error` + +The `success`, and `error` aliases were deprecated in [0.4.0](https://github.com/axios/axios/blob/master/CHANGELOG.md#040-oct-03-2014). As of this release they have been removed entirely. Instead please use `axios.then`, and `axios.catch` respectively. + +```js +axios.get('some/url') + .then(function (res) { + /* ... */ + }) + .catch(function (err) { + /* ... */ + }); +``` + +#### UMD + +Previous versions of axios shipped with an AMD, CommonJS, and Global build. This has all been rolled into a single UMD build. + +```js +// AMD +require(['bower_components/axios/dist/axios'], function (axios) { + /* ... */ +}); + +// CommonJS +var axios = require('axios/dist/axios'); +``` diff --git a/node_modules/axios/dist/axios.js b/node_modules/axios/dist/axios.js new file mode 100644 index 0000000..f253910 --- /dev/null +++ b/node_modules/axios/dist/axios.js @@ -0,0 +1,2193 @@ +/* axios v0.21.4 | (c) 2021 by Matt Zabriskie */ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["axios"] = factory(); + else + root["axios"] = factory(); +})(window, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./index.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./index.js": +/*!******************!*\ + !*** ./index.js ***! + \******************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = __webpack_require__(/*! ./lib/axios */ "./lib/axios.js"); + +/***/ }), + +/***/ "./lib/adapters/xhr.js": +/*!*****************************!*\ + !*** ./lib/adapters/xhr.js ***! + \*****************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); +var settle = __webpack_require__(/*! ./../core/settle */ "./lib/core/settle.js"); +var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./lib/helpers/cookies.js"); +var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./lib/helpers/buildURL.js"); +var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./lib/core/buildFullPath.js"); +var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./lib/helpers/parseHeaders.js"); +var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./lib/helpers/isURLSameOrigin.js"); +var createError = __webpack_require__(/*! ../core/createError */ "./lib/core/createError.js"); + +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; + var responseType = config.responseType; + + if (utils.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it + } + + var request = new XMLHttpRequest(); + + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } + + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + + // Set the request timeout in MS + request.timeout = config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + + settle(resolve, reject, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(createError('Request aborted', config, 'ECONNABORTED', request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(createError('Network Error', config, null, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError( + timeoutErrorMessage, + config, + config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', + request)); + + // Clean up request + request = null; + }; + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; + + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } + } + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = config.responseType; + } + + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } + + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } + + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; + } + + request.abort(); + reject(cancel); + // Clean up request + request = null; + }); + } + + if (!requestData) { + requestData = null; + } + + // Send the request + request.send(requestData); + }); +}; + + +/***/ }), + +/***/ "./lib/axios.js": +/*!**********************!*\ + !*** ./lib/axios.js ***! + \**********************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./utils */ "./lib/utils.js"); +var bind = __webpack_require__(/*! ./helpers/bind */ "./lib/helpers/bind.js"); +var Axios = __webpack_require__(/*! ./core/Axios */ "./lib/core/Axios.js"); +var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./lib/core/mergeConfig.js"); +var defaults = __webpack_require__(/*! ./defaults */ "./lib/defaults.js"); + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); + + // Copy context to instance + utils.extend(instance, context); + + return instance; +} + +// Create the default instance to be exported +var axios = createInstance(defaults); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios; + +// Factory for creating new instances +axios.create = function create(instanceConfig) { + return createInstance(mergeConfig(axios.defaults, instanceConfig)); +}; + +// Expose Cancel & CancelToken +axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./lib/cancel/Cancel.js"); +axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./lib/cancel/CancelToken.js"); +axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./lib/cancel/isCancel.js"); + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = __webpack_require__(/*! ./helpers/spread */ "./lib/helpers/spread.js"); + +// Expose isAxiosError +axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./lib/helpers/isAxiosError.js"); + +module.exports = axios; + +// Allow use of default import syntax in TypeScript +module.exports.default = axios; + + +/***/ }), + +/***/ "./lib/cancel/Cancel.js": +/*!******************************!*\ + !*** ./lib/cancel/Cancel.js ***! + \******************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; +} + +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; + +Cancel.prototype.__CANCEL__ = true; + +module.exports = Cancel; + + +/***/ }), + +/***/ "./lib/cancel/CancelToken.js": +/*!***********************************!*\ + !*** ./lib/cancel/CancelToken.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Cancel = __webpack_require__(/*! ./Cancel */ "./lib/cancel/Cancel.js"); + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new Cancel(message); + resolvePromise(token.reason); + }); +} + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; + +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; + +module.exports = CancelToken; + + +/***/ }), + +/***/ "./lib/cancel/isCancel.js": +/*!********************************!*\ + !*** ./lib/cancel/isCancel.js ***! + \********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; + + +/***/ }), + +/***/ "./lib/core/Axios.js": +/*!***************************!*\ + !*** ./lib/core/Axios.js ***! + \***************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); +var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./lib/helpers/buildURL.js"); +var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./lib/core/InterceptorManager.js"); +var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./lib/core/dispatchRequest.js"); +var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./lib/core/mergeConfig.js"); +var validator = __webpack_require__(/*! ../helpers/validator */ "./lib/helpers/validator.js"); + +var validators = validator.validators; +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} + +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; + } + + config = mergeConfig(this.defaults, config); + + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } + + var transitional = config.transitional; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'), + forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'), + clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0') + }, false); + } + + // filter out skipped interceptors + var requestInterceptorChain = []; + var synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + var responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + var promise; + + if (!synchronousRequestInterceptors) { + var chain = [dispatchRequest, undefined]; + + Array.prototype.unshift.apply(chain, requestInterceptorChain); + chain = chain.concat(responseInterceptorChain); + + promise = Promise.resolve(config); + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; + } + + + var newConfig = config; + while (requestInterceptorChain.length) { + var onFulfilled = requestInterceptorChain.shift(); + var onRejected = requestInterceptorChain.shift(); + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected(error); + break; + } + } + + try { + promise = dispatchRequest(newConfig); + } catch (error) { + return Promise.reject(error); + } + + while (responseInterceptorChain.length) { + promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); + } + + return promise; +}; + +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); +}; + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: data + })); + }; +}); + +module.exports = Axios; + + +/***/ }), + +/***/ "./lib/core/InterceptorManager.js": +/*!****************************************!*\ + !*** ./lib/core/InterceptorManager.js ***! + \****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); + +function InterceptorManager() { + this.handlers = []; +} + +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; +}; + +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; + +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; + +module.exports = InterceptorManager; + + +/***/ }), + +/***/ "./lib/core/buildFullPath.js": +/*!***********************************!*\ + !*** ./lib/core/buildFullPath.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./lib/helpers/isAbsoluteURL.js"); +var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./lib/helpers/combineURLs.js"); + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +}; + + +/***/ }), + +/***/ "./lib/core/createError.js": +/*!*********************************!*\ + !*** ./lib/core/createError.js ***! + \*********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var enhanceError = __webpack_require__(/*! ./enhanceError */ "./lib/core/enhanceError.js"); + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +module.exports = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError(error, config, code, request, response); +}; + + +/***/ }), + +/***/ "./lib/core/dispatchRequest.js": +/*!*************************************!*\ + !*** ./lib/core/dispatchRequest.js ***! + \*************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); +var transformData = __webpack_require__(/*! ./transformData */ "./lib/core/transformData.js"); +var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./lib/cancel/isCancel.js"); +var defaults = __webpack_require__(/*! ../defaults */ "./lib/defaults.js"); + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); + + // Ensure headers exist + config.headers = config.headers || {}; + + // Transform request data + config.data = transformData.call( + config, + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); + + var adapter = config.adapter || defaults.adapter; + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); +}; + + +/***/ }), + +/***/ "./lib/core/enhanceError.js": +/*!**********************************!*\ + !*** ./lib/core/enhanceError.js ***! + \**********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Update an Error with the specified config, error code, and response. + * + * @param {Error} error The error to update. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The error. + */ +module.exports = function enhanceError(error, config, code, request, response) { + error.config = config; + if (code) { + error.code = code; + } + + error.request = request; + error.response = response; + error.isAxiosError = true; + + error.toJSON = function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code + }; + }; + return error; +}; + + +/***/ }), + +/***/ "./lib/core/mergeConfig.js": +/*!*********************************!*\ + !*** ./lib/core/mergeConfig.js ***! + \*********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js"); + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + + var valueFromConfig2Keys = ['url', 'method', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; + var defaultToConfig2Keys = [ + 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', + 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' + ]; + var directMergeKeys = ['validateStatus']; + + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + } + + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } + }); + + utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); + + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + utils.forEach(directMergeKeys, function merge(prop) { + if (prop in config2) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys) + .concat(directMergeKeys); + + var otherKeys = Object + .keys(config1) + .concat(Object.keys(config2)) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); + + utils.forEach(otherKeys, mergeDeepProperties); + + return config; +}; + + +/***/ }), + +/***/ "./lib/core/settle.js": +/*!****************************!*\ + !*** ./lib/core/settle.js ***! + \****************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var createError = __webpack_require__(/*! ./createError */ "./lib/core/createError.js"); + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + */ +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(createError( + 'Request failed with status code ' + response.status, + response.config, + null, + response.request, + response + )); + } +}; + + +/***/ }), + +/***/ "./lib/core/transformData.js": +/*!***********************************!*\ + !*** ./lib/core/transformData.js ***! + \***********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); +var defaults = __webpack_require__(/*! ./../defaults */ "./lib/defaults.js"); + +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +module.exports = function transformData(data, headers, fns) { + var context = this || defaults; + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn.call(context, data, headers); + }); + + return data; +}; + + +/***/ }), + +/***/ "./lib/defaults.js": +/*!*************************!*\ + !*** ./lib/defaults.js ***! + \*************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./utils */ "./lib/utils.js"); +var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./lib/helpers/normalizeHeaderName.js"); +var enhanceError = __webpack_require__(/*! ./core/enhanceError */ "./lib/core/enhanceError.js"); + +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; + +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } +} + +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = __webpack_require__(/*! ./adapters/xhr */ "./lib/adapters/xhr.js"); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = __webpack_require__(/*! ./adapters/http */ "./lib/adapters/xhr.js"); + } + return adapter; +} + +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +var defaults = { + + transitional: { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }, + + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { + setContentTypeIfUnset(headers, 'application/json'); + return stringifySafely(data); + } + return data; + }], + + transformResponse: [function transformResponse(data) { + var transitional = this.transitional; + var silentJSONParsing = transitional && transitional.silentJSONParsing; + var forcedJSONParsing = transitional && transitional.forcedJSONParsing; + var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; + + if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw enhanceError(e, this, 'E_JSON_PARSE'); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } +}; + +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } +}; + +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); + +module.exports = defaults; + + +/***/ }), + +/***/ "./lib/helpers/bind.js": +/*!*****************************!*\ + !*** ./lib/helpers/bind.js ***! + \*****************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; + + +/***/ }), + +/***/ "./lib/helpers/buildURL.js": +/*!*********************************!*\ + !*** ./lib/helpers/buildURL.js ***! + \*********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); + +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; + + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } + + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } + + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); + }); + }); + + serializedParams = parts.join('&'); + } + + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +}; + + +/***/ }), + +/***/ "./lib/helpers/combineURLs.js": +/*!************************************!*\ + !*** ./lib/helpers/combineURLs.js ***! + \************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; + + +/***/ }), + +/***/ "./lib/helpers/cookies.js": +/*!********************************!*\ + !*** ./lib/helpers/cookies.js ***! + \********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); + +module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); + + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } + + if (utils.isString(path)) { + cookie.push('path=' + path); + } + + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } + + if (secure === true) { + cookie.push('secure'); + } + + document.cookie = cookie.join('; '); + }, + + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : + + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() +); + + +/***/ }), + +/***/ "./lib/helpers/isAbsoluteURL.js": +/*!**************************************!*\ + !*** ./lib/helpers/isAbsoluteURL.js ***! + \**************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); +}; + + +/***/ }), + +/***/ "./lib/helpers/isAxiosError.js": +/*!*************************************!*\ + !*** ./lib/helpers/isAxiosError.js ***! + \*************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return (typeof payload === 'object') && (payload.isAxiosError === true); +}; + + +/***/ }), + +/***/ "./lib/helpers/isURLSameOrigin.js": +/*!****************************************!*\ + !*** ./lib/helpers/isURLSameOrigin.js ***! + \****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); + +module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; + + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; + + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } + + originURL = resolveURL(window.location.href); + + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : + + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() +); + + +/***/ }), + +/***/ "./lib/helpers/normalizeHeaderName.js": +/*!********************************************!*\ + !*** ./lib/helpers/normalizeHeaderName.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js"); + +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; + } + }); +}; + + +/***/ }), + +/***/ "./lib/helpers/parseHeaders.js": +/*!*************************************!*\ + !*** ./lib/helpers/parseHeaders.js ***! + \*************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js"); + +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; + + if (!headers) { return parsed; } + + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); + + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + }); + + return parsed; +}; + + +/***/ }), + +/***/ "./lib/helpers/spread.js": +/*!*******************************!*\ + !*** ./lib/helpers/spread.js ***! + \*******************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; + + +/***/ }), + +/***/ "./lib/helpers/validator.js": +/*!**********************************!*\ + !*** ./lib/helpers/validator.js ***! + \**********************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var pkg = __webpack_require__(/*! ./../../package.json */ "./package.json"); + +var validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +var deprecatedWarnings = {}; +var currentVerArr = pkg.version.split('.'); + +/** + * Compare package versions + * @param {string} version + * @param {string?} thanVersion + * @returns {boolean} + */ +function isOlderVersion(version, thanVersion) { + var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr; + var destVer = version.split('.'); + for (var i = 0; i < 3; i++) { + if (pkgVersionArr[i] > destVer[i]) { + return true; + } else if (pkgVersionArr[i] < destVer[i]) { + return false; + } + } + return false; +} + +/** + * Transitional option validator + * @param {function|boolean?} validator + * @param {string?} version + * @param {string} message + * @returns {function} + */ +validators.transitional = function transitional(validator, version, message) { + var isDeprecated = version && isOlderVersion(version); + + function formatMessage(opt, desc) { + return '[Axios v' + pkg.version + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return function(value, opt, opts) { + if (validator === false) { + throw new Error(formatMessage(opt, ' has been removed in ' + version)); + } + + if (isDeprecated && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +/** + * Assert object's properties type + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + var keys = Object.keys(options); + var i = keys.length; + while (i-- > 0) { + var opt = keys[i]; + var validator = schema[opt]; + if (validator) { + var value = options[opt]; + var result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new TypeError('option ' + opt + ' must be ' + result); + } + continue; + } + if (allowUnknown !== true) { + throw Error('Unknown option ' + opt); + } + } +} + +module.exports = { + isOlderVersion: isOlderVersion, + assertOptions: assertOptions, + validators: validators +}; + + +/***/ }), + +/***/ "./lib/utils.js": +/*!**********************!*\ + !*** ./lib/utils.js ***! + \**********************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var bind = __webpack_require__(/*! ./helpers/bind */ "./lib/helpers/bind.js"); + +// utils is a library of generic helper functions non-specific to axios + +var toString = Object.prototype.toString; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return toString.call(val) === '[object Array]'; +} + +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} + +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; +} + +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); +} + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} + +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} + +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} + +/** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ +function isPlainObject(val) { + if (toString.call(val) !== '[object Object]') { + return false; + } + + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; +} + +/** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +function isDate(val) { + return toString.call(val) === '[object Date]'; +} + +/** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +function isFile(val) { + return toString.call(val) === '[object File]'; +} + +/** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +function isBlob(val) { + return toString.call(val) === '[object Blob]'; +} + +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} + +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} + +/** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; +} + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); +} + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } +} + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * @return {string} content value without BOM + */ +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM +}; + + +/***/ }), + +/***/ "./package.json": +/*!**********************!*\ + !*** ./package.json ***! + \**********************/ +/*! exports provided: name, version, description, main, scripts, repository, keywords, author, license, bugs, homepage, devDependencies, browser, jsdelivr, unpkg, typings, dependencies, bundlesize, default */ +/***/ (function(module) { + +module.exports = JSON.parse("{\"name\":\"axios\",\"version\":\"0.21.4\",\"description\":\"Promise based HTTP client for the browser and node.js\",\"main\":\"index.js\",\"scripts\":{\"test\":\"grunt test\",\"start\":\"node ./sandbox/server.js\",\"build\":\"NODE_ENV=production grunt build\",\"preversion\":\"npm test\",\"version\":\"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json\",\"postversion\":\"git push && git push --tags\",\"examples\":\"node ./examples/server.js\",\"coveralls\":\"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js\",\"fix\":\"eslint --fix lib/**/*.js\"},\"repository\":{\"type\":\"git\",\"url\":\"https://github.com/axios/axios.git\"},\"keywords\":[\"xhr\",\"http\",\"ajax\",\"promise\",\"node\"],\"author\":\"Matt Zabriskie\",\"license\":\"MIT\",\"bugs\":{\"url\":\"https://github.com/axios/axios/issues\"},\"homepage\":\"https://axios-http.com\",\"devDependencies\":{\"coveralls\":\"^3.0.0\",\"es6-promise\":\"^4.2.4\",\"grunt\":\"^1.3.0\",\"grunt-banner\":\"^0.6.0\",\"grunt-cli\":\"^1.2.0\",\"grunt-contrib-clean\":\"^1.1.0\",\"grunt-contrib-watch\":\"^1.0.0\",\"grunt-eslint\":\"^23.0.0\",\"grunt-karma\":\"^4.0.0\",\"grunt-mocha-test\":\"^0.13.3\",\"grunt-ts\":\"^6.0.0-beta.19\",\"grunt-webpack\":\"^4.0.2\",\"istanbul-instrumenter-loader\":\"^1.0.0\",\"jasmine-core\":\"^2.4.1\",\"karma\":\"^6.3.2\",\"karma-chrome-launcher\":\"^3.1.0\",\"karma-firefox-launcher\":\"^2.1.0\",\"karma-jasmine\":\"^1.1.1\",\"karma-jasmine-ajax\":\"^0.1.13\",\"karma-safari-launcher\":\"^1.0.0\",\"karma-sauce-launcher\":\"^4.3.6\",\"karma-sinon\":\"^1.0.5\",\"karma-sourcemap-loader\":\"^0.3.8\",\"karma-webpack\":\"^4.0.2\",\"load-grunt-tasks\":\"^3.5.2\",\"minimist\":\"^1.2.0\",\"mocha\":\"^8.2.1\",\"sinon\":\"^4.5.0\",\"terser-webpack-plugin\":\"^4.2.3\",\"typescript\":\"^4.0.5\",\"url-search-params\":\"^0.10.0\",\"webpack\":\"^4.44.2\",\"webpack-dev-server\":\"^3.11.0\"},\"browser\":{\"./lib/adapters/http.js\":\"./lib/adapters/xhr.js\"},\"jsdelivr\":\"dist/axios.min.js\",\"unpkg\":\"dist/axios.min.js\",\"typings\":\"./index.d.ts\",\"dependencies\":{\"follow-redirects\":\"^1.14.0\"},\"bundlesize\":[{\"path\":\"./dist/axios.min.js\",\"threshold\":\"5kB\"}]}"); + +/***/ }) + +/******/ }); +}); +//# sourceMappingURL=axios.map \ No newline at end of file diff --git a/node_modules/axios/dist/axios.map b/node_modules/axios/dist/axios.map new file mode 100644 index 0000000..4aadb21 --- /dev/null +++ b/node_modules/axios/dist/axios.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack://axios/webpack/universalModuleDefinition","webpack://axios/webpack/bootstrap","webpack://axios/./index.js","webpack://axios/./lib/adapters/xhr.js","webpack://axios/./lib/axios.js","webpack://axios/./lib/cancel/Cancel.js","webpack://axios/./lib/cancel/CancelToken.js","webpack://axios/./lib/cancel/isCancel.js","webpack://axios/./lib/core/Axios.js","webpack://axios/./lib/core/InterceptorManager.js","webpack://axios/./lib/core/buildFullPath.js","webpack://axios/./lib/core/createError.js","webpack://axios/./lib/core/dispatchRequest.js","webpack://axios/./lib/core/enhanceError.js","webpack://axios/./lib/core/mergeConfig.js","webpack://axios/./lib/core/settle.js","webpack://axios/./lib/core/transformData.js","webpack://axios/./lib/defaults.js","webpack://axios/./lib/helpers/bind.js","webpack://axios/./lib/helpers/buildURL.js","webpack://axios/./lib/helpers/combineURLs.js","webpack://axios/./lib/helpers/cookies.js","webpack://axios/./lib/helpers/isAbsoluteURL.js","webpack://axios/./lib/helpers/isAxiosError.js","webpack://axios/./lib/helpers/isURLSameOrigin.js","webpack://axios/./lib/helpers/normalizeHeaderName.js","webpack://axios/./lib/helpers/parseHeaders.js","webpack://axios/./lib/helpers/spread.js","webpack://axios/./lib/helpers/validator.js","webpack://axios/./lib/utils.js"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AACD,O;QCVA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;;QAEA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;;;QAGA;QACA;;QAEA;QACA;;QAEA;QACA;QACA;QACA,0CAA0C,gCAAgC;QAC1E;QACA;;QAEA;QACA;QACA;QACA,wDAAwD,kBAAkB;QAC1E;QACA,iDAAiD,cAAc;QAC/D;;QAEA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA,yCAAyC,iCAAiC;QAC1E,gHAAgH,mBAAmB,EAAE;QACrI;QACA;;QAEA;QACA;QACA;QACA,2BAA2B,0BAA0B,EAAE;QACvD,iCAAiC,eAAe;QAChD;QACA;QACA;;QAEA;QACA,sDAAsD,+DAA+D;;QAErH;QACA;;;QAGA;QACA;;;;;;;;;;;;AClFA,iBAAiB,mBAAO,CAAC,mCAAa,E;;;;;;;;;;;;ACAzB;;AAEb,YAAY,mBAAO,CAAC,kCAAY;AAChC,aAAa,mBAAO,CAAC,8CAAkB;AACvC,cAAc,mBAAO,CAAC,sDAAsB;AAC5C,eAAe,mBAAO,CAAC,wDAAuB;AAC9C,oBAAoB,mBAAO,CAAC,0DAAuB;AACnD,mBAAmB,mBAAO,CAAC,gEAA2B;AACtD,sBAAsB,mBAAO,CAAC,sEAA8B;AAC5D,kBAAkB,mBAAO,CAAC,sDAAqB;;AAE/C;AACA;AACA;AACA;AACA;;AAEA;AACA,4CAA4C;AAC5C;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,OAAO;AACP;;AAEA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;;;;;;;;;;;;AC5La;;AAEb,YAAY,mBAAO,CAAC,+BAAS;AAC7B,WAAW,mBAAO,CAAC,6CAAgB;AACnC,YAAY,mBAAO,CAAC,yCAAc;AAClC,kBAAkB,mBAAO,CAAC,qDAAoB;AAC9C,eAAe,mBAAO,CAAC,qCAAY;;AAEnC;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,MAAM;AAClB;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA,eAAe,mBAAO,CAAC,+CAAiB;AACxC,oBAAoB,mBAAO,CAAC,yDAAsB;AAClD,iBAAiB,mBAAO,CAAC,mDAAmB;;AAE5C;AACA;AACA;AACA;AACA,eAAe,mBAAO,CAAC,iDAAkB;;AAEzC;AACA,qBAAqB,mBAAO,CAAC,6DAAwB;;AAErD;;AAEA;AACA;;;;;;;;;;;;;ACvDa;;AAEb;AACA;AACA;AACA;AACA,WAAW,QAAQ;AACnB;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;;;;;;;;;;;;;AClBa;;AAEb,aAAa,mBAAO,CAAC,wCAAU;;AAE/B;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;;AAEA;;;;;;;;;;;;;ACxDa;;AAEb;AACA;AACA;;;;;;;;;;;;;ACJa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;AAChC,eAAe,mBAAO,CAAC,sDAAqB;AAC5C,yBAAyB,mBAAO,CAAC,8DAAsB;AACvD,sBAAsB,mBAAO,CAAC,wDAAmB;AACjD,kBAAkB,mBAAO,CAAC,gDAAe;AACzC,gBAAgB,mBAAO,CAAC,wDAAsB;;AAE9C;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA,GAAG;;AAEH;AACA;AACA;AACA,GAAG;;AAEH;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,gDAAgD;AAChD;AACA;AACA,yBAAyB;AACzB,KAAK;AACL;AACA,CAAC;;AAED;AACA;AACA;AACA,gDAAgD;AAChD;AACA;AACA;AACA,KAAK;AACL;AACA,CAAC;;AAED;;;;;;;;;;;;;ACnJa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB;AACA,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;AAEA;;;;;;;;;;;;;ACrDa;;AAEb,oBAAoB,mBAAO,CAAC,gEAA0B;AACtD,kBAAkB,mBAAO,CAAC,4DAAwB;;AAElD;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACnBa;;AAEb,mBAAmB,mBAAO,CAAC,kDAAgB;;AAE3C;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,MAAM;AACnB;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACjBa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;AAChC,oBAAoB,mBAAO,CAAC,oDAAiB;AAC7C,eAAe,mBAAO,CAAC,oDAAoB;AAC3C,eAAe,mBAAO,CAAC,sCAAa;;AAEpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,+BAA+B;AAC/B,uCAAuC;AACvC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;AACH;;;;;;;;;;;;;ACjFa;;AAEb;AACA;AACA;AACA,WAAW,MAAM;AACjB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,MAAM;AACnB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACzCa;;AAEb,YAAY,mBAAO,CAAC,gCAAU;;AAE9B;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL,2BAA2B;AAC3B,KAAK;AACL;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,GAAG;;AAEH;;AAEA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;;AAEA;AACA;;;;;;;;;;;;;ACtFa;;AAEb,kBAAkB,mBAAO,CAAC,gDAAe;;AAEzC;AACA;AACA;AACA,WAAW,SAAS;AACpB,WAAW,SAAS;AACpB,WAAW,OAAO;AAClB;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACxBa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;AAChC,eAAe,mBAAO,CAAC,wCAAe;;AAEtC;AACA;AACA;AACA,WAAW,cAAc;AACzB,WAAW,MAAM;AACjB,WAAW,eAAe;AAC1B,aAAa,EAAE;AACf;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;;;;;;;;;;;;;ACrBa;;AAEb,YAAY,mBAAO,CAAC,+BAAS;AAC7B,0BAA0B,mBAAO,CAAC,2EAA+B;AACjE,mBAAmB,mBAAO,CAAC,uDAAqB;;AAEhD;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA,cAAc,mBAAO,CAAC,6CAAgB;AACtC,GAAG;AACH;AACA,cAAc,mBAAO,CAAC,8CAAiB;AACvC;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA,GAAG;;AAEH;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wEAAwE;AACxE;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA,GAAG;;AAEH;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,CAAC;;AAED;AACA;AACA,CAAC;;AAED;;;;;;;;;;;;;ACrIa;;AAEb;AACA;AACA;AACA,mBAAmB,iBAAiB;AACpC;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACVa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,GAAG;AACH;AACA,GAAG;AACH;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA,OAAO;AACP;AACA;;AAEA;AACA;AACA;AACA,SAAS;AACT;AACA;AACA;AACA,OAAO;AACP,KAAK;;AAEL;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;ACrEa;;AAEb;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACba;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,0CAA0C;AAC1C,SAAS;;AAET;AACA,4DAA4D,wBAAwB;AACpF;AACA,SAAS;;AAET;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA,kCAAkC;AAClC,+BAA+B,aAAa,EAAE;AAC9C;AACA;AACA,KAAK;AACL;;;;;;;;;;;;;ACpDa;;AAEb;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACba;;AAEb;AACA;AACA;AACA,WAAW,EAAE;AACb,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;;;;;;;;;;;;ACVa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,cAAc,OAAO;AACrB,gBAAgB;AAChB;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA,cAAc,OAAO;AACrB,gBAAgB,QAAQ;AACxB;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;;AAEL;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;;;;;;;;;;;;;ACnEa;;AAEb,YAAY,mBAAO,CAAC,gCAAU;;AAE9B;AACA;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;;;;;;;;;;;;;ACXa;;AAEb,YAAY,mBAAO,CAAC,kCAAY;;AAEhC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA,iBAAiB,eAAe;;AAEhC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;AACP;AACA;AACA;AACA,GAAG;;AAEH;AACA;;;;;;;;;;;;;ACpDa;;AAEb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,+BAA+B;AAC/B;AACA;AACA,WAAW,SAAS;AACpB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;AC1Ba;;AAEb,UAAU,mBAAO,CAAC,4CAAsB;;AAExC;;AAEA;AACA;AACA;AACA;AACA;AACA,CAAC;;AAED;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,QAAQ;AACnB,aAAa;AACb;AACA;AACA;AACA;AACA,iBAAiB,OAAO;AACxB;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,WAAW,kBAAkB;AAC7B,WAAW,QAAQ;AACnB,WAAW,OAAO;AAClB,aAAa;AACb;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,SAAS;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;ACxGa;;AAEb,WAAW,mBAAO,CAAC,6CAAgB;;AAEnC;;AAEA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,QAAQ;AACpB;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,QAAQ;AACrB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,WAAW,aAAa;AACxB,WAAW,SAAS;AACpB;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,mCAAmC,OAAO;AAC1C;AACA;AACA,GAAG;AACH;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uBAAuB,SAAS,GAAG,SAAS;AAC5C,2BAA2B;AAC3B;AACA;AACA,WAAW,OAAO;AAClB,aAAa,OAAO;AACpB;AACA;AACA;AACA;AACA;AACA;AACA,KAAK;AACL,4BAA4B;AAC5B,KAAK;AACL;AACA,KAAK;AACL;AACA;AACA;;AAEA,uCAAuC,OAAO;AAC9C;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA,KAAK;AACL;AACA;AACA,GAAG;AACH;AACA;;AAEA;AACA;AACA;AACA,WAAW,OAAO;AAClB,YAAY,OAAO;AACnB;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"axios.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"axios\"] = factory();\n\telse\n\t\troot[\"axios\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = \"./index.js\");\n","module.exports = require('./lib/axios');","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar createError = require('../core/createError');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(resolve, reject, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(\n timeoutErrorMessage,\n config,\n config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken) {\n // Handle cancellation\n config.cancelToken.promise.then(function onCanceled(cancel) {\n if (!request) {\n return;\n }\n\n request.abort();\n reject(cancel);\n // Clean up request\n request = null;\n });\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Factory for creating new instances\naxios.create = function create(instanceConfig) {\n return createInstance(mergeConfig(axios.defaults, instanceConfig));\n};\n\n// Expose Cancel & CancelToken\naxios.Cancel = require('./cancel/Cancel');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n","'use strict';\n\nvar Cancel = require('./Cancel');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = arguments[1] || {};\n config.url = arguments[0];\n } else {\n config = config || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'),\n forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'),\n clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0')\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\nvar enhanceError = require('./enhanceError');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code\n };\n };\n return error;\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n var valueFromConfig2Keys = ['url', 'method', 'data'];\n var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];\n var defaultToConfig2Keys = [\n 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',\n 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',\n 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',\n 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',\n 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'\n ];\n var directMergeKeys = ['validateStatus'];\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n }\n\n utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n }\n });\n\n utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);\n\n utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n utils.forEach(directMergeKeys, function merge(prop) {\n if (prop in config2) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n var axiosKeys = valueFromConfig2Keys\n .concat(mergeDeepPropertiesKeys)\n .concat(defaultToConfig2Keys)\n .concat(directMergeKeys);\n\n var otherKeys = Object\n .keys(config1)\n .concat(Object.keys(config2))\n .filter(function filterAxiosKeys(key) {\n return axiosKeys.indexOf(key) === -1;\n });\n\n utils.forEach(otherKeys, mergeDeepProperties);\n\n return config;\n};\n","'use strict';\n\nvar createError = require('./createError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('./../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\nvar enhanceError = require('./core/enhanceError');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n },\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw enhanceError(e, this, 'E_JSON_PARSE');\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n }\n};\n\ndefaults.headers = {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d\\+\\-\\.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return (typeof payload === 'object') && (payload.isAxiosError === true);\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\nvar pkg = require('./../../package.json');\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\nvar currentVerArr = pkg.version.split('.');\n\n/**\n * Compare package versions\n * @param {string} version\n * @param {string?} thanVersion\n * @returns {boolean}\n */\nfunction isOlderVersion(version, thanVersion) {\n var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr;\n var destVer = version.split('.');\n for (var i = 0; i < 3; i++) {\n if (pkgVersionArr[i] > destVer[i]) {\n return true;\n } else if (pkgVersionArr[i] < destVer[i]) {\n return false;\n }\n }\n return false;\n}\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator\n * @param {string?} version\n * @param {string} message\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n var isDeprecated = version && isOlderVersion(version);\n\n function formatMessage(opt, desc) {\n return '[Axios v' + pkg.version + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new Error(formatMessage(opt, ' has been removed in ' + version));\n }\n\n if (isDeprecated && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new TypeError('option ' + opt + ' must be ' + result);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw Error('Unknown option ' + opt);\n }\n }\n}\n\nmodule.exports = {\n isOlderVersion: isOlderVersion,\n assertOptions: assertOptions,\n validators: validators\n};\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (toString.call(val) !== '[object Object]') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM\n};\n"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/axios/dist/axios.min.js b/node_modules/axios/dist/axios.min.js new file mode 100644 index 0000000..d5b138a --- /dev/null +++ b/node_modules/axios/dist/axios.min.js @@ -0,0 +1,3 @@ +/* axios v0.21.4 | (c) 2021 by Matt Zabriskie */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=10)}([function(e,t,r){"use strict";var n=r(2),o=Object.prototype.toString;function i(e){return"[object Array]"===o.call(e)}function s(e){return void 0===e}function a(e){return null!==e&&"object"==typeof e}function u(e){if("[object Object]"!==o.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function c(e){return"[object Function]"===o.call(e)}function f(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),i(e))for(var r=0,n=e.length;r=200&&e<300}};c.headers={common:{Accept:"application/json, text/plain, */*"}},n.forEach(["delete","get","head"],(function(e){c.headers[e]={}})),n.forEach(["post","put","patch"],(function(e){c.headers[e]=n.merge(s)})),e.exports=c},function(e,t,r){"use strict";e.exports=function(e,t){return function(){for(var r=new Array(arguments.length),n=0;n=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([r]):s[t]?s[t]+", "+r:r}})),s):s}},function(e,t,r){"use strict";var n=r(0);e.exports=n.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function o(e){var n=e;return t&&(r.setAttribute("href",n),n=r.href),r.setAttribute("href",n),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=o(window.location.href),function(t){var r=n.isString(t)?o(t):t;return r.protocol===e.protocol&&r.host===e.host}}():function(){return!0}},function(e,t,r){"use strict";var n=r(25),o={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){o[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var i={},s=n.version.split(".");function a(e,t){for(var r=t?t.split("."):s,n=e.split("."),o=0;o<3;o++){if(r[o]>n[o])return!0;if(r[o]0;){var i=n[o],s=t[i];if(s){var a=e[i],u=void 0===a||s(a,i,e);if(!0!==u)throw new TypeError("option "+i+" must be "+u)}else if(!0!==r)throw Error("Unknown option "+i)}},validators:o}},function(e){e.exports=JSON.parse('{"name":"axios","version":"0.21.4","description":"Promise based HTTP client for the browser and node.js","main":"index.js","scripts":{"test":"grunt test","start":"node ./sandbox/server.js","build":"NODE_ENV=production grunt build","preversion":"npm test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json","postversion":"git push && git push --tags","examples":"node ./examples/server.js","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","fix":"eslint --fix lib/**/*.js"},"repository":{"type":"git","url":"https://github.com/axios/axios.git"},"keywords":["xhr","http","ajax","promise","node"],"author":"Matt Zabriskie","license":"MIT","bugs":{"url":"https://github.com/axios/axios/issues"},"homepage":"https://axios-http.com","devDependencies":{"coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^8.2.1","sinon":"^4.5.0","terser-webpack-plugin":"^4.2.3","typescript":"^4.0.5","url-search-params":"^0.10.0","webpack":"^4.44.2","webpack-dev-server":"^3.11.0"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"jsdelivr":"dist/axios.min.js","unpkg":"dist/axios.min.js","typings":"./index.d.ts","dependencies":{"follow-redirects":"^1.14.0"},"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}]}')},function(e,t,r){"use strict";var n=r(9);function o(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var r=this;e((function(e){r.reason||(r.reason=new n(e),t(r.reason))}))}o.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},o.source=function(){var e;return{token:new o((function(t){e=t})),cancel:e}},e.exports=o},function(e,t,r){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}},function(e,t,r){"use strict";e.exports=function(e){return"object"==typeof e&&!0===e.isAxiosError}}])})); +//# sourceMappingURL=axios.min.map \ No newline at end of file diff --git a/node_modules/axios/dist/axios.min.map b/node_modules/axios/dist/axios.min.map new file mode 100644 index 0000000..468a5ba --- /dev/null +++ b/node_modules/axios/dist/axios.min.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack://axios/webpack/universalModuleDefinition","webpack://axios/webpack/bootstrap","webpack://axios/./lib/utils.js","webpack://axios/./lib/defaults.js","webpack://axios/./lib/helpers/bind.js","webpack://axios/./lib/helpers/buildURL.js","webpack://axios/./lib/core/enhanceError.js","webpack://axios/./lib/adapters/xhr.js","webpack://axios/./lib/core/createError.js","webpack://axios/./lib/cancel/isCancel.js","webpack://axios/./lib/core/mergeConfig.js","webpack://axios/./lib/cancel/Cancel.js","webpack://axios/./index.js","webpack://axios/./lib/axios.js","webpack://axios/./lib/core/Axios.js","webpack://axios/./lib/core/InterceptorManager.js","webpack://axios/./lib/core/dispatchRequest.js","webpack://axios/./lib/core/transformData.js","webpack://axios/./lib/helpers/normalizeHeaderName.js","webpack://axios/./lib/core/settle.js","webpack://axios/./lib/helpers/cookies.js","webpack://axios/./lib/core/buildFullPath.js","webpack://axios/./lib/helpers/isAbsoluteURL.js","webpack://axios/./lib/helpers/combineURLs.js","webpack://axios/./lib/helpers/parseHeaders.js","webpack://axios/./lib/helpers/isURLSameOrigin.js","webpack://axios/./lib/helpers/validator.js","webpack://axios/./lib/cancel/CancelToken.js","webpack://axios/./lib/helpers/spread.js","webpack://axios/./lib/helpers/isAxiosError.js"],"names":["root","factory","exports","module","define","amd","window","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","toString","isArray","val","isUndefined","isObject","isPlainObject","getPrototypeOf","isFunction","forEach","obj","fn","length","isArrayBuffer","isBuffer","constructor","isFormData","FormData","isArrayBufferView","ArrayBuffer","isView","buffer","isString","isNumber","isDate","isFile","isBlob","isStream","pipe","isURLSearchParams","URLSearchParams","isStandardBrowserEnv","navigator","product","document","merge","result","assignValue","slice","arguments","extend","a","b","thisArg","trim","str","replace","stripBOM","content","charCodeAt","utils","normalizeHeaderName","enhanceError","DEFAULT_CONTENT_TYPE","setContentTypeIfUnset","headers","adapter","defaults","transitional","silentJSONParsing","forcedJSONParsing","clarifyTimeoutError","XMLHttpRequest","process","transformRequest","data","rawValue","parser","encoder","JSON","parse","e","stringify","stringifySafely","transformResponse","this","strictJSONParsing","responseType","timeout","xsrfCookieName","xsrfHeaderName","maxContentLength","maxBodyLength","validateStatus","status","common","method","args","Array","apply","encode","encodeURIComponent","url","params","paramsSerializer","serializedParams","parts","v","toISOString","push","join","hashmarkIndex","indexOf","error","config","code","request","response","isAxiosError","toJSON","message","description","number","fileName","lineNumber","columnNumber","stack","settle","cookies","buildURL","buildFullPath","parseHeaders","isURLSameOrigin","createError","Promise","resolve","reject","requestData","requestHeaders","auth","username","password","unescape","Authorization","btoa","fullPath","baseURL","onloadend","responseHeaders","getAllResponseHeaders","responseText","statusText","open","toUpperCase","onreadystatechange","readyState","responseURL","setTimeout","onabort","onerror","ontimeout","timeoutErrorMessage","xsrfValue","withCredentials","read","undefined","toLowerCase","setRequestHeader","onDownloadProgress","addEventListener","onUploadProgress","upload","cancelToken","promise","then","cancel","abort","send","Error","__CANCEL__","config1","config2","valueFromConfig2Keys","mergeDeepPropertiesKeys","defaultToConfig2Keys","directMergeKeys","getMergedValue","target","source","mergeDeepProperties","prop","axiosKeys","concat","otherKeys","keys","filter","Cancel","Axios","mergeConfig","createInstance","defaultConfig","context","instance","axios","instanceConfig","CancelToken","isCancel","all","promises","spread","default","InterceptorManager","dispatchRequest","validator","validators","interceptors","assertOptions","boolean","requestInterceptorChain","synchronousRequestInterceptors","interceptor","runWhen","synchronous","unshift","fulfilled","rejected","responseInterceptorChain","chain","shift","newConfig","onFulfilled","onRejected","getUri","handlers","use","options","eject","id","h","transformData","throwIfCancellationRequested","throwIfRequested","reason","fns","normalizedName","write","expires","path","domain","secure","cookie","Date","toGMTString","match","RegExp","decodeURIComponent","remove","now","isAbsoluteURL","combineURLs","requestedURL","test","relativeURL","ignoreDuplicateOf","parsed","split","line","substr","originURL","msie","userAgent","urlParsingNode","createElement","resolveURL","href","setAttribute","protocol","host","search","hash","hostname","port","pathname","charAt","location","requestURL","pkg","type","thing","deprecatedWarnings","currentVerArr","version","isOlderVersion","thanVersion","pkgVersionArr","destVer","isDeprecated","formatMessage","opt","desc","opts","console","warn","schema","allowUnknown","TypeError","executor","resolvePromise","token","callback","arr","payload"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAe,MAAID,IAEnBD,EAAY,MAAIC,IARlB,CASGK,QAAQ,WACX,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQv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AK/D,GAC1D,IAAe,IAAX7L,EACF,MAAM,IAAImQ,UAAU,UAAYP,EAAM,YAAc5P,QAIxD,IAAqB,IAAjBkQ,EACF,MAAM9H,MAAM,kBAAoBwH,KAQpCpF,WAAYA,I,0+DCrGd,IAAIlB,EAAS,EAAQ,GAQrB,SAASS,EAAYqG,GACnB,GAAwB,mBAAbA,EACT,MAAM,IAAID,UAAU,gCAGtB,IAAIE,EACJ9N,KAAKwF,QAAU,IAAIvC,SAAQ,SAAyBC,GAClD4K,EAAiB5K,KAGnB,IAAI6K,EAAQ/N,KACZ6N,GAAS,SAAgB1L,GACnB4L,EAAMlE,SAKVkE,EAAMlE,OAAS,IAAI9C,EAAO5E,GAC1B2L,EAAeC,EAAMlE,YAOzBrC,EAAYtM,UAAU0O,iBAAmB,WACvC,GAAI5J,KAAK6J,OACP,MAAM7J,KAAK6J,QAQfrC,EAAYjB,OAAS,WACnB,IAAIb,EAIJ,MAAO,CACLqI,MAJU,IAAIvG,GAAY,SAAkB7N,GAC5C+L,EAAS/L,KAIT+L,OAAQA,IAIZ3M,EAAOD,QAAU0O,G,6BClCjBzO,EAAOD,QAAU,SAAgBkV,GAC/B,OAAO,SAAcC,GACnB,OAAOD,EAASlN,MAAM,KAAMmN,M,6BChBhClV,EAAOD,QAAU,SAAsBoV,GACrC,MAA2B,iBAAZA,IAAmD,IAAzBA,EAAQjM","file":"axios.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"axios\"] = factory();\n\telse\n\t\troot[\"axios\"] = factory();\n})(window, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 10);\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (toString.call(val) !== '[object Object]') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\nvar enhanceError = require('./core/enhanceError');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n },\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw enhanceError(e, this, 'E_JSON_PARSE');\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n }\n};\n\ndefaults.headers = {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code\n };\n };\n return error;\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar createError = require('../core/createError');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(resolve, reject, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(\n timeoutErrorMessage,\n config,\n config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken) {\n // Handle cancellation\n config.cancelToken.promise.then(function onCanceled(cancel) {\n if (!request) {\n return;\n }\n\n request.abort();\n reject(cancel);\n // Clean up request\n request = null;\n });\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar enhanceError = require('./enhanceError');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n var valueFromConfig2Keys = ['url', 'method', 'data'];\n var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];\n var defaultToConfig2Keys = [\n 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',\n 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',\n 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',\n 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',\n 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'\n ];\n var directMergeKeys = ['validateStatus'];\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n }\n\n utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n }\n });\n\n utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);\n\n utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n utils.forEach(directMergeKeys, function merge(prop) {\n if (prop in config2) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n var axiosKeys = valueFromConfig2Keys\n .concat(mergeDeepPropertiesKeys)\n .concat(defaultToConfig2Keys)\n .concat(directMergeKeys);\n\n var otherKeys = Object\n .keys(config1)\n .concat(Object.keys(config2))\n .filter(function filterAxiosKeys(key) {\n return axiosKeys.indexOf(key) === -1;\n });\n\n utils.forEach(otherKeys, mergeDeepProperties);\n\n return config;\n};\n","'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n","module.exports = require('./lib/axios');","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Factory for creating new instances\naxios.create = function create(instanceConfig) {\n return createInstance(mergeConfig(axios.defaults, instanceConfig));\n};\n\n// Expose Cancel & CancelToken\naxios.Cancel = require('./cancel/Cancel');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = arguments[1] || {};\n config.url = arguments[0];\n } else {\n config = config || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'),\n forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'),\n clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0')\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('./../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","'use strict';\n\nvar createError = require('./createError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d\\+\\-\\.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\nvar pkg = require('./../../package.json');\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\nvar currentVerArr = pkg.version.split('.');\n\n/**\n * Compare package versions\n * @param {string} version\n * @param {string?} thanVersion\n * @returns {boolean}\n */\nfunction isOlderVersion(version, thanVersion) {\n var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr;\n var destVer = version.split('.');\n for (var i = 0; i < 3; i++) {\n if (pkgVersionArr[i] > destVer[i]) {\n return true;\n } else if (pkgVersionArr[i] < destVer[i]) {\n return false;\n }\n }\n return false;\n}\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator\n * @param {string?} version\n * @param {string} message\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n var isDeprecated = version && isOlderVersion(version);\n\n function formatMessage(opt, desc) {\n return '[Axios v' + pkg.version + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new Error(formatMessage(opt, ' has been removed in ' + version));\n }\n\n if (isDeprecated && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new TypeError('option ' + opt + ' must be ' + result);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw Error('Unknown option ' + opt);\n }\n }\n}\n\nmodule.exports = {\n isOlderVersion: isOlderVersion,\n assertOptions: assertOptions,\n validators: validators\n};\n","'use strict';\n\nvar Cancel = require('./Cancel');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return (typeof payload === 'object') && (payload.isAxiosError === true);\n};\n"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/axios/index.d.ts b/node_modules/axios/index.d.ts new file mode 100644 index 0000000..78f733f --- /dev/null +++ b/node_modules/axios/index.d.ts @@ -0,0 +1,168 @@ +export interface AxiosTransformer { + (data: any, headers?: any): any; +} + +export interface AxiosAdapter { + (config: AxiosRequestConfig): AxiosPromise; +} + +export interface AxiosBasicCredentials { + username: string; + password: string; +} + +export interface AxiosProxyConfig { + host: string; + port: number; + auth?: { + username: string; + password:string; + }; + protocol?: string; +} + +export type Method = + | 'get' | 'GET' + | 'delete' | 'DELETE' + | 'head' | 'HEAD' + | 'options' | 'OPTIONS' + | 'post' | 'POST' + | 'put' | 'PUT' + | 'patch' | 'PATCH' + | 'purge' | 'PURGE' + | 'link' | 'LINK' + | 'unlink' | 'UNLINK' + +export type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream' + +export interface TransitionalOptions{ + silentJSONParsing: boolean; + forcedJSONParsing: boolean; + clarifyTimeoutError: boolean; +} + +export interface AxiosRequestConfig { + url?: string; + method?: Method; + baseURL?: string; + transformRequest?: AxiosTransformer | AxiosTransformer[]; + transformResponse?: AxiosTransformer | AxiosTransformer[]; + headers?: any; + params?: any; + paramsSerializer?: (params: any) => string; + data?: any; + timeout?: number; + timeoutErrorMessage?: string; + withCredentials?: boolean; + adapter?: AxiosAdapter; + auth?: AxiosBasicCredentials; + responseType?: ResponseType; + xsrfCookieName?: string; + xsrfHeaderName?: string; + onUploadProgress?: (progressEvent: any) => void; + onDownloadProgress?: (progressEvent: any) => void; + maxContentLength?: number; + validateStatus?: ((status: number) => boolean) | null; + maxBodyLength?: number; + maxRedirects?: number; + socketPath?: string | null; + httpAgent?: any; + httpsAgent?: any; + proxy?: AxiosProxyConfig | false; + cancelToken?: CancelToken; + decompress?: boolean; + transitional?: TransitionalOptions +} + +export interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: any; + config: AxiosRequestConfig; + request?: any; +} + +export interface AxiosError extends Error { + config: AxiosRequestConfig; + code?: string; + request?: any; + response?: AxiosResponse; + isAxiosError: boolean; + toJSON: () => object; +} + +export interface AxiosPromise extends Promise> { +} + +export interface CancelStatic { + new (message?: string): Cancel; +} + +export interface Cancel { + message: string; +} + +export interface Canceler { + (message?: string): void; +} + +export interface CancelTokenStatic { + new (executor: (cancel: Canceler) => void): CancelToken; + source(): CancelTokenSource; +} + +export interface CancelToken { + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; +} + +export interface CancelTokenSource { + token: CancelToken; + cancel: Canceler; +} + +export interface AxiosInterceptorManager { + use(onFulfilled?: (value: V) => T | Promise, onRejected?: (error: any) => any): number; + eject(id: number): void; +} + +export interface AxiosInstance { + (config: AxiosRequestConfig): AxiosPromise; + (url: string, config?: AxiosRequestConfig): AxiosPromise; + defaults: AxiosRequestConfig; + interceptors: { + request: AxiosInterceptorManager; + response: AxiosInterceptorManager; + }; + getUri(config?: AxiosRequestConfig): string; + request> (config: AxiosRequestConfig): Promise; + get>(url: string, config?: AxiosRequestConfig): Promise; + delete>(url: string, config?: AxiosRequestConfig): Promise; + head>(url: string, config?: AxiosRequestConfig): Promise; + options>(url: string, config?: AxiosRequestConfig): Promise; + post>(url: string, data?: any, config?: AxiosRequestConfig): Promise; + put>(url: string, data?: any, config?: AxiosRequestConfig): Promise; + patch>(url: string, data?: any, config?: AxiosRequestConfig): Promise; +} + +export interface AxiosStatic extends AxiosInstance { + create(config?: AxiosRequestConfig): AxiosInstance; + Cancel: CancelStatic; + CancelToken: CancelTokenStatic; + isCancel(value: any): boolean; + all(values: (T | Promise)[]): Promise; + spread(callback: (...args: T[]) => R): (array: T[]) => R; + isAxiosError(payload: any): payload is AxiosError; +} + +declare const axios: AxiosStatic; + +export default axios; diff --git a/node_modules/axios/index.js b/node_modules/axios/index.js new file mode 100644 index 0000000..79dfd09 --- /dev/null +++ b/node_modules/axios/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/axios'); \ No newline at end of file diff --git a/node_modules/axios/lib/adapters/README.md b/node_modules/axios/lib/adapters/README.md new file mode 100644 index 0000000..68f1118 --- /dev/null +++ b/node_modules/axios/lib/adapters/README.md @@ -0,0 +1,37 @@ +# axios // adapters + +The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. + +## Example + +```js +var settle = require('./../core/settle'); + +module.exports = function myAdapter(config) { + // At this point: + // - config has been merged with defaults + // - request transformers have already run + // - request interceptors have already run + + // Make the request using config provided + // Upon response settle the Promise + + return new Promise(function(resolve, reject) { + + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + + settle(resolve, reject, response); + + // From here: + // - response transformers will run + // - response interceptors will run + }); +} +``` diff --git a/node_modules/axios/lib/adapters/http.js b/node_modules/axios/lib/adapters/http.js new file mode 100755 index 0000000..0cca3bd --- /dev/null +++ b/node_modules/axios/lib/adapters/http.js @@ -0,0 +1,331 @@ +'use strict'; + +var utils = require('./../utils'); +var settle = require('./../core/settle'); +var buildFullPath = require('../core/buildFullPath'); +var buildURL = require('./../helpers/buildURL'); +var http = require('http'); +var https = require('https'); +var httpFollow = require('follow-redirects').http; +var httpsFollow = require('follow-redirects').https; +var url = require('url'); +var zlib = require('zlib'); +var pkg = require('./../../package.json'); +var createError = require('../core/createError'); +var enhanceError = require('../core/enhanceError'); + +var isHttps = /https:?/; + +/** + * + * @param {http.ClientRequestArgs} options + * @param {AxiosProxyConfig} proxy + * @param {string} location + */ +function setProxy(options, proxy, location) { + options.hostname = proxy.host; + options.host = proxy.host; + options.port = proxy.port; + options.path = location; + + // Basic proxy authorization + if (proxy.auth) { + var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64'); + options.headers['Proxy-Authorization'] = 'Basic ' + base64; + } + + // If a proxy is used, any redirects must also pass through the proxy + options.beforeRedirect = function beforeRedirect(redirection) { + redirection.headers.host = redirection.host; + setProxy(redirection, proxy, redirection.href); + }; +} + +/*eslint consistent-return:0*/ +module.exports = function httpAdapter(config) { + return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) { + var resolve = function resolve(value) { + resolvePromise(value); + }; + var reject = function reject(value) { + rejectPromise(value); + }; + var data = config.data; + var headers = config.headers; + + // Set User-Agent (required by some servers) + // See https://github.com/axios/axios/issues/69 + if ('User-Agent' in headers || 'user-agent' in headers) { + // User-Agent is specified; handle case where no UA header is desired + if (!headers['User-Agent'] && !headers['user-agent']) { + delete headers['User-Agent']; + delete headers['user-agent']; + } + // Otherwise, use specified value + } else { + // Only set header if it hasn't been set in config + headers['User-Agent'] = 'axios/' + pkg.version; + } + + if (data && !utils.isStream(data)) { + if (Buffer.isBuffer(data)) { + // Nothing to do... + } else if (utils.isArrayBuffer(data)) { + data = Buffer.from(new Uint8Array(data)); + } else if (utils.isString(data)) { + data = Buffer.from(data, 'utf-8'); + } else { + return reject(createError( + 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', + config + )); + } + + // Add Content-Length header if data exists + headers['Content-Length'] = data.length; + } + + // HTTP basic authentication + var auth = undefined; + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + auth = username + ':' + password; + } + + // Parse url + var fullPath = buildFullPath(config.baseURL, config.url); + var parsed = url.parse(fullPath); + var protocol = parsed.protocol || 'http:'; + + if (!auth && parsed.auth) { + var urlAuth = parsed.auth.split(':'); + var urlUsername = urlAuth[0] || ''; + var urlPassword = urlAuth[1] || ''; + auth = urlUsername + ':' + urlPassword; + } + + if (auth) { + delete headers.Authorization; + } + + var isHttpsRequest = isHttps.test(protocol); + var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent; + + var options = { + path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''), + method: config.method.toUpperCase(), + headers: headers, + agent: agent, + agents: { http: config.httpAgent, https: config.httpsAgent }, + auth: auth + }; + + if (config.socketPath) { + options.socketPath = config.socketPath; + } else { + options.hostname = parsed.hostname; + options.port = parsed.port; + } + + var proxy = config.proxy; + if (!proxy && proxy !== false) { + var proxyEnv = protocol.slice(0, -1) + '_proxy'; + var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()]; + if (proxyUrl) { + var parsedProxyUrl = url.parse(proxyUrl); + var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY; + var shouldProxy = true; + + if (noProxyEnv) { + var noProxy = noProxyEnv.split(',').map(function trim(s) { + return s.trim(); + }); + + shouldProxy = !noProxy.some(function proxyMatch(proxyElement) { + if (!proxyElement) { + return false; + } + if (proxyElement === '*') { + return true; + } + if (proxyElement[0] === '.' && + parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { + return true; + } + + return parsed.hostname === proxyElement; + }); + } + + if (shouldProxy) { + proxy = { + host: parsedProxyUrl.hostname, + port: parsedProxyUrl.port, + protocol: parsedProxyUrl.protocol + }; + + if (parsedProxyUrl.auth) { + var proxyUrlAuth = parsedProxyUrl.auth.split(':'); + proxy.auth = { + username: proxyUrlAuth[0], + password: proxyUrlAuth[1] + }; + } + } + } + } + + if (proxy) { + options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : ''); + setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path); + } + + var transport; + var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true); + if (config.transport) { + transport = config.transport; + } else if (config.maxRedirects === 0) { + transport = isHttpsProxy ? https : http; + } else { + if (config.maxRedirects) { + options.maxRedirects = config.maxRedirects; + } + transport = isHttpsProxy ? httpsFollow : httpFollow; + } + + if (config.maxBodyLength > -1) { + options.maxBodyLength = config.maxBodyLength; + } + + // Create the request + var req = transport.request(options, function handleResponse(res) { + if (req.aborted) return; + + // uncompress the response body transparently if required + var stream = res; + + // return the last request in case of redirects + var lastRequest = res.req || req; + + + // if no content, is HEAD request or decompress disabled we should not decompress + if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) { + switch (res.headers['content-encoding']) { + /*eslint default-case:0*/ + case 'gzip': + case 'compress': + case 'deflate': + // add the unzipper to the body stream processing pipeline + stream = stream.pipe(zlib.createUnzip()); + + // remove the content-encoding in order to not confuse downstream operations + delete res.headers['content-encoding']; + break; + } + } + + var response = { + status: res.statusCode, + statusText: res.statusMessage, + headers: res.headers, + config: config, + request: lastRequest + }; + + if (config.responseType === 'stream') { + response.data = stream; + settle(resolve, reject, response); + } else { + var responseBuffer = []; + var totalResponseBytes = 0; + stream.on('data', function handleStreamData(chunk) { + responseBuffer.push(chunk); + totalResponseBytes += chunk.length; + + // make sure the content length is not over the maxContentLength if specified + if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) { + stream.destroy(); + reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded', + config, null, lastRequest)); + } + }); + + stream.on('error', function handleStreamError(err) { + if (req.aborted) return; + reject(enhanceError(err, config, null, lastRequest)); + }); + + stream.on('end', function handleStreamEnd() { + var responseData = Buffer.concat(responseBuffer); + if (config.responseType !== 'arraybuffer') { + responseData = responseData.toString(config.responseEncoding); + if (!config.responseEncoding || config.responseEncoding === 'utf8') { + responseData = utils.stripBOM(responseData); + } + } + + response.data = responseData; + settle(resolve, reject, response); + }); + } + }); + + // Handle errors + req.on('error', function handleRequestError(err) { + if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return; + reject(enhanceError(err, config, null, req)); + }); + + // Handle request timeout + if (config.timeout) { + // This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types. + var timeout = parseInt(config.timeout, 10); + + if (isNaN(timeout)) { + reject(createError( + 'error trying to parse `config.timeout` to int', + config, + 'ERR_PARSE_TIMEOUT', + req + )); + + return; + } + + // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system. + // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET. + // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up. + // And then these socket which be hang up will devoring CPU little by little. + // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect. + req.setTimeout(timeout, function handleRequestTimeout() { + req.abort(); + reject(createError( + 'timeout of ' + timeout + 'ms exceeded', + config, + config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', + req + )); + }); + } + + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (req.aborted) return; + + req.abort(); + reject(cancel); + }); + } + + // Send the request + if (utils.isStream(data)) { + data.on('error', function handleStreamError(err) { + reject(enhanceError(err, config, null, req)); + }).pipe(req); + } else { + req.end(data); + } + }); +}; diff --git a/node_modules/axios/lib/adapters/xhr.js b/node_modules/axios/lib/adapters/xhr.js new file mode 100644 index 0000000..a386dd2 --- /dev/null +++ b/node_modules/axios/lib/adapters/xhr.js @@ -0,0 +1,189 @@ +'use strict'; + +var utils = require('./../utils'); +var settle = require('./../core/settle'); +var cookies = require('./../helpers/cookies'); +var buildURL = require('./../helpers/buildURL'); +var buildFullPath = require('../core/buildFullPath'); +var parseHeaders = require('./../helpers/parseHeaders'); +var isURLSameOrigin = require('./../helpers/isURLSameOrigin'); +var createError = require('../core/createError'); + +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; + var responseType = config.responseType; + + if (utils.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it + } + + var request = new XMLHttpRequest(); + + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } + + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + + // Set the request timeout in MS + request.timeout = config.timeout; + + function onloadend() { + if (!request) { + return; + } + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !responseType || responseType === 'text' || responseType === 'json' ? + request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; + + settle(resolve, reject, response); + + // Clean up request + request = null; + } + + if ('onloadend' in request) { + // Use onloadend if available + request.onloadend = onloadend; + } else { + // Listen for ready state to emulate onloadend + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } + + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } + // readystate handler is calling before onerror or ontimeout handlers, + // so we should call onloadend on the next 'tick' + setTimeout(onloadend); + }; + } + + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; + } + + reject(createError('Request aborted', config, 'ECONNABORTED', request)); + + // Clean up request + request = null; + }; + + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(createError('Network Error', config, null, request)); + + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; + } + reject(createError( + timeoutErrorMessage, + config, + config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', + request)); + + // Clean up request + request = null; + }; + + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; + + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; + } + } + + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); + } + + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } + + // Add responseType to request if needed + if (responseType && responseType !== 'json') { + request.responseType = config.responseType; + } + + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } + + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } + + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; + } + + request.abort(); + reject(cancel); + // Clean up request + request = null; + }); + } + + if (!requestData) { + requestData = null; + } + + // Send the request + request.send(requestData); + }); +}; diff --git a/node_modules/axios/lib/axios.js b/node_modules/axios/lib/axios.js new file mode 100644 index 0000000..c6357b0 --- /dev/null +++ b/node_modules/axios/lib/axios.js @@ -0,0 +1,56 @@ +'use strict'; + +var utils = require('./utils'); +var bind = require('./helpers/bind'); +var Axios = require('./core/Axios'); +var mergeConfig = require('./core/mergeConfig'); +var defaults = require('./defaults'); + +/** + * Create an instance of Axios + * + * @param {Object} defaultConfig The default config for the instance + * @return {Axios} A new instance of Axios + */ +function createInstance(defaultConfig) { + var context = new Axios(defaultConfig); + var instance = bind(Axios.prototype.request, context); + + // Copy axios.prototype to instance + utils.extend(instance, Axios.prototype, context); + + // Copy context to instance + utils.extend(instance, context); + + return instance; +} + +// Create the default instance to be exported +var axios = createInstance(defaults); + +// Expose Axios class to allow class inheritance +axios.Axios = Axios; + +// Factory for creating new instances +axios.create = function create(instanceConfig) { + return createInstance(mergeConfig(axios.defaults, instanceConfig)); +}; + +// Expose Cancel & CancelToken +axios.Cancel = require('./cancel/Cancel'); +axios.CancelToken = require('./cancel/CancelToken'); +axios.isCancel = require('./cancel/isCancel'); + +// Expose all/spread +axios.all = function all(promises) { + return Promise.all(promises); +}; +axios.spread = require('./helpers/spread'); + +// Expose isAxiosError +axios.isAxiosError = require('./helpers/isAxiosError'); + +module.exports = axios; + +// Allow use of default import syntax in TypeScript +module.exports.default = axios; diff --git a/node_modules/axios/lib/cancel/Cancel.js b/node_modules/axios/lib/cancel/Cancel.js new file mode 100644 index 0000000..e0de400 --- /dev/null +++ b/node_modules/axios/lib/cancel/Cancel.js @@ -0,0 +1,19 @@ +'use strict'; + +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; +} + +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; + +Cancel.prototype.__CANCEL__ = true; + +module.exports = Cancel; diff --git a/node_modules/axios/lib/cancel/CancelToken.js b/node_modules/axios/lib/cancel/CancelToken.js new file mode 100644 index 0000000..6b46e66 --- /dev/null +++ b/node_modules/axios/lib/cancel/CancelToken.js @@ -0,0 +1,57 @@ +'use strict'; + +var Cancel = require('./Cancel'); + +/** + * A `CancelToken` is an object that can be used to request cancellation of an operation. + * + * @class + * @param {Function} executor The executor function. + */ +function CancelToken(executor) { + if (typeof executor !== 'function') { + throw new TypeError('executor must be a function.'); + } + + var resolvePromise; + this.promise = new Promise(function promiseExecutor(resolve) { + resolvePromise = resolve; + }); + + var token = this; + executor(function cancel(message) { + if (token.reason) { + // Cancellation has already been requested + return; + } + + token.reason = new Cancel(message); + resolvePromise(token.reason); + }); +} + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +CancelToken.prototype.throwIfRequested = function throwIfRequested() { + if (this.reason) { + throw this.reason; + } +}; + +/** + * Returns an object that contains a new `CancelToken` and a function that, when called, + * cancels the `CancelToken`. + */ +CancelToken.source = function source() { + var cancel; + var token = new CancelToken(function executor(c) { + cancel = c; + }); + return { + token: token, + cancel: cancel + }; +}; + +module.exports = CancelToken; diff --git a/node_modules/axios/lib/cancel/isCancel.js b/node_modules/axios/lib/cancel/isCancel.js new file mode 100644 index 0000000..051f3ae --- /dev/null +++ b/node_modules/axios/lib/cancel/isCancel.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); +}; diff --git a/node_modules/axios/lib/core/Axios.js b/node_modules/axios/lib/core/Axios.js new file mode 100644 index 0000000..42ea75e --- /dev/null +++ b/node_modules/axios/lib/core/Axios.js @@ -0,0 +1,148 @@ +'use strict'; + +var utils = require('./../utils'); +var buildURL = require('../helpers/buildURL'); +var InterceptorManager = require('./InterceptorManager'); +var dispatchRequest = require('./dispatchRequest'); +var mergeConfig = require('./mergeConfig'); +var validator = require('../helpers/validator'); + +var validators = validator.validators; +/** + * Create a new instance of Axios + * + * @param {Object} instanceConfig The default config for the instance + */ +function Axios(instanceConfig) { + this.defaults = instanceConfig; + this.interceptors = { + request: new InterceptorManager(), + response: new InterceptorManager() + }; +} + +/** + * Dispatch a request + * + * @param {Object} config The config specific for this request (merged with this.defaults) + */ +Axios.prototype.request = function request(config) { + /*eslint no-param-reassign:0*/ + // Allow for axios('example/url'[, config]) a la fetch API + if (typeof config === 'string') { + config = arguments[1] || {}; + config.url = arguments[0]; + } else { + config = config || {}; + } + + config = mergeConfig(this.defaults, config); + + // Set config.method + if (config.method) { + config.method = config.method.toLowerCase(); + } else if (this.defaults.method) { + config.method = this.defaults.method.toLowerCase(); + } else { + config.method = 'get'; + } + + var transitional = config.transitional; + + if (transitional !== undefined) { + validator.assertOptions(transitional, { + silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'), + forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'), + clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0') + }, false); + } + + // filter out skipped interceptors + var requestInterceptorChain = []; + var synchronousRequestInterceptors = true; + this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { + if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { + return; + } + + synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; + + requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); + }); + + var responseInterceptorChain = []; + this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { + responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); + }); + + var promise; + + if (!synchronousRequestInterceptors) { + var chain = [dispatchRequest, undefined]; + + Array.prototype.unshift.apply(chain, requestInterceptorChain); + chain = chain.concat(responseInterceptorChain); + + promise = Promise.resolve(config); + while (chain.length) { + promise = promise.then(chain.shift(), chain.shift()); + } + + return promise; + } + + + var newConfig = config; + while (requestInterceptorChain.length) { + var onFulfilled = requestInterceptorChain.shift(); + var onRejected = requestInterceptorChain.shift(); + try { + newConfig = onFulfilled(newConfig); + } catch (error) { + onRejected(error); + break; + } + } + + try { + promise = dispatchRequest(newConfig); + } catch (error) { + return Promise.reject(error); + } + + while (responseInterceptorChain.length) { + promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); + } + + return promise; +}; + +Axios.prototype.getUri = function getUri(config) { + config = mergeConfig(this.defaults, config); + return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); +}; + +// Provide aliases for supported request methods +utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: (config || {}).data + })); + }; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + /*eslint func-names:0*/ + Axios.prototype[method] = function(url, data, config) { + return this.request(mergeConfig(config || {}, { + method: method, + url: url, + data: data + })); + }; +}); + +module.exports = Axios; diff --git a/node_modules/axios/lib/core/InterceptorManager.js b/node_modules/axios/lib/core/InterceptorManager.js new file mode 100644 index 0000000..900f448 --- /dev/null +++ b/node_modules/axios/lib/core/InterceptorManager.js @@ -0,0 +1,54 @@ +'use strict'; + +var utils = require('./../utils'); + +function InterceptorManager() { + this.handlers = []; +} + +/** + * Add a new interceptor to the stack + * + * @param {Function} fulfilled The function to handle `then` for a `Promise` + * @param {Function} rejected The function to handle `reject` for a `Promise` + * + * @return {Number} An ID used to remove interceptor later + */ +InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { + this.handlers.push({ + fulfilled: fulfilled, + rejected: rejected, + synchronous: options ? options.synchronous : false, + runWhen: options ? options.runWhen : null + }); + return this.handlers.length - 1; +}; + +/** + * Remove an interceptor from the stack + * + * @param {Number} id The ID that was returned by `use` + */ +InterceptorManager.prototype.eject = function eject(id) { + if (this.handlers[id]) { + this.handlers[id] = null; + } +}; + +/** + * Iterate over all the registered interceptors + * + * This method is particularly useful for skipping over any + * interceptors that may have become `null` calling `eject`. + * + * @param {Function} fn The function to call for each interceptor + */ +InterceptorManager.prototype.forEach = function forEach(fn) { + utils.forEach(this.handlers, function forEachHandler(h) { + if (h !== null) { + fn(h); + } + }); +}; + +module.exports = InterceptorManager; diff --git a/node_modules/axios/lib/core/README.md b/node_modules/axios/lib/core/README.md new file mode 100644 index 0000000..84559ce --- /dev/null +++ b/node_modules/axios/lib/core/README.md @@ -0,0 +1,8 @@ +# axios // core + +The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: + +- Dispatching requests + - Requests sent via `adapters/` (see lib/adapters/README.md) +- Managing interceptors +- Handling config diff --git a/node_modules/axios/lib/core/buildFullPath.js b/node_modules/axios/lib/core/buildFullPath.js new file mode 100644 index 0000000..00b2b05 --- /dev/null +++ b/node_modules/axios/lib/core/buildFullPath.js @@ -0,0 +1,20 @@ +'use strict'; + +var isAbsoluteURL = require('../helpers/isAbsoluteURL'); +var combineURLs = require('../helpers/combineURLs'); + +/** + * Creates a new URL by combining the baseURL with the requestedURL, + * only when the requestedURL is not already an absolute URL. + * If the requestURL is absolute, this function returns the requestedURL untouched. + * + * @param {string} baseURL The base URL + * @param {string} requestedURL Absolute or relative URL to combine + * @returns {string} The combined full path + */ +module.exports = function buildFullPath(baseURL, requestedURL) { + if (baseURL && !isAbsoluteURL(requestedURL)) { + return combineURLs(baseURL, requestedURL); + } + return requestedURL; +}; diff --git a/node_modules/axios/lib/core/createError.js b/node_modules/axios/lib/core/createError.js new file mode 100644 index 0000000..933680f --- /dev/null +++ b/node_modules/axios/lib/core/createError.js @@ -0,0 +1,18 @@ +'use strict'; + +var enhanceError = require('./enhanceError'); + +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +module.exports = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError(error, config, code, request, response); +}; diff --git a/node_modules/axios/lib/core/dispatchRequest.js b/node_modules/axios/lib/core/dispatchRequest.js new file mode 100644 index 0000000..9ce3b96 --- /dev/null +++ b/node_modules/axios/lib/core/dispatchRequest.js @@ -0,0 +1,82 @@ +'use strict'; + +var utils = require('./../utils'); +var transformData = require('./transformData'); +var isCancel = require('../cancel/isCancel'); +var defaults = require('../defaults'); + +/** + * Throws a `Cancel` if cancellation has been requested. + */ +function throwIfCancellationRequested(config) { + if (config.cancelToken) { + config.cancelToken.throwIfRequested(); + } +} + +/** + * Dispatch a request to the server using the configured adapter. + * + * @param {object} config The config that is to be used for the request + * @returns {Promise} The Promise to be fulfilled + */ +module.exports = function dispatchRequest(config) { + throwIfCancellationRequested(config); + + // Ensure headers exist + config.headers = config.headers || {}; + + // Transform request data + config.data = transformData.call( + config, + config.data, + config.headers, + config.transformRequest + ); + + // Flatten headers + config.headers = utils.merge( + config.headers.common || {}, + config.headers[config.method] || {}, + config.headers + ); + + utils.forEach( + ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], + function cleanHeaderConfig(method) { + delete config.headers[method]; + } + ); + + var adapter = config.adapter || defaults.adapter; + + return adapter(config).then(function onAdapterResolution(response) { + throwIfCancellationRequested(config); + + // Transform response data + response.data = transformData.call( + config, + response.data, + response.headers, + config.transformResponse + ); + + return response; + }, function onAdapterRejection(reason) { + if (!isCancel(reason)) { + throwIfCancellationRequested(config); + + // Transform response data + if (reason && reason.response) { + reason.response.data = transformData.call( + config, + reason.response.data, + reason.response.headers, + config.transformResponse + ); + } + } + + return Promise.reject(reason); + }); +}; diff --git a/node_modules/axios/lib/core/enhanceError.js b/node_modules/axios/lib/core/enhanceError.js new file mode 100644 index 0000000..b6bc444 --- /dev/null +++ b/node_modules/axios/lib/core/enhanceError.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * Update an Error with the specified config, error code, and response. + * + * @param {Error} error The error to update. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The error. + */ +module.exports = function enhanceError(error, config, code, request, response) { + error.config = config; + if (code) { + error.code = code; + } + + error.request = request; + error.response = response; + error.isAxiosError = true; + + error.toJSON = function toJSON() { + return { + // Standard + message: this.message, + name: this.name, + // Microsoft + description: this.description, + number: this.number, + // Mozilla + fileName: this.fileName, + lineNumber: this.lineNumber, + columnNumber: this.columnNumber, + stack: this.stack, + // Axios + config: this.config, + code: this.code + }; + }; + return error; +}; diff --git a/node_modules/axios/lib/core/mergeConfig.js b/node_modules/axios/lib/core/mergeConfig.js new file mode 100644 index 0000000..5a2c10c --- /dev/null +++ b/node_modules/axios/lib/core/mergeConfig.js @@ -0,0 +1,87 @@ +'use strict'; + +var utils = require('../utils'); + +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + + var valueFromConfig2Keys = ['url', 'method', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; + var defaultToConfig2Keys = [ + 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', + 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' + ]; + var directMergeKeys = ['validateStatus']; + + function getMergedValue(target, source) { + if (utils.isPlainObject(target) && utils.isPlainObject(source)) { + return utils.merge(target, source); + } else if (utils.isPlainObject(source)) { + return utils.merge({}, source); + } else if (utils.isArray(source)) { + return source.slice(); + } + return source; + } + + function mergeDeepProperties(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + } + + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } + }); + + utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); + + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (!utils.isUndefined(config2[prop])) { + config[prop] = getMergedValue(undefined, config2[prop]); + } else if (!utils.isUndefined(config1[prop])) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + utils.forEach(directMergeKeys, function merge(prop) { + if (prop in config2) { + config[prop] = getMergedValue(config1[prop], config2[prop]); + } else if (prop in config1) { + config[prop] = getMergedValue(undefined, config1[prop]); + } + }); + + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys) + .concat(directMergeKeys); + + var otherKeys = Object + .keys(config1) + .concat(Object.keys(config2)) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); + + utils.forEach(otherKeys, mergeDeepProperties); + + return config; +}; diff --git a/node_modules/axios/lib/core/settle.js b/node_modules/axios/lib/core/settle.js new file mode 100644 index 0000000..886adb0 --- /dev/null +++ b/node_modules/axios/lib/core/settle.js @@ -0,0 +1,25 @@ +'use strict'; + +var createError = require('./createError'); + +/** + * Resolve or reject a Promise based on response status. + * + * @param {Function} resolve A function that resolves the promise. + * @param {Function} reject A function that rejects the promise. + * @param {object} response The response. + */ +module.exports = function settle(resolve, reject, response) { + var validateStatus = response.config.validateStatus; + if (!response.status || !validateStatus || validateStatus(response.status)) { + resolve(response); + } else { + reject(createError( + 'Request failed with status code ' + response.status, + response.config, + null, + response.request, + response + )); + } +}; diff --git a/node_modules/axios/lib/core/transformData.js b/node_modules/axios/lib/core/transformData.js new file mode 100644 index 0000000..c584d12 --- /dev/null +++ b/node_modules/axios/lib/core/transformData.js @@ -0,0 +1,22 @@ +'use strict'; + +var utils = require('./../utils'); +var defaults = require('./../defaults'); + +/** + * Transform the data for a request or a response + * + * @param {Object|String} data The data to be transformed + * @param {Array} headers The headers for the request or response + * @param {Array|Function} fns A single function or Array of functions + * @returns {*} The resulting transformed data + */ +module.exports = function transformData(data, headers, fns) { + var context = this || defaults; + /*eslint no-param-reassign:0*/ + utils.forEach(fns, function transform(fn) { + data = fn.call(context, data, headers); + }); + + return data; +}; diff --git a/node_modules/axios/lib/defaults.js b/node_modules/axios/lib/defaults.js new file mode 100644 index 0000000..55e69d9 --- /dev/null +++ b/node_modules/axios/lib/defaults.js @@ -0,0 +1,134 @@ +'use strict'; + +var utils = require('./utils'); +var normalizeHeaderName = require('./helpers/normalizeHeaderName'); +var enhanceError = require('./core/enhanceError'); + +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; + +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; + } +} + +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = require('./adapters/xhr'); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = require('./adapters/http'); + } + return adapter; +} + +function stringifySafely(rawValue, parser, encoder) { + if (utils.isString(rawValue)) { + try { + (parser || JSON.parse)(rawValue); + return utils.trim(rawValue); + } catch (e) { + if (e.name !== 'SyntaxError') { + throw e; + } + } + } + + return (encoder || JSON.stringify)(rawValue); +} + +var defaults = { + + transitional: { + silentJSONParsing: true, + forcedJSONParsing: true, + clarifyTimeoutError: false + }, + + adapter: getDefaultAdapter(), + + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { + setContentTypeIfUnset(headers, 'application/json'); + return stringifySafely(data); + } + return data; + }], + + transformResponse: [function transformResponse(data) { + var transitional = this.transitional; + var silentJSONParsing = transitional && transitional.silentJSONParsing; + var forcedJSONParsing = transitional && transitional.forcedJSONParsing; + var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; + + if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { + try { + return JSON.parse(data); + } catch (e) { + if (strictJSONParsing) { + if (e.name === 'SyntaxError') { + throw enhanceError(e, this, 'E_JSON_PARSE'); + } + throw e; + } + } + } + + return data; + }], + + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', + + maxContentLength: -1, + maxBodyLength: -1, + + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; + } +}; + +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } +}; + +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); + +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); + +module.exports = defaults; diff --git a/node_modules/axios/lib/helpers/README.md b/node_modules/axios/lib/helpers/README.md new file mode 100644 index 0000000..4ae3419 --- /dev/null +++ b/node_modules/axios/lib/helpers/README.md @@ -0,0 +1,7 @@ +# axios // helpers + +The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: + +- Browser polyfills +- Managing cookies +- Parsing HTTP headers diff --git a/node_modules/axios/lib/helpers/bind.js b/node_modules/axios/lib/helpers/bind.js new file mode 100644 index 0000000..6147c60 --- /dev/null +++ b/node_modules/axios/lib/helpers/bind.js @@ -0,0 +1,11 @@ +'use strict'; + +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; +}; diff --git a/node_modules/axios/lib/helpers/buildURL.js b/node_modules/axios/lib/helpers/buildURL.js new file mode 100644 index 0000000..31595c3 --- /dev/null +++ b/node_modules/axios/lib/helpers/buildURL.js @@ -0,0 +1,70 @@ +'use strict'; + +var utils = require('./../utils'); + +function encode(val) { + return encodeURIComponent(val). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} + +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } + + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; + + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } + + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } + + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); + }); + }); + + serializedParams = parts.join('&'); + } + + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } + + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } + + return url; +}; diff --git a/node_modules/axios/lib/helpers/combineURLs.js b/node_modules/axios/lib/helpers/combineURLs.js new file mode 100644 index 0000000..f1b58a5 --- /dev/null +++ b/node_modules/axios/lib/helpers/combineURLs.js @@ -0,0 +1,14 @@ +'use strict'; + +/** + * Creates a new URL by combining the specified URLs + * + * @param {string} baseURL The base URL + * @param {string} relativeURL The relative URL + * @returns {string} The combined URL + */ +module.exports = function combineURLs(baseURL, relativeURL) { + return relativeURL + ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') + : baseURL; +}; diff --git a/node_modules/axios/lib/helpers/cookies.js b/node_modules/axios/lib/helpers/cookies.js new file mode 100644 index 0000000..5a8a666 --- /dev/null +++ b/node_modules/axios/lib/helpers/cookies.js @@ -0,0 +1,53 @@ +'use strict'; + +var utils = require('./../utils'); + +module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs support document.cookie + (function standardBrowserEnv() { + return { + write: function write(name, value, expires, path, domain, secure) { + var cookie = []; + cookie.push(name + '=' + encodeURIComponent(value)); + + if (utils.isNumber(expires)) { + cookie.push('expires=' + new Date(expires).toGMTString()); + } + + if (utils.isString(path)) { + cookie.push('path=' + path); + } + + if (utils.isString(domain)) { + cookie.push('domain=' + domain); + } + + if (secure === true) { + cookie.push('secure'); + } + + document.cookie = cookie.join('; '); + }, + + read: function read(name) { + var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); + return (match ? decodeURIComponent(match[3]) : null); + }, + + remove: function remove(name) { + this.write(name, '', Date.now() - 86400000); + } + }; + })() : + + // Non standard browser env (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return { + write: function write() {}, + read: function read() { return null; }, + remove: function remove() {} + }; + })() +); diff --git a/node_modules/axios/lib/helpers/deprecatedMethod.js b/node_modules/axios/lib/helpers/deprecatedMethod.js new file mode 100644 index 0000000..ed40965 --- /dev/null +++ b/node_modules/axios/lib/helpers/deprecatedMethod.js @@ -0,0 +1,24 @@ +'use strict'; + +/*eslint no-console:0*/ + +/** + * Supply a warning to the developer that a method they are using + * has been deprecated. + * + * @param {string} method The name of the deprecated method + * @param {string} [instead] The alternate method to use if applicable + * @param {string} [docs] The documentation URL to get further details + */ +module.exports = function deprecatedMethod(method, instead, docs) { + try { + console.warn( + 'DEPRECATED method `' + method + '`.' + + (instead ? ' Use `' + instead + '` instead.' : '') + + ' This method will be removed in a future release.'); + + if (docs) { + console.warn('For more information about usage see ' + docs); + } + } catch (e) { /* Ignore */ } +}; diff --git a/node_modules/axios/lib/helpers/isAbsoluteURL.js b/node_modules/axios/lib/helpers/isAbsoluteURL.js new file mode 100644 index 0000000..d33e992 --- /dev/null +++ b/node_modules/axios/lib/helpers/isAbsoluteURL.js @@ -0,0 +1,14 @@ +'use strict'; + +/** + * Determines whether the specified URL is absolute + * + * @param {string} url The URL to test + * @returns {boolean} True if the specified URL is absolute, otherwise false + */ +module.exports = function isAbsoluteURL(url) { + // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL). + // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed + // by any combination of letters, digits, plus, period, or hyphen. + return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); +}; diff --git a/node_modules/axios/lib/helpers/isAxiosError.js b/node_modules/axios/lib/helpers/isAxiosError.js new file mode 100644 index 0000000..29ff41a --- /dev/null +++ b/node_modules/axios/lib/helpers/isAxiosError.js @@ -0,0 +1,11 @@ +'use strict'; + +/** + * Determines whether the payload is an error thrown by Axios + * + * @param {*} payload The value to test + * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false + */ +module.exports = function isAxiosError(payload) { + return (typeof payload === 'object') && (payload.isAxiosError === true); +}; diff --git a/node_modules/axios/lib/helpers/isURLSameOrigin.js b/node_modules/axios/lib/helpers/isURLSameOrigin.js new file mode 100644 index 0000000..f1d89ad --- /dev/null +++ b/node_modules/axios/lib/helpers/isURLSameOrigin.js @@ -0,0 +1,68 @@ +'use strict'; + +var utils = require('./../utils'); + +module.exports = ( + utils.isStandardBrowserEnv() ? + + // Standard browser envs have full support of the APIs needed to test + // whether the request URL is of the same origin as current location. + (function standardBrowserEnv() { + var msie = /(msie|trident)/i.test(navigator.userAgent); + var urlParsingNode = document.createElement('a'); + var originURL; + + /** + * Parse a URL to discover it's components + * + * @param {String} url The URL to be parsed + * @returns {Object} + */ + function resolveURL(url) { + var href = url; + + if (msie) { + // IE needs attribute set twice to normalize properties + urlParsingNode.setAttribute('href', href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') ? + urlParsingNode.pathname : + '/' + urlParsingNode.pathname + }; + } + + originURL = resolveURL(window.location.href); + + /** + * Determine if a URL shares the same origin as the current location + * + * @param {String} requestURL The URL to test + * @returns {boolean} True if URL shares the same origin, otherwise false + */ + return function isURLSameOrigin(requestURL) { + var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; + return (parsed.protocol === originURL.protocol && + parsed.host === originURL.host); + }; + })() : + + // Non standard browser envs (web workers, react-native) lack needed support. + (function nonStandardBrowserEnv() { + return function isURLSameOrigin() { + return true; + }; + })() +); diff --git a/node_modules/axios/lib/helpers/normalizeHeaderName.js b/node_modules/axios/lib/helpers/normalizeHeaderName.js new file mode 100644 index 0000000..738c9fe --- /dev/null +++ b/node_modules/axios/lib/helpers/normalizeHeaderName.js @@ -0,0 +1,12 @@ +'use strict'; + +var utils = require('../utils'); + +module.exports = function normalizeHeaderName(headers, normalizedName) { + utils.forEach(headers, function processHeader(value, name) { + if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { + headers[normalizedName] = value; + delete headers[name]; + } + }); +}; diff --git a/node_modules/axios/lib/helpers/parseHeaders.js b/node_modules/axios/lib/helpers/parseHeaders.js new file mode 100644 index 0000000..8af2cc7 --- /dev/null +++ b/node_modules/axios/lib/helpers/parseHeaders.js @@ -0,0 +1,53 @@ +'use strict'; + +var utils = require('./../utils'); + +// Headers whose duplicates are ignored by node +// c.f. https://nodejs.org/api/http.html#http_message_headers +var ignoreDuplicateOf = [ + 'age', 'authorization', 'content-length', 'content-type', 'etag', + 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', + 'last-modified', 'location', 'max-forwards', 'proxy-authorization', + 'referer', 'retry-after', 'user-agent' +]; + +/** + * Parse headers into an object + * + * ``` + * Date: Wed, 27 Aug 2014 08:58:49 GMT + * Content-Type: application/json + * Connection: keep-alive + * Transfer-Encoding: chunked + * ``` + * + * @param {String} headers Headers needing to be parsed + * @returns {Object} Headers parsed into an object + */ +module.exports = function parseHeaders(headers) { + var parsed = {}; + var key; + var val; + var i; + + if (!headers) { return parsed; } + + utils.forEach(headers.split('\n'), function parser(line) { + i = line.indexOf(':'); + key = utils.trim(line.substr(0, i)).toLowerCase(); + val = utils.trim(line.substr(i + 1)); + + if (key) { + if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { + return; + } + if (key === 'set-cookie') { + parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); + } else { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + }); + + return parsed; +}; diff --git a/node_modules/axios/lib/helpers/spread.js b/node_modules/axios/lib/helpers/spread.js new file mode 100644 index 0000000..25e3cdd --- /dev/null +++ b/node_modules/axios/lib/helpers/spread.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * Syntactic sugar for invoking a function and expanding an array for arguments. + * + * Common use case would be to use `Function.prototype.apply`. + * + * ```js + * function f(x, y, z) {} + * var args = [1, 2, 3]; + * f.apply(null, args); + * ``` + * + * With `spread` this example can be re-written. + * + * ```js + * spread(function(x, y, z) {})([1, 2, 3]); + * ``` + * + * @param {Function} callback + * @returns {Function} + */ +module.exports = function spread(callback) { + return function wrap(arr) { + return callback.apply(null, arr); + }; +}; diff --git a/node_modules/axios/lib/helpers/validator.js b/node_modules/axios/lib/helpers/validator.js new file mode 100644 index 0000000..7f1bc7d --- /dev/null +++ b/node_modules/axios/lib/helpers/validator.js @@ -0,0 +1,105 @@ +'use strict'; + +var pkg = require('./../../package.json'); + +var validators = {}; + +// eslint-disable-next-line func-names +['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { + validators[type] = function validator(thing) { + return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; + }; +}); + +var deprecatedWarnings = {}; +var currentVerArr = pkg.version.split('.'); + +/** + * Compare package versions + * @param {string} version + * @param {string?} thanVersion + * @returns {boolean} + */ +function isOlderVersion(version, thanVersion) { + var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr; + var destVer = version.split('.'); + for (var i = 0; i < 3; i++) { + if (pkgVersionArr[i] > destVer[i]) { + return true; + } else if (pkgVersionArr[i] < destVer[i]) { + return false; + } + } + return false; +} + +/** + * Transitional option validator + * @param {function|boolean?} validator + * @param {string?} version + * @param {string} message + * @returns {function} + */ +validators.transitional = function transitional(validator, version, message) { + var isDeprecated = version && isOlderVersion(version); + + function formatMessage(opt, desc) { + return '[Axios v' + pkg.version + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + } + + // eslint-disable-next-line func-names + return function(value, opt, opts) { + if (validator === false) { + throw new Error(formatMessage(opt, ' has been removed in ' + version)); + } + + if (isDeprecated && !deprecatedWarnings[opt]) { + deprecatedWarnings[opt] = true; + // eslint-disable-next-line no-console + console.warn( + formatMessage( + opt, + ' has been deprecated since v' + version + ' and will be removed in the near future' + ) + ); + } + + return validator ? validator(value, opt, opts) : true; + }; +}; + +/** + * Assert object's properties type + * @param {object} options + * @param {object} schema + * @param {boolean?} allowUnknown + */ + +function assertOptions(options, schema, allowUnknown) { + if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + var keys = Object.keys(options); + var i = keys.length; + while (i-- > 0) { + var opt = keys[i]; + var validator = schema[opt]; + if (validator) { + var value = options[opt]; + var result = value === undefined || validator(value, opt, options); + if (result !== true) { + throw new TypeError('option ' + opt + ' must be ' + result); + } + continue; + } + if (allowUnknown !== true) { + throw Error('Unknown option ' + opt); + } + } +} + +module.exports = { + isOlderVersion: isOlderVersion, + assertOptions: assertOptions, + validators: validators +}; diff --git a/node_modules/axios/lib/utils.js b/node_modules/axios/lib/utils.js new file mode 100644 index 0000000..5d966f4 --- /dev/null +++ b/node_modules/axios/lib/utils.js @@ -0,0 +1,349 @@ +'use strict'; + +var bind = require('./helpers/bind'); + +// utils is a library of generic helper functions non-specific to axios + +var toString = Object.prototype.toString; + +/** + * Determine if a value is an Array + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Array, otherwise false + */ +function isArray(val) { + return toString.call(val) === '[object Array]'; +} + +/** + * Determine if a value is undefined + * + * @param {Object} val The value to test + * @returns {boolean} True if the value is undefined, otherwise false + */ +function isUndefined(val) { + return typeof val === 'undefined'; +} + +/** + * Determine if a value is a Buffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Buffer, otherwise false + */ +function isBuffer(val) { + return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) + && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); +} + +/** + * Determine if a value is an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an ArrayBuffer, otherwise false + */ +function isArrayBuffer(val) { + return toString.call(val) === '[object ArrayBuffer]'; +} + +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return (typeof FormData !== 'undefined') && (val instanceof FormData); +} + +/** + * Determine if a value is a view on an ArrayBuffer + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false + */ +function isArrayBufferView(val) { + var result; + if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { + result = ArrayBuffer.isView(val); + } else { + result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); + } + return result; +} + +/** + * Determine if a value is a String + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a String, otherwise false + */ +function isString(val) { + return typeof val === 'string'; +} + +/** + * Determine if a value is a Number + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Number, otherwise false + */ +function isNumber(val) { + return typeof val === 'number'; +} + +/** + * Determine if a value is an Object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an Object, otherwise false + */ +function isObject(val) { + return val !== null && typeof val === 'object'; +} + +/** + * Determine if a value is a plain Object + * + * @param {Object} val The value to test + * @return {boolean} True if value is a plain Object, otherwise false + */ +function isPlainObject(val) { + if (toString.call(val) !== '[object Object]') { + return false; + } + + var prototype = Object.getPrototypeOf(val); + return prototype === null || prototype === Object.prototype; +} + +/** + * Determine if a value is a Date + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Date, otherwise false + */ +function isDate(val) { + return toString.call(val) === '[object Date]'; +} + +/** + * Determine if a value is a File + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a File, otherwise false + */ +function isFile(val) { + return toString.call(val) === '[object File]'; +} + +/** + * Determine if a value is a Blob + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Blob, otherwise false + */ +function isBlob(val) { + return toString.call(val) === '[object Blob]'; +} + +/** + * Determine if a value is a Function + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Function, otherwise false + */ +function isFunction(val) { + return toString.call(val) === '[object Function]'; +} + +/** + * Determine if a value is a Stream + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a Stream, otherwise false + */ +function isStream(val) { + return isObject(val) && isFunction(val.pipe); +} + +/** + * Determine if a value is a URLSearchParams object + * + * @param {Object} val The value to test + * @returns {boolean} True if value is a URLSearchParams object, otherwise false + */ +function isURLSearchParams(val) { + return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; +} + +/** + * Trim excess whitespace off the beginning and end of a string + * + * @param {String} str The String to trim + * @returns {String} The String freed of excess whitespace + */ +function trim(str) { + return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); +} + +/** + * Determine if we're running in a standard browser environment + * + * This allows axios to run in a web worker, and react-native. + * Both environments support XMLHttpRequest, but not fully standard globals. + * + * web workers: + * typeof window -> undefined + * typeof document -> undefined + * + * react-native: + * navigator.product -> 'ReactNative' + * nativescript + * navigator.product -> 'NativeScript' or 'NS' + */ +function isStandardBrowserEnv() { + if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || + navigator.product === 'NativeScript' || + navigator.product === 'NS')) { + return false; + } + return ( + typeof window !== 'undefined' && + typeof document !== 'undefined' + ); +} + +/** + * Iterate over an Array or an Object invoking a function for each item. + * + * If `obj` is an Array callback will be called passing + * the value, index, and complete array for each item. + * + * If 'obj' is an Object callback will be called passing + * the value, key, and complete object for each property. + * + * @param {Object|Array} obj The object to iterate + * @param {Function} fn The callback to invoke for each item + */ +function forEach(obj, fn) { + // Don't bother if no value provided + if (obj === null || typeof obj === 'undefined') { + return; + } + + // Force an array if not already something iterable + if (typeof obj !== 'object') { + /*eslint no-param-reassign:0*/ + obj = [obj]; + } + + if (isArray(obj)) { + // Iterate over array values + for (var i = 0, l = obj.length; i < l; i++) { + fn.call(null, obj[i], i, obj); + } + } else { + // Iterate over object keys + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn.call(null, obj[key], key, obj); + } + } + } +} + +/** + * Accepts varargs expecting each argument to be an object, then + * immutably merges the properties of each object and returns result. + * + * When multiple objects contain the same key the later object in + * the arguments list will take precedence. + * + * Example: + * + * ```js + * var result = merge({foo: 123}, {foo: 456}); + * console.log(result.foo); // outputs 456 + * ``` + * + * @param {Object} obj1 Object to merge + * @returns {Object} Result of all merge properties + */ +function merge(/* obj1, obj2, obj3, ... */) { + var result = {}; + function assignValue(val, key) { + if (isPlainObject(result[key]) && isPlainObject(val)) { + result[key] = merge(result[key], val); + } else if (isPlainObject(val)) { + result[key] = merge({}, val); + } else if (isArray(val)) { + result[key] = val.slice(); + } else { + result[key] = val; + } + } + + for (var i = 0, l = arguments.length; i < l; i++) { + forEach(arguments[i], assignValue); + } + return result; +} + +/** + * Extends object a by mutably adding to it the properties of object b. + * + * @param {Object} a The object to be extended + * @param {Object} b The object to copy properties from + * @param {Object} thisArg The object to bind function to + * @return {Object} The resulting value of object a + */ +function extend(a, b, thisArg) { + forEach(b, function assignValue(val, key) { + if (thisArg && typeof val === 'function') { + a[key] = bind(val, thisArg); + } else { + a[key] = val; + } + }); + return a; +} + +/** + * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) + * + * @param {string} content with BOM + * @return {string} content value without BOM + */ +function stripBOM(content) { + if (content.charCodeAt(0) === 0xFEFF) { + content = content.slice(1); + } + return content; +} + +module.exports = { + isArray: isArray, + isArrayBuffer: isArrayBuffer, + isBuffer: isBuffer, + isFormData: isFormData, + isArrayBufferView: isArrayBufferView, + isString: isString, + isNumber: isNumber, + isObject: isObject, + isPlainObject: isPlainObject, + isUndefined: isUndefined, + isDate: isDate, + isFile: isFile, + isBlob: isBlob, + isFunction: isFunction, + isStream: isStream, + isURLSearchParams: isURLSearchParams, + isStandardBrowserEnv: isStandardBrowserEnv, + forEach: forEach, + merge: merge, + extend: extend, + trim: trim, + stripBOM: stripBOM +}; diff --git a/node_modules/axios/package.json b/node_modules/axios/package.json new file mode 100644 index 0000000..9762f34 --- /dev/null +++ b/node_modules/axios/package.json @@ -0,0 +1,111 @@ +{ + "_from": "axios@0.21.4", + "_id": "axios@0.21.4", + "_inBundle": false, + "_integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", + "_location": "/axios", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "axios@0.21.4", + "name": "axios", + "escapedName": "axios", + "rawSpec": "0.21.4", + "saveSpec": null, + "fetchSpec": "0.21.4" + }, + "_requiredBy": [ + "/getstream" + ], + "_resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", + "_shasum": "c67b90dc0568e5c1cf2b0b858c43ba28e2eda575", + "_spec": "axios@0.21.4", + "_where": "/home/other/discord_bot/node_modules/getstream", + "author": { + "name": "Matt Zabriskie" + }, + "browser": { + "./lib/adapters/http.js": "./lib/adapters/xhr.js" + }, + "bugs": { + "url": "https://github.com/axios/axios/issues" + }, + "bundleDependencies": false, + "bundlesize": [ + { + "path": "./dist/axios.min.js", + "threshold": "5kB" + } + ], + "dependencies": { + "follow-redirects": "^1.14.0" + }, + "deprecated": false, + "description": "Promise based HTTP client for the browser and node.js", + "devDependencies": { + "coveralls": "^3.0.0", + "es6-promise": "^4.2.4", + "grunt": "^1.3.0", + "grunt-banner": "^0.6.0", + "grunt-cli": "^1.2.0", + "grunt-contrib-clean": "^1.1.0", + "grunt-contrib-watch": "^1.0.0", + "grunt-eslint": "^23.0.0", + "grunt-karma": "^4.0.0", + "grunt-mocha-test": "^0.13.3", + "grunt-ts": "^6.0.0-beta.19", + "grunt-webpack": "^4.0.2", + "istanbul-instrumenter-loader": "^1.0.0", + "jasmine-core": "^2.4.1", + "karma": "^6.3.2", + "karma-chrome-launcher": "^3.1.0", + "karma-firefox-launcher": "^2.1.0", + "karma-jasmine": "^1.1.1", + "karma-jasmine-ajax": "^0.1.13", + "karma-safari-launcher": "^1.0.0", + "karma-sauce-launcher": "^4.3.6", + "karma-sinon": "^1.0.5", + "karma-sourcemap-loader": "^0.3.8", + "karma-webpack": "^4.0.2", + "load-grunt-tasks": "^3.5.2", + "minimist": "^1.2.0", + "mocha": "^8.2.1", + "sinon": "^4.5.0", + "terser-webpack-plugin": "^4.2.3", + "typescript": "^4.0.5", + "url-search-params": "^0.10.0", + "webpack": "^4.44.2", + "webpack-dev-server": "^3.11.0" + }, + "homepage": "https://axios-http.com", + "jsdelivr": "dist/axios.min.js", + "keywords": [ + "xhr", + "http", + "ajax", + "promise", + "node" + ], + "license": "MIT", + "main": "index.js", + "name": "axios", + "repository": { + "type": "git", + "url": "git+https://github.com/axios/axios.git" + }, + "scripts": { + "build": "NODE_ENV=production grunt build", + "coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js", + "examples": "node ./examples/server.js", + "fix": "eslint --fix lib/**/*.js", + "postversion": "git push && git push --tags", + "preversion": "npm test", + "start": "node ./sandbox/server.js", + "test": "grunt test", + "version": "npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json" + }, + "typings": "./index.d.ts", + "unpkg": "dist/axios.min.js", + "version": "0.21.4" +} diff --git a/node_modules/balanced-match/.github/FUNDING.yml b/node_modules/balanced-match/.github/FUNDING.yml new file mode 100644 index 0000000..cea8b16 --- /dev/null +++ b/node_modules/balanced-match/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/balanced-match" +patreon: juliangruber diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +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/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000..d2a48b6 --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,97 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +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/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000..c67a646 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,62 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000..8cb8862 --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,79 @@ +{ + "_args": [ + [ + "balanced-match@1.0.2", + "/home/other/discord_bot" + ] + ], + "_from": "balanced-match@1.0.2", + "_id": "balanced-match@1.0.2", + "_inBundle": false, + "_integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "_location": "/balanced-match", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "balanced-match@1.0.2", + "name": "balanced-match", + "escapedName": "balanced-match", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/brace-expansion" + ], + "_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "_spec": "1.0.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/balanced-match/issues" + }, + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "license": "MIT", + "main": "index.js", + "name": "balanced-match", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "scripts": { + "bench": "matcha test/bench.js", + "test": "tape test/test.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.0.2" +} diff --git a/node_modules/binary-extensions/binary-extensions.json b/node_modules/binary-extensions/binary-extensions.json new file mode 100644 index 0000000..4aab383 --- /dev/null +++ b/node_modules/binary-extensions/binary-extensions.json @@ -0,0 +1,260 @@ +[ + "3dm", + "3ds", + "3g2", + "3gp", + "7z", + "a", + "aac", + "adp", + "ai", + "aif", + "aiff", + "alz", + "ape", + "apk", + "appimage", + "ar", + "arj", + "asf", + "au", + "avi", + "bak", + "baml", + "bh", + "bin", + "bk", + "bmp", + "btif", + "bz2", + "bzip2", + "cab", + "caf", + "cgm", + "class", + "cmx", + "cpio", + "cr2", + "cur", + "dat", + "dcm", + "deb", + "dex", + "djvu", + "dll", + "dmg", + "dng", + "doc", + "docm", + "docx", + "dot", + "dotm", + "dra", + "DS_Store", + "dsk", + "dts", + "dtshd", + "dvb", + "dwg", + "dxf", + "ecelp4800", + "ecelp7470", + "ecelp9600", + "egg", + "eol", + "eot", + "epub", + "exe", + "f4v", + "fbs", + "fh", + "fla", + "flac", + "flatpak", + "fli", + "flv", + "fpx", + "fst", + "fvt", + "g3", + "gh", + "gif", + "graffle", + "gz", + "gzip", + "h261", + "h263", + "h264", + "icns", + "ico", + "ief", + "img", + "ipa", + "iso", + "jar", + "jpeg", + "jpg", + "jpgv", + "jpm", + "jxr", + "key", + "ktx", + "lha", + "lib", + "lvp", + "lz", + "lzh", + "lzma", + "lzo", + "m3u", + "m4a", + "m4v", + "mar", + "mdi", + "mht", + "mid", + "midi", + "mj2", + "mka", + "mkv", + "mmr", + "mng", + "mobi", + "mov", + "movie", + "mp3", + "mp4", + "mp4a", + "mpeg", + "mpg", + "mpga", + "mxu", + "nef", + "npx", + "numbers", + "nupkg", + "o", + "odp", + "ods", + "odt", + "oga", + "ogg", + "ogv", + "otf", + "ott", + "pages", + "pbm", + "pcx", + "pdb", + "pdf", + "pea", + "pgm", + "pic", + "png", + "pnm", + "pot", + "potm", + "potx", + "ppa", + "ppam", + "ppm", + "pps", + "ppsm", + "ppsx", + "ppt", + "pptm", + "pptx", + "psd", + "pya", + "pyc", + "pyo", + "pyv", + "qt", + "rar", + "ras", + "raw", + "resources", + "rgb", + "rip", + "rlc", + "rmf", + "rmvb", + "rpm", + "rtf", + "rz", + "s3m", + "s7z", + "scpt", + "sgi", + "shar", + "snap", + "sil", + "sketch", + "slk", + "smv", + "snk", + "so", + "stl", + "suo", + "sub", + "swf", + "tar", + "tbz", + "tbz2", + "tga", + "tgz", + "thmx", + "tif", + "tiff", + "tlz", + "ttc", + "ttf", + "txz", + "udf", + "uvh", + "uvi", + "uvm", + "uvp", + "uvs", + "uvu", + "viv", + "vob", + "war", + "wav", + "wax", + "wbmp", + "wdp", + "weba", + "webm", + "webp", + "whl", + "wim", + "wm", + "wma", + "wmv", + "wmx", + "woff", + "woff2", + "wrm", + "wvx", + "xbm", + "xif", + "xla", + "xlam", + "xls", + "xlsb", + "xlsm", + "xlsx", + "xlt", + "xltm", + "xltx", + "xm", + "xmind", + "xpi", + "xpm", + "xwd", + "xz", + "z", + "zip", + "zipx" +] diff --git a/node_modules/binary-extensions/binary-extensions.json.d.ts b/node_modules/binary-extensions/binary-extensions.json.d.ts new file mode 100644 index 0000000..94a248c --- /dev/null +++ b/node_modules/binary-extensions/binary-extensions.json.d.ts @@ -0,0 +1,3 @@ +declare const binaryExtensionsJson: readonly string[]; + +export = binaryExtensionsJson; diff --git a/node_modules/binary-extensions/index.d.ts b/node_modules/binary-extensions/index.d.ts new file mode 100644 index 0000000..f469ac5 --- /dev/null +++ b/node_modules/binary-extensions/index.d.ts @@ -0,0 +1,14 @@ +/** +List of binary file extensions. + +@example +``` +import binaryExtensions = require('binary-extensions'); + +console.log(binaryExtensions); +//=> ['3ds', '3g2', …] +``` +*/ +declare const binaryExtensions: readonly string[]; + +export = binaryExtensions; diff --git a/node_modules/binary-extensions/index.js b/node_modules/binary-extensions/index.js new file mode 100644 index 0000000..d46e468 --- /dev/null +++ b/node_modules/binary-extensions/index.js @@ -0,0 +1 @@ +module.exports = require('./binary-extensions.json'); diff --git a/node_modules/binary-extensions/license b/node_modules/binary-extensions/license new file mode 100644 index 0000000..401b1c7 --- /dev/null +++ b/node_modules/binary-extensions/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), Paul Miller (https://paulmillr.com) + +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/binary-extensions/package.json b/node_modules/binary-extensions/package.json new file mode 100644 index 0000000..6e15408 --- /dev/null +++ b/node_modules/binary-extensions/package.json @@ -0,0 +1,73 @@ +{ + "_args": [ + [ + "binary-extensions@2.2.0", + "/home/other/discord_bot" + ] + ], + "_from": "binary-extensions@2.2.0", + "_id": "binary-extensions@2.2.0", + "_inBundle": false, + "_integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "_location": "/binary-extensions", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "binary-extensions@2.2.0", + "name": "binary-extensions", + "escapedName": "binary-extensions", + "rawSpec": "2.2.0", + "saveSpec": null, + "fetchSpec": "2.2.0" + }, + "_requiredBy": [ + "/is-binary-path" + ], + "_resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "_spec": "2.2.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/binary-extensions/issues" + }, + "description": "List of binary file extensions", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts", + "binary-extensions.json", + "binary-extensions.json.d.ts" + ], + "homepage": "https://github.com/sindresorhus/binary-extensions#readme", + "keywords": [ + "binary", + "extensions", + "extension", + "file", + "json", + "list", + "array" + ], + "license": "MIT", + "name": "binary-extensions", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/binary-extensions.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.2.0" +} diff --git a/node_modules/binary-extensions/readme.md b/node_modules/binary-extensions/readme.md new file mode 100644 index 0000000..3e25dd8 --- /dev/null +++ b/node_modules/binary-extensions/readme.md @@ -0,0 +1,41 @@ +# binary-extensions + +> List of binary file extensions + +The list is just a [JSON file](binary-extensions.json) and can be used anywhere. + + +## Install + +``` +$ npm install binary-extensions +``` + + +## Usage + +```js +const binaryExtensions = require('binary-extensions'); + +console.log(binaryExtensions); +//=> ['3ds', '3g2', …] +``` + + +## Related + +- [is-binary-path](https://github.com/sindresorhus/is-binary-path) - Check if a filepath is a binary file +- [text-extensions](https://github.com/sindresorhus/text-extensions) - List of text file extensions + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/boxen/index.d.ts b/node_modules/boxen/index.d.ts new file mode 100644 index 0000000..69ebd42 --- /dev/null +++ b/node_modules/boxen/index.d.ts @@ -0,0 +1,200 @@ +import {LiteralUnion} from 'type-fest'; +import {BoxStyle, Boxes} from 'cli-boxes'; + +declare namespace boxen { + /** + Characters used for custom border. + + @example + ``` + // affffb + // e e + // dffffc + + const border: CustomBorderStyle = { + topLeft: 'a', + topRight: 'b', + bottomRight: 'c', + bottomLeft: 'd', + vertical: 'e', + horizontal: 'f' + }; + ``` + */ + interface CustomBorderStyle extends BoxStyle {} + + /** + Spacing used for `padding` and `margin`. + */ + interface Spacing { + readonly top: number; + readonly right: number; + readonly bottom: number; + readonly left: number; + } + + interface Options { + /** + Color of the box border. + */ + readonly borderColor?: LiteralUnion< + | 'black' + | 'red' + | 'green' + | 'yellow' + | 'blue' + | 'magenta' + | 'cyan' + | 'white' + | 'gray' + | 'grey' + | 'blackBright' + | 'redBright' + | 'greenBright' + | 'yellowBright' + | 'blueBright' + | 'magentaBright' + | 'cyanBright' + | 'whiteBright', + string + >; + + /** + Style of the box border. + + @default 'single' + */ + readonly borderStyle?: keyof Boxes | CustomBorderStyle; + + /** + Reduce opacity of the border. + + @default false + */ + readonly dimBorder?: boolean; + + /** + Space between the text and box border. + + @default 0 + */ + readonly padding?: number | Spacing; + + /** + Space around the box. + + @default 0 + */ + readonly margin?: number | Spacing; + + /** + Float the box on the available terminal screen space. + + @default 'left' + */ + readonly float?: 'left' | 'right' | 'center'; + + /** + Color of the background. + */ + readonly backgroundColor?: LiteralUnion< + | 'black' + | 'red' + | 'green' + | 'yellow' + | 'blue' + | 'magenta' + | 'cyan' + | 'white' + | 'blackBright' + | 'redBright' + | 'greenBright' + | 'yellowBright' + | 'blueBright' + | 'magentaBright' + | 'cyanBright' + | 'whiteBright', + string + >; + + /** + Align the text in the box based on the widest line. + + @default 'left' + @deprecated Use `textAlignment` instead. + */ + readonly align?: 'left' | 'right' | 'center'; + + /** + Align the text in the box based on the widest line. + + @default 'left' + */ + readonly textAlignment?: 'left' | 'right' | 'center'; + + /** + Display a title at the top of the box. + If needed, the box will horizontally expand to fit the title. + + @example + ``` + console.log(boxen('foo bar', {title: 'example'})); + // ┌ example ┐ + // │foo bar │ + // └─────────┘ + ``` + */ + readonly title?: string; + + /** + Align the title in the top bar. + + @default 'left' + + @example + ``` + console.log(boxen('foo bar foo bar', {title: 'example', titleAlignment: 'center'})); + // ┌─── example ───┐ + // │foo bar foo bar│ + // └───────────────┘ + + console.log(boxen('foo bar foo bar', {title: 'example', titleAlignment: 'right'})); + // ┌────── example ┐ + // │foo bar foo bar│ + // └───────────────┘ + ``` + */ + readonly titleAlignment?: 'left' | 'right' | 'center'; + } +} + +/** +Creates a box in the terminal. + +@param text - The text inside the box. +@returns The box. + +@example +``` +import boxen = require('boxen'); + +console.log(boxen('unicorn', {padding: 1})); +// ┌─────────────┐ +// │ │ +// │ unicorn │ +// │ │ +// └─────────────┘ + +console.log(boxen('unicorn', {padding: 1, margin: 1, borderStyle: 'double'})); +// +// ╔═════════════╗ +// ║ ║ +// ║ unicorn ║ +// ║ ║ +// ╚═════════════╝ +// +``` +*/ +declare const boxen: (text: string, options?: boxen.Options) => string; + +export = boxen; diff --git a/node_modules/boxen/index.js b/node_modules/boxen/index.js new file mode 100644 index 0000000..d6bc693 --- /dev/null +++ b/node_modules/boxen/index.js @@ -0,0 +1,279 @@ +'use strict'; +const stringWidth = require('string-width'); +const chalk = require('chalk'); +const widestLine = require('widest-line'); +const cliBoxes = require('cli-boxes'); +const camelCase = require('camelcase'); +const ansiAlign = require('ansi-align'); +const wrapAnsi = require('wrap-ansi'); + +const NL = '\n'; +const PAD = ' '; + +const terminalColumns = () => { + const {env, stdout, stderr} = process; + + if (stdout && stdout.columns) { + return stdout.columns; + } + + if (stderr && stderr.columns) { + return stderr.columns; + } + + if (env.COLUMNS) { + return Number.parseInt(env.COLUMNS, 10); + } + + return 80; +}; + +const getObject = detail => { + return typeof detail === 'number' ? { + top: detail, + right: detail * 3, + bottom: detail, + left: detail * 3 + } : { + top: 0, + right: 0, + bottom: 0, + left: 0, + ...detail + }; +}; + +const getBorderChars = borderStyle => { + const sides = [ + 'topLeft', + 'topRight', + 'bottomRight', + 'bottomLeft', + 'vertical', + 'horizontal' + ]; + + let chararacters; + + if (typeof borderStyle === 'string') { + chararacters = cliBoxes[borderStyle]; + + if (!chararacters) { + throw new TypeError(`Invalid border style: ${borderStyle}`); + } + } else { + for (const side of sides) { + if (!borderStyle[side] || typeof borderStyle[side] !== 'string') { + throw new TypeError(`Invalid border style: ${side}`); + } + } + + chararacters = borderStyle; + } + + return chararacters; +}; + +const makeTitle = (text, horizontal, alignement) => { + let title = ''; + + const textWidth = stringWidth(text); + + switch (alignement) { + case 'left': + title = text + horizontal.slice(textWidth); + break; + case 'right': + title = horizontal.slice(textWidth) + text; + break; + default: + horizontal = horizontal.slice(textWidth); + + if (horizontal.length % 2 === 1) { // This is needed in case the length is odd + horizontal = horizontal.slice(Math.floor(horizontal.length / 2)); + title = horizontal.slice(1) + text + horizontal; // We reduce the left part of one character to avoid the bar to go beyond its limit + } else { + horizontal = horizontal.slice(horizontal.length / 2); + title = horizontal + text + horizontal; + } + + break; + } + + return title; +}; + +const makeContentText = (text, padding, columns, align) => { + text = ansiAlign(text, {align}); + let lines = text.split(NL); + const textWidth = widestLine(text); + + const max = columns - padding.left - padding.right; + + if (textWidth > max) { + const newLines = []; + for (const line of lines) { + const createdLines = wrapAnsi(line, max, {hard: true}); + const alignedLines = ansiAlign(createdLines, {align}); + const alignedLinesArray = alignedLines.split('\n'); + const longestLength = Math.max(...alignedLinesArray.map(s => stringWidth(s))); + + for (const alignedLine of alignedLinesArray) { + let paddedLine; + switch (align) { + case 'center': + paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine; + break; + case 'right': + paddedLine = PAD.repeat(max - longestLength) + alignedLine; + break; + default: + paddedLine = alignedLine; + break; + } + + newLines.push(paddedLine); + } + } + + lines = newLines; + } + + if (align === 'center' && textWidth < max) { + lines = lines.map(line => PAD.repeat((max - textWidth) / 2) + line); + } else if (align === 'right' && textWidth < max) { + lines = lines.map(line => PAD.repeat(max - textWidth) + line); + } + + const paddingLeft = PAD.repeat(padding.left); + const paddingRight = PAD.repeat(padding.right); + + lines = lines.map(line => paddingLeft + line + paddingRight); + + lines = lines.map(line => { + if (columns - stringWidth(line) > 0) { + switch (align) { + case 'center': + return line + PAD.repeat(columns - stringWidth(line)); + case 'right': + return line + PAD.repeat(columns - stringWidth(line)); + default: + return line + PAD.repeat(columns - stringWidth(line)); + } + } + + return line; + }); + + if (padding.top > 0) { + lines = new Array(padding.top).fill(PAD.repeat(columns)).concat(lines); + } + + if (padding.bottom > 0) { + lines = lines.concat(new Array(padding.bottom).fill(PAD.repeat(columns))); + } + + return lines.join(NL); +}; + +const isHex = color => color.match(/^#(?:[0-f]{3}){1,2}$/i); +const isColorValid = color => typeof color === 'string' && ((chalk[color]) || isHex(color)); +const getColorFn = color => isHex(color) ? chalk.hex(color) : chalk[color]; +const getBGColorFn = color => isHex(color) ? chalk.bgHex(color) : chalk[camelCase(['bg', color])]; + +module.exports = (text, options) => { + options = { + padding: 0, + borderStyle: 'single', + dimBorder: false, + textAlignment: 'left', + float: 'left', + titleAlignment: 'left', + ...options + }; + + // This option is deprecated + if (options.align) { + options.textAlignment = options.align; + } + + const BORDERS_WIDTH = 2; + + if (options.borderColor && !isColorValid(options.borderColor)) { + throw new Error(`${options.borderColor} is not a valid borderColor`); + } + + if (options.backgroundColor && !isColorValid(options.backgroundColor)) { + throw new Error(`${options.backgroundColor} is not a valid backgroundColor`); + } + + const chars = getBorderChars(options.borderStyle); + const padding = getObject(options.padding); + const margin = getObject(options.margin); + + const colorizeBorder = border => { + const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border; + return options.dimBorder ? chalk.dim(newBorder) : newBorder; + }; + + const colorizeContent = content => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content; + + const columns = terminalColumns(); + + let contentWidth = widestLine(wrapAnsi(text, columns - BORDERS_WIDTH, {hard: true, trim: false})) + padding.left + padding.right; + + // This prevents the title bar to exceed the console's width + let title = options.title && options.title.slice(0, columns - 4 - margin.left - margin.right); + + if (title) { + title = ` ${title} `; + // Make the box larger to fit a larger title + if (stringWidth(title) > contentWidth) { + contentWidth = stringWidth(title); + } + } + + if ((margin.left && margin.right) && contentWidth + BORDERS_WIDTH + margin.left + margin.right > columns) { + // Let's assume we have margins: left = 3, right = 5, in total = 8 + const spaceForMargins = columns - contentWidth - BORDERS_WIDTH; + // Let's assume we have space = 4 + const multiplier = spaceForMargins / (margin.left + margin.right); + // Here: multiplier = 4/8 = 0.5 + margin.left = Math.max(0, Math.floor(margin.left * multiplier)); + margin.right = Math.max(0, Math.floor(margin.right * multiplier)); + // Left: 3 * 0.5 = 1.5 -> 1 + // Right: 6 * 0.5 = 3 + } + + // Prevent content from exceeding the console's width + contentWidth = Math.min(contentWidth, columns - BORDERS_WIDTH - margin.left - margin.right); + + text = makeContentText(text, padding, contentWidth, options.textAlignment); + + let marginLeft = PAD.repeat(margin.left); + + if (options.float === 'center') { + const marginWidth = Math.max((columns - contentWidth - BORDERS_WIDTH) / 2, 0); + marginLeft = PAD.repeat(marginWidth); + } else if (options.float === 'right') { + const marginWidth = Math.max(columns - contentWidth - margin.right - BORDERS_WIDTH, 0); + marginLeft = PAD.repeat(marginWidth); + } + + const horizontal = chars.horizontal.repeat(contentWidth); + const top = colorizeBorder(NL.repeat(margin.top) + marginLeft + chars.topLeft + (title ? makeTitle(title, horizontal, options.titleAlignment) : horizontal) + chars.topRight); + const bottom = colorizeBorder(marginLeft + chars.bottomLeft + horizontal + chars.bottomRight + NL.repeat(margin.bottom)); + const side = colorizeBorder(chars.vertical); + + const LINE_SEPARATOR = (contentWidth + BORDERS_WIDTH + margin.left >= columns) ? '' : NL; + + const lines = text.split(NL); + + const middle = lines.map(line => { + return marginLeft + side + colorizeContent(line) + side; + }).join(LINE_SEPARATOR); + + return top + LINE_SEPARATOR + middle + LINE_SEPARATOR + bottom; +}; + +module.exports._borderStyles = cliBoxes; diff --git a/node_modules/boxen/license b/node_modules/boxen/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/boxen/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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/boxen/package.json b/node_modules/boxen/package.json new file mode 100644 index 0000000..d1802b0 --- /dev/null +++ b/node_modules/boxen/package.json @@ -0,0 +1,83 @@ +{ + "_from": "boxen@5.1.2", + "_id": "boxen@5.1.2", + "_inBundle": false, + "_integrity": "sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==", + "_location": "/boxen", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "boxen@5.1.2", + "name": "boxen", + "escapedName": "boxen", + "rawSpec": "5.1.2", + "saveSpec": null, + "fetchSpec": "5.1.2" + }, + "_requiredBy": [ + "/update-notifier" + ], + "_resolved": "https://registry.npmjs.org/boxen/-/boxen-5.1.2.tgz", + "_shasum": "788cb686fc83c1f486dfa8a40c68fc2b831d2b50", + "_spec": "boxen@5.1.2", + "_where": "/home/other/discord_bot/node_modules/update-notifier", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/boxen/issues" + }, + "bundleDependencies": false, + "dependencies": { + "ansi-align": "^3.0.0", + "camelcase": "^6.2.0", + "chalk": "^4.1.0", + "cli-boxes": "^2.2.1", + "string-width": "^4.2.2", + "type-fest": "^0.20.2", + "widest-line": "^3.1.0", + "wrap-ansi": "^7.0.0" + }, + "deprecated": false, + "description": "Create boxes in the terminal", + "devDependencies": { + "ava": "^2.4.0", + "nyc": "^15.1.0", + "tsd": "^0.14.0", + "xo": "^0.36.1" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/boxen#readme", + "keywords": [ + "cli", + "box", + "boxes", + "terminal", + "term", + "console", + "ascii", + "unicode", + "border", + "text" + ], + "license": "MIT", + "name": "boxen", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/boxen.git" + }, + "scripts": { + "test": "xo && nyc ava && tsd" + }, + "version": "5.1.2" +} diff --git a/node_modules/boxen/readme.md b/node_modules/boxen/readme.md new file mode 100644 index 0000000..c7ed496 --- /dev/null +++ b/node_modules/boxen/readme.md @@ -0,0 +1,244 @@ +# boxen + +> Create boxes in the terminal + +![](screenshot.png) + +## Install + +``` +$ npm install boxen +``` + +## Usage + +```js +const boxen = require('boxen'); + +console.log(boxen('unicorn', {padding: 1})); +/* +┌─────────────┐ +│ │ +│ unicorn │ +│ │ +└─────────────┘ +*/ + +console.log(boxen('unicorn', {padding: 1, margin: 1, borderStyle: 'double'})); +/* + + ╔═════════════╗ + ║ ║ + ║ unicorn ║ + ║ ║ + ╚═════════════╝ + +*/ + +console.log(boxen('unicorns love rainbows', {title: 'magical', titleAlignment: 'center'})); +/* +┌────── magical ───────┐ +│unicorns love rainbows│ +└──────────────────────┘ +*/ +``` + +## API + +### boxen(text, options?) + +#### text + +Type: `string` + +Text inside the box. + +#### options + +Type: `object` + +##### borderColor + +Type: `string`\ +Values: `'black'` `'red'` `'green'` `'yellow'` `'blue'` `'magenta'` `'cyan'` `'white'` `'gray'` or a hex value like `'#ff0000'` + +Color of the box border. + +##### borderStyle + +Type: `string | object`\ +Default: `'single'`\ +Values: +- `'single'` +``` +┌───┐ +│foo│ +└───┘ +``` +- `'double'` +``` +╔═══╗ +║foo║ +╚═══╝ +``` +- `'round'` (`'single'` sides with round corners) +``` +╭───╮ +│foo│ +╰───╯ +``` +- `'bold'` +``` +┏━━━┓ +┃foo┃ +┗━━━┛ +``` +- `'singleDouble'` (`'single'` on top and bottom, `'double'` on right and left) +``` +╓───╖ +║foo║ +╙───╜ +``` +- `'doubleSingle'` (`'double'` on top and bottom, `'single'` on right and left) +``` +╒═══╕ +│foo│ +╘═══╛ +``` +- `'classic'` +``` ++---+ +|foo| ++---+ +``` + +Style of the box border. + +Can be any of the above predefined styles or an object with the following keys: + +```js +{ + topLeft: '+', + topRight: '+', + bottomLeft: '+', + bottomRight: '+', + horizontal: '-', + vertical: '|' +} +``` + +##### dimBorder + +Type: `boolean`\ +Default: `false` + +Reduce opacity of the border. + +##### title + +Type: `string` + +Display a title at the top of the box. +If needed, the box will horizontally expand to fit the title. + +Example: +```js +console.log(boxen('foo bar', {title: 'example'})); +/* +┌ example ┐ +│foo bar │ +└─────────┘ +*/ +``` + +##### titleAlignment + +Type: `string`\ +Default: `'left'` + +Align the title in the top bar. + +Values: +- `'left'` +```js +/* +┌ example ──────┐ +│foo bar foo bar│ +└───────────────┘ +*/ +``` +- `'center'` +```js +/* +┌─── example ───┐ +│foo bar foo bar│ +└───────────────┘ +*/ +``` +- `'right'` +```js +/* +┌────── example ┐ +│foo bar foo bar│ +└───────────────┘ +*/ +``` + +##### padding + +Type: `number | object`\ +Default: `0` + +Space between the text and box border. + +Accepts a number or an object with any of the `top`, `right`, `bottom`, `left` properties. When a number is specified, the left/right padding is 3 times the top/bottom to make it look nice. + +##### margin + +Type: `number | object`\ +Default: `0` + +Space around the box. + +Accepts a number or an object with any of the `top`, `right`, `bottom`, `left` properties. When a number is specified, the left/right margin is 3 times the top/bottom to make it look nice. + +##### float + +Type: `string`\ +Default: `'left'`\ +Values: `'right'` `'center'` `'left'` + +Float the box on the available terminal screen space. + +##### backgroundColor + +Type: `string`\ +Values: `'black'` `'red'` `'green'` `'yellow'` `'blue'` `'magenta'` `'cyan'` `'white'` `'gray'` or a hex value like `'#ff0000'` + +Color of the background. + +##### textAlignment + +Type: `string`\ +Default: `'left'`\ +Values: `'left'` `'center'` `'right'` + +Align the text in the box based on the widest line. + +## Related + +- [boxen-cli](https://github.com/sindresorhus/boxen-cli) - CLI for this module +- [cli-boxes](https://github.com/sindresorhus/cli-boxes) - Boxes for use in the terminal +- [ink-box](https://github.com/sindresorhus/ink-box) - Box component for Ink that uses this package + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +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/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..6b4e0e1 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +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/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..0478be8 --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..ef82bc6 --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "brace-expansion@1.1.11", + "/home/other/discord_bot" + ] + ], + "_from": "brace-expansion@1.1.11", + "_id": "brace-expansion@1.1.11", + "_inBundle": false, + "_integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "_location": "/brace-expansion", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "brace-expansion@1.1.11", + "name": "brace-expansion", + "escapedName": "brace-expansion", + "rawSpec": "1.1.11", + "saveSpec": null, + "fetchSpec": "1.1.11" + }, + "_requiredBy": [ + "/minimatch" + ], + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "_spec": "1.1.11", + "_where": "/home/other/discord_bot", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/brace-expansion/issues" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "description": "Brace expansion as known from sh/bash", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "keywords": [], + "license": "MIT", + "main": "index.js", + "name": "brace-expansion", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "scripts": { + "bench": "matcha test/perf/bench.js", + "gentest": "bash test/generate.sh", + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.1.11" +} diff --git a/node_modules/braces/CHANGELOG.md b/node_modules/braces/CHANGELOG.md new file mode 100644 index 0000000..36f798b --- /dev/null +++ b/node_modules/braces/CHANGELOG.md @@ -0,0 +1,184 @@ +# Release history + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +
+ Guiding Principles + +- Changelogs are for humans, not machines. +- There should be an entry for every single version. +- The same types of changes should be grouped. +- Versions and sections should be linkable. +- The latest version comes first. +- The release date of each versions is displayed. +- Mention whether you follow Semantic Versioning. + +
+ +
+ Types of changes + +Changelog entries are classified using the following labels _(from [keep-a-changelog](http://keepachangelog.com/)_): + +- `Added` for new features. +- `Changed` for changes in existing functionality. +- `Deprecated` for soon-to-be removed features. +- `Removed` for now removed features. +- `Fixed` for any bug fixes. +- `Security` in case of vulnerabilities. + +
+ +## [3.0.0] - 2018-04-08 + +v3.0 is a complete refactor, resulting in a faster, smaller codebase, with fewer deps, and a more accurate parser and compiler. + +**Breaking Changes** + +- The undocumented `.makeRe` method was removed + +**Non-breaking changes** + +- Caching was removed + +## [2.3.2] - 2018-04-08 + +- start refactoring +- cover sets +- better range handling + +## [2.3.1] - 2018-02-17 + +- Remove unnecessary escape in Regex. (#14) + +## [2.3.0] - 2017-10-19 + +- minor code reorganization +- optimize regex +- expose `maxLength` option + +## [2.2.1] - 2017-05-30 + +- don't condense when braces contain extglobs + +## [2.2.0] - 2017-05-28 + +- ensure word boundaries are preserved +- fixes edge case where extglob characters precede a brace pattern + +## [2.1.1] - 2017-04-27 + +- use snapdragon-node +- handle edge case +- optimizations, lint + +## [2.0.4] - 2017-04-11 + +- pass opts to compiler +- minor optimization in create method +- re-write parser handlers to remove negation regex + +## [2.0.3] - 2016-12-10 + +- use split-string +- clear queue at the end +- adds sequences example +- add unit tests + +## [2.0.2] - 2016-10-21 + +- fix comma handling in nested extglobs + +## [2.0.1] - 2016-10-20 + +- add comments +- more tests, ensure quotes are stripped + +## [2.0.0] - 2016-10-19 + +- don't expand braces inside character classes +- add quantifier pattern + +## [1.8.5] - 2016-05-21 + +- Refactor (#10) + +## [1.8.4] - 2016-04-20 + +- fixes https://github.com/jonschlinkert/micromatch/issues/66 + +## [1.8.0] - 2015-03-18 + +- adds exponent examples, tests +- fixes the first example in https://github.com/jonschlinkert/micromatch/issues/38 + +## [1.6.0] - 2015-01-30 + +- optimizations, `bash` mode: +- improve path escaping + +## [1.5.0] - 2015-01-28 + +- Merge pull request #5 from eush77/lib-files + +## [1.4.0] - 2015-01-24 + +- add extglob tests +- externalize exponent function +- better whitespace handling + +## [1.3.0] - 2015-01-24 + +- make regex patterns explicity + +## [1.1.0] - 2015-01-11 + +- don't create a match group with `makeRe` + +## [1.0.0] - 2014-12-23 + +- Merge commit '97b05f5544f8348736a8efaecf5c32bbe3e2ad6e' +- support empty brace syntax +- better bash coverage +- better support for regex strings + +## [0.1.4] - 2014-11-14 + +- improve recognition of bad args, recognize mismatched argument types +- support escaping +- remove pathname-expansion +- support whitespace in patterns + +## [0.1.0] + +- first commit + +[2.3.2]: https://github.com/micromatch/braces/compare/2.3.1...2.3.2 +[2.3.1]: https://github.com/micromatch/braces/compare/2.3.0...2.3.1 +[2.3.0]: https://github.com/micromatch/braces/compare/2.2.1...2.3.0 +[2.2.1]: https://github.com/micromatch/braces/compare/2.2.0...2.2.1 +[2.2.0]: https://github.com/micromatch/braces/compare/2.1.1...2.2.0 +[2.1.1]: https://github.com/micromatch/braces/compare/2.1.0...2.1.1 +[2.1.0]: https://github.com/micromatch/braces/compare/2.0.4...2.1.0 +[2.0.4]: https://github.com/micromatch/braces/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/micromatch/braces/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/micromatch/braces/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/micromatch/braces/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/micromatch/braces/compare/1.8.5...2.0.0 +[1.8.5]: https://github.com/micromatch/braces/compare/1.8.4...1.8.5 +[1.8.4]: https://github.com/micromatch/braces/compare/1.8.0...1.8.4 +[1.8.0]: https://github.com/micromatch/braces/compare/1.6.0...1.8.0 +[1.6.0]: https://github.com/micromatch/braces/compare/1.5.0...1.6.0 +[1.5.0]: https://github.com/micromatch/braces/compare/1.4.0...1.5.0 +[1.4.0]: https://github.com/micromatch/braces/compare/1.3.0...1.4.0 +[1.3.0]: https://github.com/micromatch/braces/compare/1.2.0...1.3.0 +[1.2.0]: https://github.com/micromatch/braces/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/micromatch/braces/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/micromatch/braces/compare/0.1.4...1.0.0 +[0.1.4]: https://github.com/micromatch/braces/compare/0.1.0...0.1.4 + +[Unreleased]: https://github.com/micromatch/braces/compare/0.1.0...HEAD +[keep-a-changelog]: https://github.com/olivierlacan/keep-a-changelog \ No newline at end of file diff --git a/node_modules/braces/LICENSE b/node_modules/braces/LICENSE new file mode 100644 index 0000000..d32ab44 --- /dev/null +++ b/node_modules/braces/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2018, Jon Schlinkert. + +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/braces/README.md b/node_modules/braces/README.md new file mode 100644 index 0000000..cba2f60 --- /dev/null +++ b/node_modules/braces/README.md @@ -0,0 +1,593 @@ +# braces [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) + +> Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save braces +``` + +## v3.0.0 Released!! + +See the [changelog](CHANGELOG.md) for details. + +## Why use braces? + +Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters. + +* **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) +* **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. +* **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up. +* **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written). +* **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)). +* [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']` +* [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']` +* [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']` +* [Supports escaping](#escaping) - To prevent evaluation of special characters. + +## Usage + +The main export is a function that takes one or more brace `patterns` and `options`. + +```js +const braces = require('braces'); +// braces(patterns[, options]); + +console.log(braces(['{01..05}', '{a..e}'])); +//=> ['(0[1-5])', '([a-e])'] + +console.log(braces(['{01..05}', '{a..e}'], { expand: true })); +//=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e'] +``` + +### Brace Expansion vs. Compilation + +By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching. + +**Compiled** + +```js +console.log(braces('a/{x,y,z}/b')); +//=> ['a/(x|y|z)/b'] +console.log(braces(['a/{01..20}/b', 'a/{1..5}/b'])); +//=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ] +``` + +**Expanded** + +Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)): + +```js +console.log(braces('a/{x,y,z}/b', { expand: true })); +//=> ['a/x/b', 'a/y/b', 'a/z/b'] + +console.log(braces.expand('{01..10}')); +//=> ['01','02','03','04','05','06','07','08','09','10'] +``` + +### Lists + +Expand lists (like Bash "sets"): + +```js +console.log(braces('a/{foo,bar,baz}/*.js')); +//=> ['a/(foo|bar|baz)/*.js'] + +console.log(braces.expand('a/{foo,bar,baz}/*.js')); +//=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] +``` + +### Sequences + +Expand ranges of characters (like Bash "sequences"): + +```js +console.log(braces.expand('{1..3}')); // ['1', '2', '3'] +console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b'] +console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c'] +console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c'] + +// supports zero-padded ranges +console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b'] +console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b'] +``` + +See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options. + +### Steppped ranges + +Steps, or increments, may be used with ranges: + +```js +console.log(braces.expand('{2..10..2}')); +//=> ['2', '4', '6', '8', '10'] + +console.log(braces('{2..10..2}')); +//=> ['(2|4|6|8|10)'] +``` + +When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. + +### Nesting + +Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. + +**"Expanded" braces** + +```js +console.log(braces.expand('a{b,c,/{x,y}}/e')); +//=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] + +console.log(braces.expand('a/{x,{1..5},y}/c')); +//=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] +``` + +**"Optimized" braces** + +```js +console.log(braces('a{b,c,/{x,y}}/e')); +//=> ['a(b|c|/(x|y))/e'] + +console.log(braces('a/{x,{1..5},y}/c')); +//=> ['a/(x|([1-5])|y)/c'] +``` + +### Escaping + +**Escaping braces** + +A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: + +```js +console.log(braces.expand('a\\{d,c,b}e')); +//=> ['a{d,c,b}e'] + +console.log(braces.expand('a{d,c,b\\}e')); +//=> ['a{d,c,b}e'] +``` + +**Escaping commas** + +Commas inside braces may also be escaped: + +```js +console.log(braces.expand('a{b\\,c}d')); +//=> ['a{b,c}d'] + +console.log(braces.expand('a{d\\,c,b}e')); +//=> ['ad,ce', 'abe'] +``` + +**Single items** + +Following bash conventions, a brace pattern is also not expanded when it contains a single character: + +```js +console.log(braces.expand('a{b}c')); +//=> ['a{b}c'] +``` + +## Options + +### options.maxLength + +**Type**: `Number` + +**Default**: `65,536` + +**Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. + +```js +console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error +``` + +### options.expand + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing). + +```js +console.log(braces('a/{b,c}/d', { expand: true })); +//=> [ 'a/b/d', 'a/c/d' ] +``` + +### options.nodupes + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Remove duplicates from the returned array. + +### options.rangeLimit + +**Type**: `Number` + +**Default**: `1000` + +**Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`. + +You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether. + +**Examples** + +```js +// pattern exceeds the "rangeLimit", so it's optimized automatically +console.log(braces.expand('{1..1000}')); +//=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] + +// pattern does not exceed "rangeLimit", so it's NOT optimized +console.log(braces.expand('{1..100}')); +//=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100'] +``` + +### options.transform + +**Type**: `Function` + +**Default**: `undefined` + +**Description**: Customize range expansion. + +**Example: Transforming non-numeric values** + +```js +const alpha = braces.expand('x/{a..e}/y', { + transform(value, index) { + // When non-numeric values are passed, "value" is a character code. + return 'foo/' + String.fromCharCode(value) + '-' + index; + } +}); +console.log(alpha); +//=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ] +``` + +**Example: Transforming numeric values** + +```js +const numeric = braces.expand('{1..5}', { + transform(value) { + // when numeric values are passed, "value" is a number + return 'foo/' + value * 2; + } +}); +console.log(numeric); +//=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ] +``` + +### options.quantifiers + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times. + +Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists) + +The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists. + +**Examples** + +```js +const braces = require('braces'); +console.log(braces('a/b{1,3}/{x,y,z}')); +//=> [ 'a/b(1|3)/(x|y|z)' ] +console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true})); +//=> [ 'a/b{1,3}/(x|y|z)' ] +console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true})); +//=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] +``` + +### options.unescape + +**Type**: `Boolean` + +**Default**: `undefined` + +**Description**: Strip backslashes that were used for escaping from the result. + +## What is "brace expansion"? + +Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). + +In addition to "expansion", braces are also used for matching. In other words: + +* [brace expansion](#brace-expansion) is for generating new lists +* [brace matching](#brace-matching) is for filtering existing lists + +
+More about brace expansion (click to expand) + +There are two main types of brace expansion: + +1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` +2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". + +Here are some example brace patterns to illustrate how they work: + +**Sets** + +``` +{a,b,c} => a b c +{a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 +``` + +**Sequences** + +``` +{1..9} => 1 2 3 4 5 6 7 8 9 +{4..-4} => 4 3 2 1 0 -1 -2 -3 -4 +{1..20..3} => 1 4 7 10 13 16 19 +{a..j} => a b c d e f g h i j +{j..a} => j i h g f e d c b a +{a..z..3} => a d g j m p s v y +``` + +**Combination** + +Sets and sequences can be mixed together or used along with any other strings. + +``` +{a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 +foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar +``` + +The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. + +## Brace matching + +In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. + +For example, the pattern `foo/{1..3}/bar` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +``` + +But not: + +``` +baz/1/qux +baz/2/qux +baz/3/qux +``` + +Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: + +``` +foo/1/bar +foo/2/bar +foo/3/bar +baz/1/qux +baz/2/qux +baz/3/qux +``` + +## Brace matching pitfalls + +Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. + +### tldr + +**"brace bombs"** + +* brace expansion can eat up a huge amount of processing resources +* as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially +* users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) + +For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. + +### The solution + +Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. + +### Geometric complexity + +At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. + +For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: + +``` +{1,2}{3,4} => (2X2) => 13 14 23 24 +{1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 +``` + +But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: + +``` +{1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 + 249 257 258 259 267 268 269 347 348 349 357 + 358 359 367 368 369 +``` + +Now, imagine how this complexity grows given that each element is a n-tuple: + +``` +{1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) +{1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) +``` + +Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. + +**More information** + +Interested in learning more about brace expansion? + +* [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) +* [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) +* [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) + +
+ +## Performance + +Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. + +### Better algorithms + +Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. + +Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. + +**The proof is in the numbers** + +Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. + +| **Pattern** | **braces** | **[minimatch][]** | +| --- | --- | --- | +| `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs)| N/A (freezes) | +| `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | +| `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | +| `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | +| `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | +| `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | +| `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | +| `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | +| `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | +| `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | +| `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | +| `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | +| `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | +| `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | +| `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | +| `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | +| `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | + +### Faster algorithms + +When you need expansion, braces is still much faster. + +_(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ + +| **Pattern** | **braces** | **[minimatch][]** | +| --- | --- | --- | +| `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | +| `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | +| `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | +| `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | +| `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | +| `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | +| `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | +| `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | + +If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). + +## Benchmarks + +### Running benchmarks + +Install dev dependencies: + +```bash +npm i -d && npm benchmark +``` + +### Latest results + +Braces is more accurate, without sacrificing performance. + +```bash +# range (expanded) + braces x 29,040 ops/sec ±3.69% (91 runs sampled)) + minimatch x 4,735 ops/sec ±1.28% (90 runs sampled) + +# range (optimized for regex) + braces x 382,878 ops/sec ±0.56% (94 runs sampled) + minimatch x 1,040 ops/sec ±0.44% (93 runs sampled) + +# nested ranges (expanded) + braces x 19,744 ops/sec ±2.27% (92 runs sampled)) + minimatch x 4,579 ops/sec ±0.50% (93 runs sampled) + +# nested ranges (optimized for regex) + braces x 246,019 ops/sec ±2.02% (93 runs sampled) + minimatch x 1,028 ops/sec ±0.39% (94 runs sampled) + +# set (expanded) + braces x 138,641 ops/sec ±0.53% (95 runs sampled) + minimatch x 219,582 ops/sec ±0.98% (94 runs sampled) + +# set (optimized for regex) + braces x 388,408 ops/sec ±0.41% (95 runs sampled) + minimatch x 44,724 ops/sec ±0.91% (89 runs sampled) + +# nested sets (expanded) + braces x 84,966 ops/sec ±0.48% (94 runs sampled) + minimatch x 140,720 ops/sec ±0.37% (95 runs sampled) + +# nested sets (optimized for regex) + braces x 263,340 ops/sec ±2.06% (92 runs sampled) + minimatch x 28,714 ops/sec ±0.40% (90 runs sampled) +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 197 | [jonschlinkert](https://github.com/jonschlinkert) | +| 4 | [doowb](https://github.com/doowb) | +| 1 | [es128](https://github.com/es128) | +| 1 | [eush77](https://github.com/eush77) | +| 1 | [hemanth](https://github.com/hemanth) | +| 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ \ No newline at end of file diff --git a/node_modules/braces/index.js b/node_modules/braces/index.js new file mode 100644 index 0000000..0eee0f5 --- /dev/null +++ b/node_modules/braces/index.js @@ -0,0 +1,170 @@ +'use strict'; + +const stringify = require('./lib/stringify'); +const compile = require('./lib/compile'); +const expand = require('./lib/expand'); +const parse = require('./lib/parse'); + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces.parse = (input, options = {}) => parse(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify(braces.parse(input, options), options); + } + return stringify(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + return compile(input, options); +}; + +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + let result = expand(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces.compile(input, options) + : braces.expand(input, options); +}; + +/** + * Expose "braces" + */ + +module.exports = braces; diff --git a/node_modules/braces/lib/compile.js b/node_modules/braces/lib/compile.js new file mode 100644 index 0000000..3e984a4 --- /dev/null +++ b/node_modules/braces/lib/compile.js @@ -0,0 +1,57 @@ +'use strict'; + +const fill = require('fill-range'); +const utils = require('./utils'); + +const compile = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? (prefix + node.value) : '('; + } + + if (node.type === 'close') { + return invalid ? (prefix + node.value) : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils.reduce(node.nodes); + let range = fill(...args, { ...options, wrap: false, toRegex: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + + return walk(ast); +}; + +module.exports = compile; diff --git a/node_modules/braces/lib/constants.js b/node_modules/braces/lib/constants.js new file mode 100644 index 0000000..a937943 --- /dev/null +++ b/node_modules/braces/lib/constants.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = { + MAX_LENGTH: 1024 * 64, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; diff --git a/node_modules/braces/lib/expand.js b/node_modules/braces/lib/expand.js new file mode 100644 index 0000000..376c748 --- /dev/null +++ b/node_modules/braces/lib/expand.js @@ -0,0 +1,113 @@ +'use strict'; + +const fill = require('fill-range'); +const stringify = require('./stringify'); +const utils = require('./utils'); + +const append = (queue = '', stash = '', enclose = false) => { + let result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); + } + } + } + return utils.flatten(result); +}; + +const expand = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils.reduce(node.nodes); + + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fill(...args, options); + if (range.length === 0) { + range = stringify(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils.flatten(walk(ast)); +}; + +module.exports = expand; diff --git a/node_modules/braces/lib/parse.js b/node_modules/braces/lib/parse.js new file mode 100644 index 0000000..145ea26 --- /dev/null +++ b/node_modules/braces/lib/parse.js @@ -0,0 +1,333 @@ +'use strict'; + +const stringify = require('./stringify'); + +/** + * Constants + */ + +const { + MAX_LENGTH, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = require('./constants'); + +/** + * parse + */ + +const parse = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + let memo = {}; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + + let closed = true; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +module.exports = parse; diff --git a/node_modules/braces/lib/stringify.js b/node_modules/braces/lib/stringify.js new file mode 100644 index 0000000..414b7bc --- /dev/null +++ b/node_modules/braces/lib/stringify.js @@ -0,0 +1,32 @@ +'use strict'; + +const utils = require('./utils'); + +module.exports = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + diff --git a/node_modules/braces/lib/utils.js b/node_modules/braces/lib/utils.js new file mode 100644 index 0000000..e3551a6 --- /dev/null +++ b/node_modules/braces/lib/utils.js @@ -0,0 +1,112 @@ +'use strict'; + +exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; +}; + +/** + * Find a node of the given type + */ + +exports.find = (node, type) => node.nodes.find(node => node.type === type); + +/** + * Find a node of the given type + */ + +exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; +}; + +/** + * Escape the given node with '\\' before node.value + */ + +exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } +}; + +/** + * Returns true if the given brace node should be enclosed in literal braces + */ + +exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a brace node is invalid. + */ + +exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; +}; + +/** + * Returns true if a node is an open or close node + */ + +exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; +}; + +/** + * Reduce an array of text nodes. + */ + +exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; +}, []); + +/** + * Flatten an array + */ + +exports.flatten = (...args) => { + const result = []; + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; +}; diff --git a/node_modules/braces/package.json b/node_modules/braces/package.json new file mode 100644 index 0000000..50b29a2 --- /dev/null +++ b/node_modules/braces/package.json @@ -0,0 +1,126 @@ +{ + "_args": [ + [ + "braces@3.0.2", + "/home/other/discord_bot" + ] + ], + "_from": "braces@3.0.2", + "_id": "braces@3.0.2", + "_inBundle": false, + "_integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "_location": "/braces", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "braces@3.0.2", + "name": "braces", + "escapedName": "braces", + "rawSpec": "3.0.2", + "saveSpec": null, + "fetchSpec": "3.0.2" + }, + "_requiredBy": [ + "/chokidar" + ], + "_resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "_spec": "3.0.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "Jon Schlinkert", + "url": "https://github.com/jonschlinkert" + }, + "bugs": { + "url": "https://github.com/micromatch/braces/issues" + }, + "contributors": [ + { + "name": "Brian Woodward", + "url": "https://twitter.com/doowb" + }, + { + "name": "Elan Shanker", + "url": "https://github.com/es128" + }, + { + "name": "Eugene Sharygin", + "url": "https://github.com/eush77" + }, + { + "name": "hemanth.hm", + "url": "http://h3manth.com" + }, + { + "name": "Jon Schlinkert", + "url": "http://twitter.com/jonschlinkert" + } + ], + "dependencies": { + "fill-range": "^7.0.1" + }, + "description": "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.", + "devDependencies": { + "ansi-colors": "^3.2.4", + "bash-path": "^2.0.1", + "gulp-format-md": "^2.0.0", + "mocha": "^6.1.1" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/micromatch/braces", + "keywords": [ + "alpha", + "alphabetical", + "bash", + "brace", + "braces", + "expand", + "expansion", + "filepath", + "fill", + "fs", + "glob", + "globbing", + "letter", + "match", + "matches", + "matching", + "number", + "numerical", + "path", + "range", + "ranges", + "sh" + ], + "license": "MIT", + "main": "index.js", + "name": "braces", + "repository": { + "type": "git", + "url": "git+https://github.com/micromatch/braces.git" + }, + "scripts": { + "benchmark": "node benchmark", + "test": "mocha" + }, + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "lint": { + "reflinks": true + }, + "plugins": [ + "gulp-format-md" + ] + }, + "version": "3.0.2" +} diff --git a/node_modules/buffer-equal-constant-time/.npmignore b/node_modules/buffer-equal-constant-time/.npmignore new file mode 100644 index 0000000..34e4f5c --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.npmignore @@ -0,0 +1,2 @@ +.*.sw[mnop] +node_modules/ diff --git a/node_modules/buffer-equal-constant-time/.travis.yml b/node_modules/buffer-equal-constant-time/.travis.yml new file mode 100644 index 0000000..78e1c01 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: +- "0.11" +- "0.10" diff --git a/node_modules/buffer-equal-constant-time/LICENSE.txt b/node_modules/buffer-equal-constant-time/LICENSE.txt new file mode 100644 index 0000000..9a064f3 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) 2013, GoInstant Inc., a salesforce.com company +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of salesforce.com, nor GoInstant, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/buffer-equal-constant-time/README.md b/node_modules/buffer-equal-constant-time/README.md new file mode 100644 index 0000000..4f227f5 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/README.md @@ -0,0 +1,50 @@ +# buffer-equal-constant-time + +Constant-time `Buffer` comparison for node.js. Should work with browserify too. + +[![Build Status](https://travis-ci.org/goinstant/buffer-equal-constant-time.png?branch=master)](https://travis-ci.org/goinstant/buffer-equal-constant-time) + +```sh + npm install buffer-equal-constant-time +``` + +# Usage + +```js + var bufferEq = require('buffer-equal-constant-time'); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (bufferEq(a,b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +If you'd like to install an `.equal()` method onto the node.js `Buffer` and +`SlowBuffer` prototypes: + +```js + require('buffer-equal-constant-time').install(); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (a.equal(b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +To get rid of the installed `.equal()` method, call `.restore()`: + +```js + require('buffer-equal-constant-time').restore(); +``` + +# Legal + +© 2013 GoInstant Inc., a salesforce.com company + +Licensed under the BSD 3-clause license. diff --git a/node_modules/buffer-equal-constant-time/index.js b/node_modules/buffer-equal-constant-time/index.js new file mode 100644 index 0000000..5462c1f --- /dev/null +++ b/node_modules/buffer-equal-constant-time/index.js @@ -0,0 +1,41 @@ +/*jshint node:true */ +'use strict'; +var Buffer = require('buffer').Buffer; // browserify +var SlowBuffer = require('buffer').SlowBuffer; + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} + +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; diff --git a/node_modules/buffer-equal-constant-time/package.json b/node_modules/buffer-equal-constant-time/package.json new file mode 100644 index 0000000..b58e45c --- /dev/null +++ b/node_modules/buffer-equal-constant-time/package.json @@ -0,0 +1,58 @@ +{ + "_args": [ + [ + "buffer-equal-constant-time@1.0.1", + "/home/other/discord_bot" + ] + ], + "_from": "buffer-equal-constant-time@1.0.1", + "_id": "buffer-equal-constant-time@1.0.1", + "_inBundle": false, + "_integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=", + "_location": "/buffer-equal-constant-time", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "buffer-equal-constant-time@1.0.1", + "name": "buffer-equal-constant-time", + "escapedName": "buffer-equal-constant-time", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/jwa" + ], + "_resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "_spec": "1.0.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "GoInstant Inc., a salesforce.com company" + }, + "bugs": { + "url": "https://github.com/goinstant/buffer-equal-constant-time/issues" + }, + "description": "Constant-time comparison of Buffers", + "devDependencies": { + "mocha": "~1.15.1" + }, + "homepage": "https://github.com/goinstant/buffer-equal-constant-time#readme", + "keywords": [ + "buffer", + "equal", + "constant-time", + "crypto" + ], + "license": "BSD-3-Clause", + "main": "index.js", + "name": "buffer-equal-constant-time", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/goinstant/buffer-equal-constant-time.git" + }, + "scripts": { + "test": "mocha test.js" + }, + "version": "1.0.1" +} diff --git a/node_modules/buffer-equal-constant-time/test.js b/node_modules/buffer-equal-constant-time/test.js new file mode 100644 index 0000000..0bc972d --- /dev/null +++ b/node_modules/buffer-equal-constant-time/test.js @@ -0,0 +1,42 @@ +/*jshint node:true */ +'use strict'; + +var bufferEq = require('./index'); +var assert = require('assert'); + +describe('buffer-equal-constant-time', function() { + var a = new Buffer('asdfasdf123456'); + var b = new Buffer('asdfasdf123456'); + var c = new Buffer('asdfasdf'); + + describe('bufferEq', function() { + it('says a == b', function() { + assert.strictEqual(bufferEq(a, b), true); + }); + + it('says a != c', function() { + assert.strictEqual(bufferEq(a, c), false); + }); + }); + + describe('install/restore', function() { + before(function() { + bufferEq.install(); + }); + after(function() { + bufferEq.restore(); + }); + + it('installed an .equal method', function() { + var SlowBuffer = require('buffer').SlowBuffer; + assert.ok(Buffer.prototype.equal); + assert.ok(SlowBuffer.prototype.equal); + }); + + it('infected existing Buffers', function() { + assert.strictEqual(a.equal(b), true); + assert.strictEqual(a.equal(c), false); + }); + }); + +}); diff --git a/node_modules/busboy/.eslintrc.js b/node_modules/busboy/.eslintrc.js new file mode 100644 index 0000000..be9311d --- /dev/null +++ b/node_modules/busboy/.eslintrc.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + extends: '@mscdex/eslint-config', +}; diff --git a/node_modules/busboy/.github/workflows/ci.yml b/node_modules/busboy/.github/workflows/ci.yml new file mode 100644 index 0000000..799bae0 --- /dev/null +++ b/node_modules/busboy/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +jobs: + tests-linux: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [10.16.0, 10.x, 12.x, 14.x, 16.x] + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install module + run: npm install + - name: Run tests + run: npm test diff --git a/node_modules/busboy/.github/workflows/lint.yml b/node_modules/busboy/.github/workflows/lint.yml new file mode 100644 index 0000000..9f9e1f5 --- /dev/null +++ b/node_modules/busboy/.github/workflows/lint.yml @@ -0,0 +1,23 @@ +name: lint + +on: + pull_request: + push: + branches: [ master ] + +env: + NODE_VERSION: 16.x + +jobs: + lint-js: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ env.NODE_VERSION }} + uses: actions/setup-node@v1 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Install ESLint + ESLint configs/plugins + run: npm install --only=dev + - name: Lint files + run: npm run lint diff --git a/node_modules/busboy/LICENSE b/node_modules/busboy/LICENSE new file mode 100644 index 0000000..290762e --- /dev/null +++ b/node_modules/busboy/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +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/busboy/README.md b/node_modules/busboy/README.md new file mode 100644 index 0000000..654af30 --- /dev/null +++ b/node_modules/busboy/README.md @@ -0,0 +1,191 @@ +# Description + +A node.js module for parsing incoming HTML form data. + +Changes (breaking or otherwise) in v1.0.0 can be found [here](https://github.com/mscdex/busboy/issues/266). + +# Requirements + +* [node.js](http://nodejs.org/) -- v10.16.0 or newer + + +# Install + + npm install busboy + + +# Examples + +* Parsing (multipart) with default options: + +```js +const http = require('http'); + +const busboy = require('busboy'); + +http.createServer((req, res) => { + if (req.method === 'POST') { + console.log('POST request'); + const bb = busboy({ headers: req.headers }); + bb.on('file', (name, file, info) => { + const { filename, encoding, mimeType } = info; + console.log( + `File [${name}]: filename: %j, encoding: %j, mimeType: %j`, + filename, + encoding, + mimeType + ); + file.on('data', (data) => { + console.log(`File [${name}] got ${data.length} bytes`); + }).on('close', () => { + console.log(`File [${name}] done`); + }); + }); + bb.on('field', (name, val, info) => { + console.log(`Field [${name}]: value: %j`, val); + }); + bb.on('close', () => { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(bb); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end(` + + + +
+
+
+ +
+ + + `); + } +}).listen(8000, () => { + console.log('Listening for requests'); +}); + +// Example output: +// +// Listening for requests +// < ... form submitted ... > +// POST request +// File [filefield]: filename: "logo.jpg", encoding: "binary", mime: "image/jpeg" +// File [filefield] got 11912 bytes +// Field [textfield]: value: "testing! :-)" +// File [filefield] done +// Done parsing form! +``` + +* Save all incoming files to disk: + +```js +const { randomFillSync } = require('crypto'); +const fs = require('fs'); +const http = require('http'); +const os = require('os'); +const path = require('path'); + +const busboy = require('busboy'); + +const random = (() => { + const buf = Buffer.alloc(16); + return () => randomFillSync(buf).toString('hex'); +})(); + +http.createServer((req, res) => { + if (req.method === 'POST') { + const bb = busboy({ headers: req.headers }); + bb.on('file', (name, file, info) => { + const saveTo = path.join(os.tmpdir(), `busboy-upload-${random()}`); + file.pipe(fs.createWriteStream(saveTo)); + }); + bb.on('close', () => { + res.writeHead(200, { 'Connection': 'close' }); + res.end(`That's all folks!`); + }); + req.pipe(bb); + return; + } + res.writeHead(404); + res.end(); +}).listen(8000, () => { + console.log('Listening for requests'); +}); +``` + + +# API + +## Exports + +`busboy` exports a single function: + +**( _function_ )**(< _object_ >config) - Creates and returns a new _Writable_ form parser stream. + +* Valid `config` properties: + + * **headers** - _object_ - These are the HTTP headers of the incoming request, which are used by individual parsers. + + * **highWaterMark** - _integer_ - highWaterMark to use for the parser stream. **Default:** node's _stream.Writable_ default. + + * **fileHwm** - _integer_ - highWaterMark to use for individual file streams. **Default:** node's _stream.Readable_ default. + + * **defCharset** - _string_ - Default character set to use when one isn't defined. **Default:** `'utf8'`. + + * **defParamCharset** - _string_ - For multipart forms, the default character set to use for values of part header parameters (e.g. filename) that are not extended parameters (that contain an explicit charset). **Default:** `'latin1'`. + + * **preservePath** - _boolean_ - If paths in filenames from file parts in a `'multipart/form-data'` request shall be preserved. **Default:** `false`. + + * **limits** - _object_ - Various limits on incoming data. Valid properties are: + + * **fieldNameSize** - _integer_ - Max field name size (in bytes). **Default:** `100`. + + * **fieldSize** - _integer_ - Max field value size (in bytes). **Default:** `1048576` (1MB). + + * **fields** - _integer_ - Max number of non-file fields. **Default:** `Infinity`. + + * **fileSize** - _integer_ - For multipart forms, the max file size (in bytes). **Default:** `Infinity`. + + * **files** - _integer_ - For multipart forms, the max number of file fields. **Default:** `Infinity`. + + * **parts** - _integer_ - For multipart forms, the max number of parts (fields + files). **Default:** `Infinity`. + + * **headerPairs** - _integer_ - For multipart forms, the max number of header key-value pairs to parse. **Default:** `2000` (same as node's http module). + +This function can throw exceptions if there is something wrong with the values in `config`. For example, if the Content-Type in `headers` is missing entirely, is not a supported type, or is missing the boundary for `'multipart/form-data'` requests. + +## (Special) Parser stream events + +* **file**(< _string_ >name, < _Readable_ >stream, < _object_ >info) - Emitted for each new file found. `name` contains the form field name. `stream` is a _Readable_ stream containing the file's data. No transformations/conversions (e.g. base64 to raw binary) are done on the file's data. `info` contains the following properties: + + * `filename` - _string_ - If supplied, this contains the file's filename. **WARNING:** You should almost _never_ use this value as-is (especially if you are using `preservePath: true` in your `config`) as it could contain malicious input. You are better off generating your own (safe) filenames, or at the very least using a hash of the filename. + + * `encoding` - _string_ - The file's `'Content-Transfer-Encoding'` value. + + * `mimeType` - _string_ - The file's `'Content-Type'` value. + + **Note:** If you listen for this event, you should always consume the `stream` whether you care about its contents or not (you can simply do `stream.resume();` if you want to discard/skip the contents), otherwise the `'finish'`/`'close'` event will never fire on the busboy parser stream. + However, if you aren't accepting files, you can either simply not listen for the `'file'` event at all or set `limits.files` to `0`, and any/all files will be automatically skipped (these skipped files will still count towards any configured `limits.files` and `limits.parts` limits though). + + **Note:** If a configured `limits.fileSize` limit was reached for a file, `stream` will both have a boolean property `truncated` set to `true` (best checked at the end of the stream) and emit a `'limit'` event to notify you when this happens. + +* **field**(< _string_ >name, < _string_ >value, < _object_ >info) - Emitted for each new non-file field found. `name` contains the form field name. `value` contains the string value of the field. `info` contains the following properties: + + * `nameTruncated` - _boolean_ - Whether `name` was truncated or not (due to a configured `limits.fieldNameSize` limit) + + * `valueTruncated` - _boolean_ - Whether `value` was truncated or not (due to a configured `limits.fieldSize` limit) + + * `encoding` - _string_ - The field's `'Content-Transfer-Encoding'` value. + + * `mimeType` - _string_ - The field's `'Content-Type'` value. + +* **partsLimit**() - Emitted when the configured `limits.parts` limit has been reached. No more `'file'` or `'field'` events will be emitted. + +* **filesLimit**() - Emitted when the configured `limits.files` limit has been reached. No more `'file'` events will be emitted. + +* **fieldsLimit**() - Emitted when the configured `limits.fields` limit has been reached. No more `'field'` events will be emitted. diff --git a/node_modules/busboy/bench/bench-multipart-fields-100mb-big.js b/node_modules/busboy/bench/bench-multipart-fields-100mb-big.js new file mode 100644 index 0000000..ef15729 --- /dev/null +++ b/node_modules/busboy/bench/bench-multipart-fields-100mb-big.js @@ -0,0 +1,149 @@ +'use strict'; + +function createMultipartBuffers(boundary, sizes) { + const bufs = []; + for (let i = 0; i < sizes.length; ++i) { + const mb = sizes[i] * 1024 * 1024; + bufs.push(Buffer.from([ + `--${boundary}`, + `content-disposition: form-data; name="field${i + 1}"`, + '', + '0'.repeat(mb), + '', + ].join('\r\n'))); + } + bufs.push(Buffer.from([ + `--${boundary}--`, + '', + ].join('\r\n'))); + return bufs; +} + +const boundary = '-----------------------------168072824752491622650073'; +const buffers = createMultipartBuffers(boundary, [ + 10, + 10, + 10, + 20, + 50, +]); +const calls = { + partBegin: 0, + headerField: 0, + headerValue: 0, + headerEnd: 0, + headersEnd: 0, + partData: 0, + partEnd: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + }); + parser.on('field', (name, val, info) => { + ++calls.partBegin; + ++calls.partData; + ++calls.partEnd; + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + break; + } + + case 'formidable': { + const { MultipartParser } = require('formidable'); + + const parser = new MultipartParser(); + parser.initWithBoundary(boundary); + parser.on('data', ({ name }) => { + ++calls[name]; + if (name === 'end') + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + + break; + } + + case 'multiparty': { + const { Readable } = require('stream'); + + const { Form } = require('multiparty'); + + const form = new Form({ + maxFieldsSize: Infinity, + maxFields: Infinity, + maxFilesSize: Infinity, + autoFields: false, + autoFiles: false, + }); + + const req = new Readable({ read: () => {} }); + req.headers = { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }; + + function hijack(name, fn) { + const oldFn = form[name]; + form[name] = function() { + fn(); + return oldFn.apply(this, arguments); + }; + } + + hijack('onParseHeaderField', () => { + ++calls.headerField; + }); + hijack('onParseHeaderValue', () => { + ++calls.headerValue; + }); + hijack('onParsePartBegin', () => { + ++calls.partBegin; + }); + hijack('onParsePartData', () => { + ++calls.partData; + }); + hijack('onParsePartEnd', () => { + ++calls.partEnd; + }); + + form.on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }).on('part', (p) => p.resume()); + + console.time(moduleName); + form.parse(req); + for (const buf of buffers) + req.push(buf); + req.push(null); + + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-multipart-fields-100mb-small.js b/node_modules/busboy/bench/bench-multipart-fields-100mb-small.js new file mode 100644 index 0000000..f32d421 --- /dev/null +++ b/node_modules/busboy/bench/bench-multipart-fields-100mb-small.js @@ -0,0 +1,143 @@ +'use strict'; + +function createMultipartBuffers(boundary, sizes) { + const bufs = []; + for (let i = 0; i < sizes.length; ++i) { + const mb = sizes[i] * 1024 * 1024; + bufs.push(Buffer.from([ + `--${boundary}`, + `content-disposition: form-data; name="field${i + 1}"`, + '', + '0'.repeat(mb), + '', + ].join('\r\n'))); + } + bufs.push(Buffer.from([ + `--${boundary}--`, + '', + ].join('\r\n'))); + return bufs; +} + +const boundary = '-----------------------------168072824752491622650073'; +const buffers = createMultipartBuffers(boundary, (new Array(100)).fill(1)); +const calls = { + partBegin: 0, + headerField: 0, + headerValue: 0, + headerEnd: 0, + headersEnd: 0, + partData: 0, + partEnd: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + }); + parser.on('field', (name, val, info) => { + ++calls.partBegin; + ++calls.partData; + ++calls.partEnd; + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + break; + } + + case 'formidable': { + const { MultipartParser } = require('formidable'); + + const parser = new MultipartParser(); + parser.initWithBoundary(boundary); + parser.on('data', ({ name }) => { + ++calls[name]; + if (name === 'end') + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + + break; + } + + case 'multiparty': { + const { Readable } = require('stream'); + + const { Form } = require('multiparty'); + + const form = new Form({ + maxFieldsSize: Infinity, + maxFields: Infinity, + maxFilesSize: Infinity, + autoFields: false, + autoFiles: false, + }); + + const req = new Readable({ read: () => {} }); + req.headers = { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }; + + function hijack(name, fn) { + const oldFn = form[name]; + form[name] = function() { + fn(); + return oldFn.apply(this, arguments); + }; + } + + hijack('onParseHeaderField', () => { + ++calls.headerField; + }); + hijack('onParseHeaderValue', () => { + ++calls.headerValue; + }); + hijack('onParsePartBegin', () => { + ++calls.partBegin; + }); + hijack('onParsePartData', () => { + ++calls.partData; + }); + hijack('onParsePartEnd', () => { + ++calls.partEnd; + }); + + form.on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }).on('part', (p) => p.resume()); + + console.time(moduleName); + form.parse(req); + for (const buf of buffers) + req.push(buf); + req.push(null); + + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-multipart-files-100mb-big.js b/node_modules/busboy/bench/bench-multipart-files-100mb-big.js new file mode 100644 index 0000000..b46bdee --- /dev/null +++ b/node_modules/busboy/bench/bench-multipart-files-100mb-big.js @@ -0,0 +1,154 @@ +'use strict'; + +function createMultipartBuffers(boundary, sizes) { + const bufs = []; + for (let i = 0; i < sizes.length; ++i) { + const mb = sizes[i] * 1024 * 1024; + bufs.push(Buffer.from([ + `--${boundary}`, + `content-disposition: form-data; name="file${i + 1}"; ` + + `filename="random${i + 1}.bin"`, + 'content-type: application/octet-stream', + '', + '0'.repeat(mb), + '', + ].join('\r\n'))); + } + bufs.push(Buffer.from([ + `--${boundary}--`, + '', + ].join('\r\n'))); + return bufs; +} + +const boundary = '-----------------------------168072824752491622650073'; +const buffers = createMultipartBuffers(boundary, [ + 10, + 10, + 10, + 20, + 50, +]); +const calls = { + partBegin: 0, + headerField: 0, + headerValue: 0, + headerEnd: 0, + headersEnd: 0, + partData: 0, + partEnd: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + }); + parser.on('file', (name, stream, info) => { + ++calls.partBegin; + stream.on('data', (chunk) => { + ++calls.partData; + }).on('end', () => { + ++calls.partEnd; + }); + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + break; + } + + case 'formidable': { + const { MultipartParser } = require('formidable'); + + const parser = new MultipartParser(); + parser.initWithBoundary(boundary); + parser.on('data', ({ name }) => { + ++calls[name]; + if (name === 'end') + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + + break; + } + + case 'multiparty': { + const { Readable } = require('stream'); + + const { Form } = require('multiparty'); + + const form = new Form({ + maxFieldsSize: Infinity, + maxFields: Infinity, + maxFilesSize: Infinity, + autoFields: false, + autoFiles: false, + }); + + const req = new Readable({ read: () => {} }); + req.headers = { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }; + + function hijack(name, fn) { + const oldFn = form[name]; + form[name] = function() { + fn(); + return oldFn.apply(this, arguments); + }; + } + + hijack('onParseHeaderField', () => { + ++calls.headerField; + }); + hijack('onParseHeaderValue', () => { + ++calls.headerValue; + }); + hijack('onParsePartBegin', () => { + ++calls.partBegin; + }); + hijack('onParsePartData', () => { + ++calls.partData; + }); + hijack('onParsePartEnd', () => { + ++calls.partEnd; + }); + + form.on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }).on('part', (p) => p.resume()); + + console.time(moduleName); + form.parse(req); + for (const buf of buffers) + req.push(buf); + req.push(null); + + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-multipart-files-100mb-small.js b/node_modules/busboy/bench/bench-multipart-files-100mb-small.js new file mode 100644 index 0000000..46b5dff --- /dev/null +++ b/node_modules/busboy/bench/bench-multipart-files-100mb-small.js @@ -0,0 +1,148 @@ +'use strict'; + +function createMultipartBuffers(boundary, sizes) { + const bufs = []; + for (let i = 0; i < sizes.length; ++i) { + const mb = sizes[i] * 1024 * 1024; + bufs.push(Buffer.from([ + `--${boundary}`, + `content-disposition: form-data; name="file${i + 1}"; ` + + `filename="random${i + 1}.bin"`, + 'content-type: application/octet-stream', + '', + '0'.repeat(mb), + '', + ].join('\r\n'))); + } + bufs.push(Buffer.from([ + `--${boundary}--`, + '', + ].join('\r\n'))); + return bufs; +} + +const boundary = '-----------------------------168072824752491622650073'; +const buffers = createMultipartBuffers(boundary, (new Array(100)).fill(1)); +const calls = { + partBegin: 0, + headerField: 0, + headerValue: 0, + headerEnd: 0, + headersEnd: 0, + partData: 0, + partEnd: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }, + }); + parser.on('file', (name, stream, info) => { + ++calls.partBegin; + stream.on('data', (chunk) => { + ++calls.partData; + }).on('end', () => { + ++calls.partEnd; + }); + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + break; + } + + case 'formidable': { + const { MultipartParser } = require('formidable'); + + const parser = new MultipartParser(); + parser.initWithBoundary(boundary); + parser.on('data', ({ name }) => { + ++calls[name]; + if (name === 'end') + console.timeEnd(moduleName); + }); + + console.time(moduleName); + for (const buf of buffers) + parser.write(buf); + + break; + } + + case 'multiparty': { + const { Readable } = require('stream'); + + const { Form } = require('multiparty'); + + const form = new Form({ + maxFieldsSize: Infinity, + maxFields: Infinity, + maxFilesSize: Infinity, + autoFields: false, + autoFiles: false, + }); + + const req = new Readable({ read: () => {} }); + req.headers = { + 'content-type': `multipart/form-data; boundary=${boundary}`, + }; + + function hijack(name, fn) { + const oldFn = form[name]; + form[name] = function() { + fn(); + return oldFn.apply(this, arguments); + }; + } + + hijack('onParseHeaderField', () => { + ++calls.headerField; + }); + hijack('onParseHeaderValue', () => { + ++calls.headerValue; + }); + hijack('onParsePartBegin', () => { + ++calls.partBegin; + }); + hijack('onParsePartData', () => { + ++calls.partData; + }); + hijack('onParsePartEnd', () => { + ++calls.partEnd; + }); + + form.on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }).on('part', (p) => p.resume()); + + console.time(moduleName); + form.parse(req); + for (const buf of buffers) + req.push(buf); + req.push(null); + + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-urlencoded-fields-100pairs-small.js b/node_modules/busboy/bench/bench-urlencoded-fields-100pairs-small.js new file mode 100644 index 0000000..5c337df --- /dev/null +++ b/node_modules/busboy/bench/bench-urlencoded-fields-100pairs-small.js @@ -0,0 +1,101 @@ +'use strict'; + +const buffers = [ + Buffer.from( + (new Array(100)).fill('').map((_, i) => `key${i}=value${i}`).join('&') + ), +]; +const calls = { + field: 0, + end: 0, +}; + +let n = 3e3; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + console.time(moduleName); + (function next() { + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': 'application/x-www-form-urlencoded; charset=utf-8', + }, + }); + parser.on('field', (name, val, info) => { + ++calls.field; + }).on('close', () => { + ++calls.end; + if (--n === 0) + console.timeEnd(moduleName); + else + process.nextTick(next); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + })(); + break; + } + + case 'formidable': { + const QuerystringParser = + require('formidable/src/parsers/Querystring.js'); + + console.time(moduleName); + (function next() { + const parser = new QuerystringParser(); + parser.on('data', (obj) => { + ++calls.field; + }).on('end', () => { + ++calls.end; + if (--n === 0) + console.timeEnd(moduleName); + else + process.nextTick(next); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + })(); + break; + } + + case 'formidable-streaming': { + const QuerystringParser = + require('formidable/src/parsers/StreamingQuerystring.js'); + + console.time(moduleName); + (function next() { + const parser = new QuerystringParser(); + parser.on('data', (obj) => { + ++calls.field; + }).on('end', () => { + ++calls.end; + if (--n === 0) + console.timeEnd(moduleName); + else + process.nextTick(next); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + })(); + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/bench/bench-urlencoded-fields-900pairs-small-alt.js b/node_modules/busboy/bench/bench-urlencoded-fields-900pairs-small-alt.js new file mode 100644 index 0000000..1f5645c --- /dev/null +++ b/node_modules/busboy/bench/bench-urlencoded-fields-900pairs-small-alt.js @@ -0,0 +1,84 @@ +'use strict'; + +const buffers = [ + Buffer.from( + (new Array(900)).fill('').map((_, i) => `key${i}=value${i}`).join('&') + ), +]; +const calls = { + field: 0, + end: 0, +}; + +const moduleName = process.argv[2]; +switch (moduleName) { + case 'busboy': { + const busboy = require('busboy'); + + console.time(moduleName); + const parser = busboy({ + limits: { + fieldSizeLimit: Infinity, + }, + headers: { + 'content-type': 'application/x-www-form-urlencoded; charset=utf-8', + }, + }); + parser.on('field', (name, val, info) => { + ++calls.field; + }).on('close', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + break; + } + + case 'formidable': { + const QuerystringParser = + require('formidable/src/parsers/Querystring.js'); + + console.time(moduleName); + const parser = new QuerystringParser(); + parser.on('data', (obj) => { + ++calls.field; + }).on('end', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + break; + } + + case 'formidable-streaming': { + const QuerystringParser = + require('formidable/src/parsers/StreamingQuerystring.js'); + + console.time(moduleName); + const parser = new QuerystringParser(); + parser.on('data', (obj) => { + ++calls.field; + }).on('end', () => { + ++calls.end; + console.timeEnd(moduleName); + }); + + for (const buf of buffers) + parser.write(buf); + parser.end(); + break; + } + + default: + if (moduleName === undefined) + console.error('Missing parser module name'); + else + console.error(`Invalid parser module name: ${moduleName}`); + process.exit(1); +} diff --git a/node_modules/busboy/lib/index.js b/node_modules/busboy/lib/index.js new file mode 100644 index 0000000..873272d --- /dev/null +++ b/node_modules/busboy/lib/index.js @@ -0,0 +1,57 @@ +'use strict'; + +const { parseContentType } = require('./utils.js'); + +function getInstance(cfg) { + const headers = cfg.headers; + const conType = parseContentType(headers['content-type']); + if (!conType) + throw new Error('Malformed content type'); + + for (const type of TYPES) { + const matched = type.detect(conType); + if (!matched) + continue; + + const instanceCfg = { + limits: cfg.limits, + headers, + conType, + highWaterMark: undefined, + fileHwm: undefined, + defCharset: undefined, + defParamCharset: undefined, + preservePath: false, + }; + if (cfg.highWaterMark) + instanceCfg.highWaterMark = cfg.highWaterMark; + if (cfg.fileHwm) + instanceCfg.fileHwm = cfg.fileHwm; + instanceCfg.defCharset = cfg.defCharset; + instanceCfg.defParamCharset = cfg.defParamCharset; + instanceCfg.preservePath = cfg.preservePath; + return new type(instanceCfg); + } + + throw new Error(`Unsupported content type: ${headers['content-type']}`); +} + +// Note: types are explicitly listed here for easier bundling +// See: https://github.com/mscdex/busboy/issues/121 +const TYPES = [ + require('./types/multipart'), + require('./types/urlencoded'), +].filter(function(typemod) { return typeof typemod.detect === 'function'; }); + +module.exports = (cfg) => { + if (typeof cfg !== 'object' || cfg === null) + cfg = {}; + + if (typeof cfg.headers !== 'object' + || cfg.headers === null + || typeof cfg.headers['content-type'] !== 'string') { + throw new Error('Missing Content-Type'); + } + + return getInstance(cfg); +}; diff --git a/node_modules/busboy/lib/types/multipart.js b/node_modules/busboy/lib/types/multipart.js new file mode 100644 index 0000000..cc0d7bb --- /dev/null +++ b/node_modules/busboy/lib/types/multipart.js @@ -0,0 +1,653 @@ +'use strict'; + +const { Readable, Writable } = require('stream'); + +const StreamSearch = require('streamsearch'); + +const { + basename, + convertToUTF8, + getDecoder, + parseContentType, + parseDisposition, +} = require('../utils.js'); + +const BUF_CRLF = Buffer.from('\r\n'); +const BUF_CR = Buffer.from('\r'); +const BUF_DASH = Buffer.from('-'); + +function noop() {} + +const MAX_HEADER_PAIRS = 2000; // From node +const MAX_HEADER_SIZE = 16 * 1024; // From node (its default value) + +const HPARSER_NAME = 0; +const HPARSER_PRE_OWS = 1; +const HPARSER_VALUE = 2; +class HeaderParser { + constructor(cb) { + this.header = Object.create(null); + this.pairCount = 0; + this.byteCount = 0; + this.state = HPARSER_NAME; + this.name = ''; + this.value = ''; + this.crlf = 0; + this.cb = cb; + } + + reset() { + this.header = Object.create(null); + this.pairCount = 0; + this.byteCount = 0; + this.state = HPARSER_NAME; + this.name = ''; + this.value = ''; + this.crlf = 0; + } + + push(chunk, pos, end) { + let start = pos; + while (pos < end) { + switch (this.state) { + case HPARSER_NAME: { + let done = false; + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (TOKEN[code] !== 1) { + if (code !== 58/* ':' */) + return -1; + this.name += chunk.latin1Slice(start, pos); + if (this.name.length === 0) + return -1; + ++pos; + done = true; + this.state = HPARSER_PRE_OWS; + break; + } + } + if (!done) { + this.name += chunk.latin1Slice(start, pos); + break; + } + // FALLTHROUGH + } + case HPARSER_PRE_OWS: { + // Skip optional whitespace + let done = false; + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) { + start = pos; + done = true; + this.state = HPARSER_VALUE; + break; + } + } + if (!done) + break; + // FALLTHROUGH + } + case HPARSER_VALUE: + switch (this.crlf) { + case 0: // Nothing yet + for (; pos < end; ++pos) { + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (FIELD_VCHAR[code] !== 1) { + if (code !== 13/* '\r' */) + return -1; + ++this.crlf; + break; + } + } + this.value += chunk.latin1Slice(start, pos++); + break; + case 1: // Received CR + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + if (chunk[pos++] !== 10/* '\n' */) + return -1; + ++this.crlf; + break; + case 2: { // Received CR LF + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + const code = chunk[pos]; + if (code === 32/* ' ' */ || code === 9/* '\t' */) { + // Folded value + start = pos; + this.crlf = 0; + } else { + if (++this.pairCount < MAX_HEADER_PAIRS) { + this.name = this.name.toLowerCase(); + if (this.header[this.name] === undefined) + this.header[this.name] = [this.value]; + else + this.header[this.name].push(this.value); + } + if (code === 13/* '\r' */) { + ++this.crlf; + ++pos; + } else { + // Assume start of next header field name + start = pos; + this.crlf = 0; + this.state = HPARSER_NAME; + this.name = ''; + this.value = ''; + } + } + break; + } + case 3: { // Received CR LF CR + if (this.byteCount === MAX_HEADER_SIZE) + return -1; + ++this.byteCount; + if (chunk[pos++] !== 10/* '\n' */) + return -1; + // End of header + const header = this.header; + this.reset(); + this.cb(header); + return pos; + } + } + break; + } + } + + return pos; + } +} + +class FileStream extends Readable { + constructor(opts, owner) { + super(opts); + this.truncated = false; + this._readcb = null; + this.once('end', () => { + // We need to make sure that we call any outstanding _writecb() that is + // associated with this file so that processing of the rest of the form + // can continue. This may not happen if the file stream ends right after + // backpressure kicks in, so we force it here. + this._read(); + if (--owner._fileEndsLeft === 0 && owner._finalcb) { + const cb = owner._finalcb; + owner._finalcb = null; + // Make sure other 'end' event handlers get a chance to be executed + // before busboy's 'finish' event is emitted + process.nextTick(cb); + } + }); + } + _read(n) { + const cb = this._readcb; + if (cb) { + this._readcb = null; + cb(); + } + } +} + +const ignoreData = { + push: (chunk, pos) => {}, + destroy: () => {}, +}; + +function callAndUnsetCb(self, err) { + const cb = self._writecb; + self._writecb = null; + if (err) + self.destroy(err); + else if (cb) + cb(); +} + +function nullDecoder(val, hint) { + return val; +} + +class Multipart extends Writable { + constructor(cfg) { + const streamOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: (typeof cfg.highWaterMark === 'number' + ? cfg.highWaterMark + : undefined), + }; + super(streamOpts); + + if (!cfg.conType.params || typeof cfg.conType.params.boundary !== 'string') + throw new Error('Multipart: Boundary not found'); + + const boundary = cfg.conType.params.boundary; + const paramDecoder = (typeof cfg.defParamCharset === 'string' + && cfg.defParamCharset + ? getDecoder(cfg.defParamCharset) + : nullDecoder); + const defCharset = (cfg.defCharset || 'utf8'); + const preservePath = cfg.preservePath; + const fileOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: (typeof cfg.fileHwm === 'number' + ? cfg.fileHwm + : undefined), + }; + + const limits = cfg.limits; + const fieldSizeLimit = (limits && typeof limits.fieldSize === 'number' + ? limits.fieldSize + : 1 * 1024 * 1024); + const fileSizeLimit = (limits && typeof limits.fileSize === 'number' + ? limits.fileSize + : Infinity); + const filesLimit = (limits && typeof limits.files === 'number' + ? limits.files + : Infinity); + const fieldsLimit = (limits && typeof limits.fields === 'number' + ? limits.fields + : Infinity); + const partsLimit = (limits && typeof limits.parts === 'number' + ? limits.parts + : Infinity); + + let parts = -1; // Account for initial boundary + let fields = 0; + let files = 0; + let skipPart = false; + + this._fileEndsLeft = 0; + this._fileStream = undefined; + this._complete = false; + let fileSize = 0; + + let field; + let fieldSize = 0; + let partCharset; + let partEncoding; + let partType; + let partName; + let partTruncated = false; + + let hitFilesLimit = false; + let hitFieldsLimit = false; + + this._hparser = null; + const hparser = new HeaderParser((header) => { + this._hparser = null; + skipPart = false; + + partType = 'text/plain'; + partCharset = defCharset; + partEncoding = '7bit'; + partName = undefined; + partTruncated = false; + + let filename; + if (!header['content-disposition']) { + skipPart = true; + return; + } + + const disp = parseDisposition(header['content-disposition'][0], + paramDecoder); + if (!disp || disp.type !== 'form-data') { + skipPart = true; + return; + } + + if (disp.params) { + if (disp.params.name) + partName = disp.params.name; + + if (disp.params['filename*']) + filename = disp.params['filename*']; + else if (disp.params.filename) + filename = disp.params.filename; + + if (filename !== undefined && !preservePath) + filename = basename(filename); + } + + if (header['content-type']) { + const conType = parseContentType(header['content-type'][0]); + if (conType) { + partType = `${conType.type}/${conType.subtype}`; + if (conType.params && typeof conType.params.charset === 'string') + partCharset = conType.params.charset.toLowerCase(); + } + } + + if (header['content-transfer-encoding']) + partEncoding = header['content-transfer-encoding'][0].toLowerCase(); + + if (partType === 'application/octet-stream' || filename !== undefined) { + // File + + if (files === filesLimit) { + if (!hitFilesLimit) { + hitFilesLimit = true; + this.emit('filesLimit'); + } + skipPart = true; + return; + } + ++files; + + if (this.listenerCount('file') === 0) { + skipPart = true; + return; + } + + fileSize = 0; + this._fileStream = new FileStream(fileOpts, this); + ++this._fileEndsLeft; + this.emit( + 'file', + partName, + this._fileStream, + { filename, + encoding: partEncoding, + mimeType: partType } + ); + } else { + // Non-file + + if (fields === fieldsLimit) { + if (!hitFieldsLimit) { + hitFieldsLimit = true; + this.emit('fieldsLimit'); + } + skipPart = true; + return; + } + ++fields; + + if (this.listenerCount('field') === 0) { + skipPart = true; + return; + } + + field = []; + fieldSize = 0; + } + }); + + let matchPostBoundary = 0; + const ssCb = (isMatch, data, start, end, isDataSafe) => { +retrydata: + while (data) { + if (this._hparser !== null) { + const ret = this._hparser.push(data, start, end); + if (ret === -1) { + this._hparser = null; + hparser.reset(); + this.emit('error', new Error('Malformed part header')); + break; + } + start = ret; + } + + if (start === end) + break; + + if (matchPostBoundary !== 0) { + if (matchPostBoundary === 1) { + switch (data[start]) { + case 45: // '-' + // Try matching '--' after boundary + matchPostBoundary = 2; + ++start; + break; + case 13: // '\r' + // Try matching CR LF before header + matchPostBoundary = 3; + ++start; + break; + default: + matchPostBoundary = 0; + } + if (start === end) + return; + } + + if (matchPostBoundary === 2) { + matchPostBoundary = 0; + if (data[start] === 45/* '-' */) { + // End of multipart data + this._complete = true; + this._bparser = ignoreData; + return; + } + // We saw something other than '-', so put the dash we consumed + // "back" + const writecb = this._writecb; + this._writecb = noop; + ssCb(false, BUF_DASH, 0, 1, false); + this._writecb = writecb; + } else if (matchPostBoundary === 3) { + matchPostBoundary = 0; + if (data[start] === 10/* '\n' */) { + ++start; + if (parts >= partsLimit) + break; + // Prepare the header parser + this._hparser = hparser; + if (start === end) + break; + // Process the remaining data as a header + continue retrydata; + } else { + // We saw something other than LF, so put the CR we consumed + // "back" + const writecb = this._writecb; + this._writecb = noop; + ssCb(false, BUF_CR, 0, 1, false); + this._writecb = writecb; + } + } + } + + if (!skipPart) { + if (this._fileStream) { + let chunk; + const actualLen = Math.min(end - start, fileSizeLimit - fileSize); + if (!isDataSafe) { + chunk = Buffer.allocUnsafe(actualLen); + data.copy(chunk, 0, start, start + actualLen); + } else { + chunk = data.slice(start, start + actualLen); + } + + fileSize += chunk.length; + if (fileSize === fileSizeLimit) { + if (chunk.length > 0) + this._fileStream.push(chunk); + this._fileStream.emit('limit'); + this._fileStream.truncated = true; + skipPart = true; + } else if (!this._fileStream.push(chunk)) { + if (this._writecb) + this._fileStream._readcb = this._writecb; + this._writecb = null; + } + } else if (field !== undefined) { + let chunk; + const actualLen = Math.min( + end - start, + fieldSizeLimit - fieldSize + ); + if (!isDataSafe) { + chunk = Buffer.allocUnsafe(actualLen); + data.copy(chunk, 0, start, start + actualLen); + } else { + chunk = data.slice(start, start + actualLen); + } + + fieldSize += actualLen; + field.push(chunk); + if (fieldSize === fieldSizeLimit) { + skipPart = true; + partTruncated = true; + } + } + } + + break; + } + + if (isMatch) { + matchPostBoundary = 1; + + if (this._fileStream) { + // End the active file stream if the previous part was a file + this._fileStream.push(null); + this._fileStream = null; + } else if (field !== undefined) { + let data; + switch (field.length) { + case 0: + data = ''; + break; + case 1: + data = convertToUTF8(field[0], partCharset, 0); + break; + default: + data = convertToUTF8( + Buffer.concat(field, fieldSize), + partCharset, + 0 + ); + } + field = undefined; + fieldSize = 0; + this.emit( + 'field', + partName, + data, + { nameTruncated: false, + valueTruncated: partTruncated, + encoding: partEncoding, + mimeType: partType } + ); + } + + if (++parts === partsLimit) + this.emit('partsLimit'); + } + }; + this._bparser = new StreamSearch(`\r\n--${boundary}`, ssCb); + + this._writecb = null; + this._finalcb = null; + + // Just in case there is no preamble + this.write(BUF_CRLF); + } + + static detect(conType) { + return (conType.type === 'multipart' && conType.subtype === 'form-data'); + } + + _write(chunk, enc, cb) { + this._writecb = cb; + this._bparser.push(chunk, 0); + if (this._writecb) + callAndUnsetCb(this); + } + + _destroy(err, cb) { + this._hparser = null; + this._bparser = ignoreData; + if (!err) + err = checkEndState(this); + const fileStream = this._fileStream; + if (fileStream) { + this._fileStream = null; + fileStream.destroy(err); + } + cb(err); + } + + _final(cb) { + this._bparser.destroy(); + if (!this._complete) + return cb(new Error('Unexpected end of form')); + if (this._fileEndsLeft) + this._finalcb = finalcb.bind(null, this, cb); + else + finalcb(this, cb); + } +} + +function finalcb(self, cb, err) { + if (err) + return cb(err); + err = checkEndState(self); + cb(err); +} + +function checkEndState(self) { + if (self._hparser) + return new Error('Malformed part header'); + const fileStream = self._fileStream; + if (fileStream) { + self._fileStream = null; + fileStream.destroy(new Error('Unexpected end of file')); + } + if (!self._complete) + return new Error('Unexpected end of form'); +} + +const TOKEN = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +const FIELD_VCHAR = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, +]; + +module.exports = Multipart; diff --git a/node_modules/busboy/lib/types/urlencoded.js b/node_modules/busboy/lib/types/urlencoded.js new file mode 100644 index 0000000..5c463a2 --- /dev/null +++ b/node_modules/busboy/lib/types/urlencoded.js @@ -0,0 +1,350 @@ +'use strict'; + +const { Writable } = require('stream'); + +const { getDecoder } = require('../utils.js'); + +class URLEncoded extends Writable { + constructor(cfg) { + const streamOpts = { + autoDestroy: true, + emitClose: true, + highWaterMark: (typeof cfg.highWaterMark === 'number' + ? cfg.highWaterMark + : undefined), + }; + super(streamOpts); + + let charset = (cfg.defCharset || 'utf8'); + if (cfg.conType.params && typeof cfg.conType.params.charset === 'string') + charset = cfg.conType.params.charset; + + this.charset = charset; + + const limits = cfg.limits; + this.fieldSizeLimit = (limits && typeof limits.fieldSize === 'number' + ? limits.fieldSize + : 1 * 1024 * 1024); + this.fieldsLimit = (limits && typeof limits.fields === 'number' + ? limits.fields + : Infinity); + this.fieldNameSizeLimit = ( + limits && typeof limits.fieldNameSize === 'number' + ? limits.fieldNameSize + : 100 + ); + + this._inKey = true; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + this._fields = 0; + this._key = ''; + this._val = ''; + this._byte = -2; + this._lastPos = 0; + this._encode = 0; + this._decoder = getDecoder(charset); + } + + static detect(conType) { + return (conType.type === 'application' + && conType.subtype === 'x-www-form-urlencoded'); + } + + _write(chunk, enc, cb) { + if (this._fields >= this.fieldsLimit) + return cb(); + + let i = 0; + const len = chunk.length; + this._lastPos = 0; + + // Check if we last ended mid-percent-encoded byte + if (this._byte !== -2) { + i = readPctEnc(this, chunk, i, len); + if (i === -1) + return cb(new Error('Malformed urlencoded form')); + if (i >= len) + return cb(); + if (this._inKey) + ++this._bytesKey; + else + ++this._bytesVal; + } + +main: + while (i < len) { + if (this._inKey) { + // Parsing key + + i = skipKeyBytes(this, chunk, i, len); + + while (i < len) { + switch (chunk[i]) { + case 61: // '=' + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + this._lastPos = ++i; + this._key = this._decoder(this._key, this._encode); + this._encode = 0; + this._inKey = false; + continue main; + case 38: // '&' + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + this._lastPos = ++i; + this._key = this._decoder(this._key, this._encode); + this._encode = 0; + if (this._bytesKey > 0) { + this.emit( + 'field', + this._key, + '', + { nameTruncated: this._keyTrunc, + valueTruncated: false, + encoding: this.charset, + mimeType: 'text/plain' } + ); + } + this._key = ''; + this._val = ''; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + if (++this._fields >= this.fieldsLimit) { + this.emit('fieldsLimit'); + return cb(); + } + continue; + case 43: // '+' + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + this._key += ' '; + this._lastPos = i + 1; + break; + case 37: // '%' + if (this._encode === 0) + this._encode = 1; + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + this._lastPos = i + 1; + this._byte = -1; + i = readPctEnc(this, chunk, i + 1, len); + if (i === -1) + return cb(new Error('Malformed urlencoded form')); + if (i >= len) + return cb(); + ++this._bytesKey; + i = skipKeyBytes(this, chunk, i, len); + continue; + } + ++i; + ++this._bytesKey; + i = skipKeyBytes(this, chunk, i, len); + } + if (this._lastPos < i) + this._key += chunk.latin1Slice(this._lastPos, i); + } else { + // Parsing value + + i = skipValBytes(this, chunk, i, len); + + while (i < len) { + switch (chunk[i]) { + case 38: // '&' + if (this._lastPos < i) + this._val += chunk.latin1Slice(this._lastPos, i); + this._lastPos = ++i; + this._inKey = true; + this._val = this._decoder(this._val, this._encode); + this._encode = 0; + if (this._bytesKey > 0 || this._bytesVal > 0) { + this.emit( + 'field', + this._key, + this._val, + { nameTruncated: this._keyTrunc, + valueTruncated: this._valTrunc, + encoding: this.charset, + mimeType: 'text/plain' } + ); + } + this._key = ''; + this._val = ''; + this._keyTrunc = false; + this._valTrunc = false; + this._bytesKey = 0; + this._bytesVal = 0; + if (++this._fields >= this.fieldsLimit) { + this.emit('fieldsLimit'); + return cb(); + } + continue main; + case 43: // '+' + if (this._lastPos < i) + this._val += chunk.latin1Slice(this._lastPos, i); + this._val += ' '; + this._lastPos = i + 1; + break; + case 37: // '%' + if (this._encode === 0) + this._encode = 1; + if (this._lastPos < i) + this._val += chunk.latin1Slice(this._lastPos, i); + this._lastPos = i + 1; + this._byte = -1; + i = readPctEnc(this, chunk, i + 1, len); + if (i === -1) + return cb(new Error('Malformed urlencoded form')); + if (i >= len) + return cb(); + ++this._bytesVal; + i = skipValBytes(this, chunk, i, len); + continue; + } + ++i; + ++this._bytesVal; + i = skipValBytes(this, chunk, i, len); + } + if (this._lastPos < i) + this._val += chunk.latin1Slice(this._lastPos, i); + } + } + + cb(); + } + + _final(cb) { + if (this._byte !== -2) + return cb(new Error('Malformed urlencoded form')); + if (!this._inKey || this._bytesKey > 0 || this._bytesVal > 0) { + if (this._inKey) + this._key = this._decoder(this._key, this._encode); + else + this._val = this._decoder(this._val, this._encode); + this.emit( + 'field', + this._key, + this._val, + { nameTruncated: this._keyTrunc, + valueTruncated: this._valTrunc, + encoding: this.charset, + mimeType: 'text/plain' } + ); + } + cb(); + } +} + +function readPctEnc(self, chunk, pos, len) { + if (pos >= len) + return len; + + if (self._byte === -1) { + // We saw a '%' but no hex characters yet + const hexUpper = HEX_VALUES[chunk[pos++]]; + if (hexUpper === -1) + return -1; + + if (hexUpper >= 8) + self._encode = 2; // Indicate high bits detected + + if (pos < len) { + // Both hex characters are in this chunk + const hexLower = HEX_VALUES[chunk[pos++]]; + if (hexLower === -1) + return -1; + + if (self._inKey) + self._key += String.fromCharCode((hexUpper << 4) + hexLower); + else + self._val += String.fromCharCode((hexUpper << 4) + hexLower); + + self._byte = -2; + self._lastPos = pos; + } else { + // Only one hex character was available in this chunk + self._byte = hexUpper; + } + } else { + // We saw only one hex character so far + const hexLower = HEX_VALUES[chunk[pos++]]; + if (hexLower === -1) + return -1; + + if (self._inKey) + self._key += String.fromCharCode((self._byte << 4) + hexLower); + else + self._val += String.fromCharCode((self._byte << 4) + hexLower); + + self._byte = -2; + self._lastPos = pos; + } + + return pos; +} + +function skipKeyBytes(self, chunk, pos, len) { + // Skip bytes if we've truncated + if (self._bytesKey > self.fieldNameSizeLimit) { + if (!self._keyTrunc) { + if (self._lastPos < pos) + self._key += chunk.latin1Slice(self._lastPos, pos - 1); + } + self._keyTrunc = true; + for (; pos < len; ++pos) { + const code = chunk[pos]; + if (code === 61/* '=' */ || code === 38/* '&' */) + break; + ++self._bytesKey; + } + self._lastPos = pos; + } + + return pos; +} + +function skipValBytes(self, chunk, pos, len) { + // Skip bytes if we've truncated + if (self._bytesVal > self.fieldSizeLimit) { + if (!self._valTrunc) { + if (self._lastPos < pos) + self._val += chunk.latin1Slice(self._lastPos, pos - 1); + } + self._valTrunc = true; + for (; pos < len; ++pos) { + if (chunk[pos] === 38/* '&' */) + break; + ++self._bytesVal; + } + self._lastPos = pos; + } + + return pos; +} + +/* eslint-disable no-multi-spaces */ +const HEX_VALUES = [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +]; +/* eslint-enable no-multi-spaces */ + +module.exports = URLEncoded; diff --git a/node_modules/busboy/lib/utils.js b/node_modules/busboy/lib/utils.js new file mode 100644 index 0000000..8274f6c --- /dev/null +++ b/node_modules/busboy/lib/utils.js @@ -0,0 +1,596 @@ +'use strict'; + +function parseContentType(str) { + if (str.length === 0) + return; + + const params = Object.create(null); + let i = 0; + + // Parse type + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + if (code !== 47/* '/' */ || i === 0) + return; + break; + } + } + // Check for type without subtype + if (i === str.length) + return; + + const type = str.slice(0, i).toLowerCase(); + + // Parse subtype + const subtypeStart = ++i; + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + // Make sure we have a subtype + if (i === subtypeStart) + return; + + if (parseContentTypeParams(str, i, params) === undefined) + return; + break; + } + } + // Make sure we have a subtype + if (i === subtypeStart) + return; + + const subtype = str.slice(subtypeStart, i).toLowerCase(); + + return { type, subtype, params }; +} + +function parseContentTypeParams(str, i, params) { + while (i < str.length) { + // Consume whitespace + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) + break; + } + + // Ended on whitespace + if (i === str.length) + break; + + // Check for malformed parameter + if (str.charCodeAt(i++) !== 59/* ';' */) + return; + + // Consume whitespace + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) + break; + } + + // Ended on whitespace (malformed) + if (i === str.length) + return; + + let name; + const nameStart = i; + // Parse parameter name + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + if (code !== 61/* '=' */) + return; + break; + } + } + + // No value (malformed) + if (i === str.length) + return; + + name = str.slice(nameStart, i); + ++i; // Skip over '=' + + // No value (malformed) + if (i === str.length) + return; + + let value = ''; + let valueStart; + if (str.charCodeAt(i) === 34/* '"' */) { + valueStart = ++i; + let escaping = false; + // Parse quoted value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code === 92/* '\\' */) { + if (escaping) { + valueStart = i; + escaping = false; + } else { + value += str.slice(valueStart, i); + escaping = true; + } + continue; + } + if (code === 34/* '"' */) { + if (escaping) { + valueStart = i; + escaping = false; + continue; + } + value += str.slice(valueStart, i); + break; + } + if (escaping) { + valueStart = i - 1; + escaping = false; + } + // Invalid unescaped quoted character (malformed) + if (QDTEXT[code] !== 1) + return; + } + + // No end quote (malformed) + if (i === str.length) + return; + + ++i; // Skip over double quote + } else { + valueStart = i; + // Parse unquoted value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + // No value (malformed) + if (i === valueStart) + return; + break; + } + } + value = str.slice(valueStart, i); + } + + name = name.toLowerCase(); + if (params[name] === undefined) + params[name] = value; + } + + return params; +} + +function parseDisposition(str, defDecoder) { + if (str.length === 0) + return; + + const params = Object.create(null); + let i = 0; + + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + if (parseDispositionParams(str, i, params, defDecoder) === undefined) + return; + break; + } + } + + const type = str.slice(0, i).toLowerCase(); + + return { type, params }; +} + +function parseDispositionParams(str, i, params, defDecoder) { + while (i < str.length) { + // Consume whitespace + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) + break; + } + + // Ended on whitespace + if (i === str.length) + break; + + // Check for malformed parameter + if (str.charCodeAt(i++) !== 59/* ';' */) + return; + + // Consume whitespace + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code !== 32/* ' ' */ && code !== 9/* '\t' */) + break; + } + + // Ended on whitespace (malformed) + if (i === str.length) + return; + + let name; + const nameStart = i; + // Parse parameter name + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + if (code === 61/* '=' */) + break; + return; + } + } + + // No value (malformed) + if (i === str.length) + return; + + let value = ''; + let valueStart; + let charset; + //~ let lang; + name = str.slice(nameStart, i); + if (name.charCodeAt(name.length - 1) === 42/* '*' */) { + // Extended value + + const charsetStart = ++i; + // Parse charset name + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (CHARSET[code] !== 1) { + if (code !== 39/* '\'' */) + return; + break; + } + } + + // Incomplete charset (malformed) + if (i === str.length) + return; + + charset = str.slice(charsetStart, i); + ++i; // Skip over the '\'' + + //~ const langStart = ++i; + // Parse language name + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code === 39/* '\'' */) + break; + } + + // Incomplete language (malformed) + if (i === str.length) + return; + + //~ lang = str.slice(langStart, i); + ++i; // Skip over the '\'' + + // No value (malformed) + if (i === str.length) + return; + + valueStart = i; + + let encode = 0; + // Parse value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (EXTENDED_VALUE[code] !== 1) { + if (code === 37/* '%' */) { + let hexUpper; + let hexLower; + if (i + 2 < str.length + && (hexUpper = HEX_VALUES[str.charCodeAt(i + 1)]) !== -1 + && (hexLower = HEX_VALUES[str.charCodeAt(i + 2)]) !== -1) { + const byteVal = (hexUpper << 4) + hexLower; + value += str.slice(valueStart, i); + value += String.fromCharCode(byteVal); + i += 2; + valueStart = i + 1; + if (byteVal >= 128) + encode = 2; + else if (encode === 0) + encode = 1; + continue; + } + // '%' disallowed in non-percent encoded contexts (malformed) + return; + } + break; + } + } + + value += str.slice(valueStart, i); + value = convertToUTF8(value, charset, encode); + if (value === undefined) + return; + } else { + // Non-extended value + + ++i; // Skip over '=' + + // No value (malformed) + if (i === str.length) + return; + + if (str.charCodeAt(i) === 34/* '"' */) { + valueStart = ++i; + let escaping = false; + // Parse quoted value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (code === 92/* '\\' */) { + if (escaping) { + valueStart = i; + escaping = false; + } else { + value += str.slice(valueStart, i); + escaping = true; + } + continue; + } + if (code === 34/* '"' */) { + if (escaping) { + valueStart = i; + escaping = false; + continue; + } + value += str.slice(valueStart, i); + break; + } + if (escaping) { + valueStart = i - 1; + escaping = false; + } + // Invalid unescaped quoted character (malformed) + if (QDTEXT[code] !== 1) + return; + } + + // No end quote (malformed) + if (i === str.length) + return; + + ++i; // Skip over double quote + } else { + valueStart = i; + // Parse unquoted value + for (; i < str.length; ++i) { + const code = str.charCodeAt(i); + if (TOKEN[code] !== 1) { + // No value (malformed) + if (i === valueStart) + return; + break; + } + } + value = str.slice(valueStart, i); + } + + value = defDecoder(value, 2); + if (value === undefined) + return; + } + + name = name.toLowerCase(); + if (params[name] === undefined) + params[name] = value; + } + + return params; +} + +function getDecoder(charset) { + let lc; + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8; + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1; + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le; + case 'base64': + return decoders.base64; + default: + if (lc === undefined) { + lc = true; + charset = charset.toLowerCase(); + continue; + } + return decoders.other.bind(charset); + } + } +} + +const decoders = { + utf8: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') { + // If `data` never had any percent-encoded bytes or never had any that + // were outside of the ASCII range, then we can safely just return the + // input since UTF-8 is ASCII compatible + if (hint < 2) + return data; + + data = Buffer.from(data, 'latin1'); + } + return data.utf8Slice(0, data.length); + }, + + latin1: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') + return data; + return data.latin1Slice(0, data.length); + }, + + utf16le: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') + data = Buffer.from(data, 'latin1'); + return data.ucs2Slice(0, data.length); + }, + + base64: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') + data = Buffer.from(data, 'latin1'); + return data.base64Slice(0, data.length); + }, + + other: (data, hint) => { + if (data.length === 0) + return ''; + if (typeof data === 'string') + data = Buffer.from(data, 'latin1'); + try { + const decoder = new TextDecoder(this); + return decoder.decode(data); + } catch {} + }, +}; + +function convertToUTF8(data, charset, hint) { + const decode = getDecoder(charset); + if (decode) + return decode(data, hint); +} + +function basename(path) { + if (typeof path !== 'string') + return ''; + for (let i = path.length - 1; i >= 0; --i) { + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1); + return (path === '..' || path === '.' ? '' : path); + } + } + return (path === '..' || path === '.' ? '' : path); +} + +const TOKEN = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +/* eslint-disable no-multi-spaces */ +const HEX_VALUES = [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, +]; +/* eslint-enable no-multi-spaces */ + +module.exports = { + basename, + convertToUTF8, + getDecoder, + parseContentType, + parseDisposition, +}; diff --git a/node_modules/busboy/package.json b/node_modules/busboy/package.json new file mode 100644 index 0000000..ac2577f --- /dev/null +++ b/node_modules/busboy/package.json @@ -0,0 +1,22 @@ +{ "name": "busboy", + "version": "1.6.0", + "author": "Brian White ", + "description": "A streaming parser for HTML form data for node.js", + "main": "./lib/index.js", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "devDependencies": { + "@mscdex/eslint-config": "^1.1.0", + "eslint": "^7.32.0" + }, + "scripts": { + "test": "node test/test.js", + "lint": "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js lib test bench", + "lint:fix": "npm run lint -- --fix" + }, + "engines": { "node": ">=10.16.0" }, + "keywords": [ "uploads", "forms", "multipart", "form-data" ], + "licenses": [ { "type": "MIT", "url": "http://github.com/mscdex/busboy/raw/master/LICENSE" } ], + "repository": { "type": "git", "url": "http://github.com/mscdex/busboy.git" } +} diff --git a/node_modules/busboy/test/common.js b/node_modules/busboy/test/common.js new file mode 100644 index 0000000..fb82ad8 --- /dev/null +++ b/node_modules/busboy/test/common.js @@ -0,0 +1,109 @@ +'use strict'; + +const assert = require('assert'); +const { inspect } = require('util'); + +const mustCallChecks = []; + +function noop() {} + +function runCallChecks(exitCode) { + if (exitCode !== 0) return; + + const failed = mustCallChecks.filter((context) => { + if ('minimum' in context) { + context.messageSegment = `at least ${context.minimum}`; + return context.actual < context.minimum; + } + context.messageSegment = `exactly ${context.exact}`; + return context.actual !== context.exact; + }); + + failed.forEach((context) => { + console.error('Mismatched %s function calls. Expected %s, actual %d.', + context.name, + context.messageSegment, + context.actual); + console.error(context.stack.split('\n').slice(2).join('\n')); + }); + + if (failed.length) + process.exit(1); +} + +function mustCall(fn, exact) { + return _mustCallInner(fn, exact, 'exact'); +} + +function mustCallAtLeast(fn, minimum) { + return _mustCallInner(fn, minimum, 'minimum'); +} + +function _mustCallInner(fn, criteria = 1, field) { + if (process._exiting) + throw new Error('Cannot use common.mustCall*() in process exit handler'); + + if (typeof fn === 'number') { + criteria = fn; + fn = noop; + } else if (fn === undefined) { + fn = noop; + } + + if (typeof criteria !== 'number') + throw new TypeError(`Invalid ${field} value: ${criteria}`); + + const context = { + [field]: criteria, + actual: 0, + stack: inspect(new Error()), + name: fn.name || '' + }; + + // Add the exit listener only once to avoid listener leak warnings + if (mustCallChecks.length === 0) + process.on('exit', runCallChecks); + + mustCallChecks.push(context); + + function wrapped(...args) { + ++context.actual; + return fn.call(this, ...args); + } + // TODO: remove origFn? + wrapped.origFn = fn; + + return wrapped; +} + +function getCallSite(top) { + const originalStackFormatter = Error.prepareStackTrace; + Error.prepareStackTrace = (err, stack) => + `${stack[0].getFileName()}:${stack[0].getLineNumber()}`; + const err = new Error(); + Error.captureStackTrace(err, top); + // With the V8 Error API, the stack is not formatted until it is accessed + // eslint-disable-next-line no-unused-expressions + err.stack; + Error.prepareStackTrace = originalStackFormatter; + return err.stack; +} + +function mustNotCall(msg) { + const callSite = getCallSite(mustNotCall); + return function mustNotCall(...args) { + args = args.map(inspect).join(', '); + const argsInfo = (args.length > 0 + ? `\ncalled with arguments: ${args}` + : ''); + assert.fail( + `${msg || 'function should not have been called'} at ${callSite}` + + argsInfo); + }; +} + +module.exports = { + mustCall, + mustCallAtLeast, + mustNotCall, +}; diff --git a/node_modules/busboy/test/test-types-multipart-charsets.js b/node_modules/busboy/test/test-types-multipart-charsets.js new file mode 100644 index 0000000..ed9c38a --- /dev/null +++ b/node_modules/busboy/test/test-types-multipart-charsets.js @@ -0,0 +1,94 @@ +'use strict'; + +const assert = require('assert'); +const { inspect } = require('util'); + +const { mustCall } = require(`${__dirname}/common.js`); + +const busboy = require('..'); + +const input = Buffer.from([ + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="テスト.dat"', + 'Content-Type: application/octet-stream', + '', + 'A'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' +].join('\r\n')); +const boundary = '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k'; +const expected = [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('A'.repeat(1023)), + info: { + filename: 'テスト.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, +]; +const bb = busboy({ + defParamCharset: 'utf8', + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + } +}); +const results = []; + +bb.on('field', (name, val, info) => { + results.push({ type: 'field', name, val, info }); +}); + +bb.on('file', (name, stream, info) => { + const data = []; + let nb = 0; + const file = { + type: 'file', + name, + data: null, + info, + limited: false, + }; + results.push(file); + stream.on('data', (d) => { + data.push(d); + nb += d.length; + }).on('limit', () => { + file.limited = true; + }).on('close', () => { + file.data = Buffer.concat(data, nb); + assert.strictEqual(stream.truncated, file.limited); + }).once('error', (err) => { + file.err = err.message; + }); +}); + +bb.on('error', (err) => { + results.push({ error: err.message }); +}); + +bb.on('partsLimit', () => { + results.push('partsLimit'); +}); + +bb.on('filesLimit', () => { + results.push('filesLimit'); +}); + +bb.on('fieldsLimit', () => { + results.push('fieldsLimit'); +}); + +bb.on('close', mustCall(() => { + assert.deepStrictEqual( + results, + expected, + 'Results mismatch.\n' + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(expected)}` + ); +})); + +bb.end(input); diff --git a/node_modules/busboy/test/test-types-multipart-stream-pause.js b/node_modules/busboy/test/test-types-multipart-stream-pause.js new file mode 100644 index 0000000..df7268a --- /dev/null +++ b/node_modules/busboy/test/test-types-multipart-stream-pause.js @@ -0,0 +1,102 @@ +'use strict'; + +const assert = require('assert'); +const { randomFillSync } = require('crypto'); +const { inspect } = require('util'); + +const busboy = require('..'); + +const { mustCall } = require('./common.js'); + +const BOUNDARY = 'u2KxIV5yF1y+xUspOQCCZopaVgeV6Jxihv35XQJmuTx8X3sh'; + +function formDataSection(key, value) { + return Buffer.from( + `\r\n--${BOUNDARY}` + + `\r\nContent-Disposition: form-data; name="${key}"` + + `\r\n\r\n${value}` + ); +} + +function formDataFile(key, filename, contentType) { + const buf = Buffer.allocUnsafe(100000); + return Buffer.concat([ + Buffer.from(`\r\n--${BOUNDARY}\r\n`), + Buffer.from(`Content-Disposition: form-data; name="${key}"` + + `; filename="${filename}"\r\n`), + Buffer.from(`Content-Type: ${contentType}\r\n\r\n`), + randomFillSync(buf) + ]); +} + +const reqChunks = [ + Buffer.concat([ + formDataFile('file', 'file.bin', 'application/octet-stream'), + formDataSection('foo', 'foo value'), + ]), + formDataSection('bar', 'bar value'), + Buffer.from(`\r\n--${BOUNDARY}--\r\n`) +]; +const bb = busboy({ + headers: { + 'content-type': `multipart/form-data; boundary=${BOUNDARY}` + } +}); +const expected = [ + { type: 'file', + name: 'file', + info: { + filename: 'file.bin', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + }, + { type: 'field', + name: 'foo', + val: 'foo value', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'bar', + val: 'bar value', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, +]; +const results = []; + +bb.on('field', (name, val, info) => { + results.push({ type: 'field', name, val, info }); +}); + +bb.on('file', (name, stream, info) => { + results.push({ type: 'file', name, info }); + // Simulate a pipe where the destination is pausing (perhaps due to waiting + // for file system write to finish) + setTimeout(() => { + stream.resume(); + }, 10); +}); + +bb.on('close', mustCall(() => { + assert.deepStrictEqual( + results, + expected, + 'Results mismatch.\n' + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(expected)}` + ); +})); + +for (const chunk of reqChunks) + bb.write(chunk); +bb.end(); diff --git a/node_modules/busboy/test/test-types-multipart.js b/node_modules/busboy/test/test-types-multipart.js new file mode 100644 index 0000000..9755642 --- /dev/null +++ b/node_modules/busboy/test/test-types-multipart.js @@ -0,0 +1,1053 @@ +'use strict'; + +const assert = require('assert'); +const { inspect } = require('util'); + +const busboy = require('..'); + +const active = new Map(); + +const tests = [ + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'super alpha file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_1"', + '', + 'super beta file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'A'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="1k_b.dat"', + 'Content-Type: application/octet-stream', + '', + 'B'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'super alpha file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'file_name_1', + val: 'super beta file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('A'.repeat(1023)), + info: { + filename: '1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('B'.repeat(1023)), + info: { + filename: '1k_b.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + ], + what: 'Fields and files' + }, + { source: [ + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name="cont"', + '', + 'some random content', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name="pass"', + '', + 'some random pass', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name=bit', + '', + '2', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--' + ].join('\r\n') + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [ + { type: 'field', + name: 'cont', + val: 'some random content', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'pass', + val: 'some random pass', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'bit', + val: '2', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + ], + what: 'Fields only' + }, + { source: [ + '' + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [ + { error: 'Unexpected end of form' }, + ], + what: 'No fields and no files' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'super alpha file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + fileSize: 13, + fieldSize: 5 + }, + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'super', + info: { + nameTruncated: false, + valueTruncated: true, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ABCDEFGHIJKLM'), + info: { + filename: '1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: true, + }, + ], + what: 'Fields and files (limits)' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'super alpha file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + files: 0 + }, + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'super alpha file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + 'filesLimit', + ], + what: 'Fields and files (limits: 0 files)' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'super alpha file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_1"', + '', + 'super beta file', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'A'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="1k_b.dat"', + 'Content-Type: application/octet-stream', + '', + 'B'.repeat(1023), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'super alpha file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + { type: 'field', + name: 'file_name_1', + val: 'super beta file', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + ], + events: ['field'], + what: 'Fields and (ignored) files' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="/tmp/1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="C:\\files\\1k_b.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_2"; filename="relative/1k_c.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: '1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: '1k_b.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_2', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: '1k_c.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + ], + what: 'Files with filenames containing paths' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="/absolute/1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="C:\\absolute\\1k_b.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_2"; filename="relative/1k_c.dat"', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + preservePath: true, + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: '/absolute/1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: 'C:\\absolute\\1k_b.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_2', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: 'relative/1k_c.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + ], + what: 'Paths to be preserved through the preservePath option' + }, + { source: [ + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name="cont"', + 'Content-Type: ', + '', + 'some random content', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: ', + '', + 'some random pass', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--' + ].join('\r\n') + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [ + { type: 'field', + name: 'cont', + val: 'some random content', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + ], + what: 'Empty content-type and empty content-disposition' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="file"; filename*=utf-8\'\'n%C3%A4me.txt', + 'Content-Type: application/octet-stream', + '', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--' + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'file', + data: Buffer.from('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), + info: { + filename: 'näme.txt', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + }, + ], + what: 'Unicode filenames' + }, + { source: [ + ['--asdasdasdasd\r\n', + 'Content-Type: text/plain\r\n', + 'Content-Disposition: form-data; name="foo"\r\n', + '\r\n', + 'asd\r\n', + '--asdasdasdasd--' + ].join(':)') + ], + boundary: 'asdasdasdasd', + expected: [ + { error: 'Malformed part header' }, + { error: 'Unexpected end of form' }, + ], + what: 'Stopped mid-header' + }, + { source: [ + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY', + 'Content-Disposition: form-data; name="cont"', + 'Content-Type: application/json', + '', + '{}', + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--', + ].join('\r\n') + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [ + { type: 'field', + name: 'cont', + val: '{}', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'application/json', + }, + }, + ], + what: 'content-type for fields' + }, + { source: [ + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--', + ], + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY', + expected: [], + what: 'empty form' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name=upload_file_0; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + 'Content-Transfer-Encoding: binary', + '', + '', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.alloc(0), + info: { + filename: '1k_a.dat', + encoding: 'binary', + mimeType: 'application/octet-stream', + }, + limited: false, + err: 'Unexpected end of form', + }, + { error: 'Unexpected end of form' }, + ], + what: 'Stopped mid-file #1' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name=upload_file_0; filename="1k_a.dat"', + 'Content-Type: application/octet-stream', + '', + 'a', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('a'), + info: { + filename: '1k_a.dat', + encoding: '7bit', + mimeType: 'application/octet-stream', + }, + limited: false, + err: 'Unexpected end of form', + }, + { error: 'Unexpected end of form' }, + ], + what: 'Stopped mid-file #2' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('a'), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Text file with charset' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: ', + ' text/plain; charset=utf8', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('a'), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Folded header value' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Type: text/plain; charset=utf8', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [], + what: 'No Content-Disposition' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'a'.repeat(64 * 1024), + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: ', + ' text/plain; charset=utf8', + '', + 'bc', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + fieldSize: Infinity, + }, + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('bc'), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + events: [ 'file' ], + what: 'Skip field parts if no listener' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: ', + ' text/plain; charset=utf8', + '', + 'bc', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + parts: 1, + }, + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'a', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + 'partsLimit', + ], + what: 'Parts limit' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_0"', + '', + 'a', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; name="file_name_1"', + '', + 'b', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + fields: 1, + }, + expected: [ + { type: 'field', + name: 'file_name_0', + val: 'a', + info: { + nameTruncated: false, + valueTruncated: false, + encoding: '7bit', + mimeType: 'text/plain', + }, + }, + 'fieldsLimit', + ], + what: 'Fields limit' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'ab', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="notes2.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'cd', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + limits: { + files: 1, + }, + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ab'), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + 'filesLimit', + ], + what: 'Files limit' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + `name="upload_file_0"; filename="${'a'.repeat(64 * 1024)}.txt"`, + 'Content-Type: text/plain; charset=utf8', + '', + 'ab', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_1"; filename="notes2.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'cd', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { error: 'Malformed part header' }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('cd'), + info: { + filename: 'notes2.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Oversized part header' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + 'name="upload_file_0"; filename="notes.txt"', + 'Content-Type: text/plain; charset=utf8', + '', + 'a'.repeat(31) + '\r', + ].join('\r\n'), + 'b'.repeat(40), + '\r\n-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + fileHwm: 32, + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('a'.repeat(31) + '\r' + 'b'.repeat(40)), + info: { + filename: 'notes.txt', + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Lookbehind data should not stall file streams' + }, + { source: [ + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + `name="upload_file_0"; filename="${'a'.repeat(8 * 1024)}.txt"`, + 'Content-Type: text/plain; charset=utf8', + '', + 'ab', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + `name="upload_file_1"; filename="${'b'.repeat(8 * 1024)}.txt"`, + 'Content-Type: text/plain; charset=utf8', + '', + 'cd', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + 'Content-Disposition: form-data; ' + + `name="upload_file_2"; filename="${'c'.repeat(8 * 1024)}.txt"`, + 'Content-Type: text/plain; charset=utf8', + '', + 'ef', + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--', + ].join('\r\n') + ], + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k', + expected: [ + { type: 'file', + name: 'upload_file_0', + data: Buffer.from('ab'), + info: { + filename: `${'a'.repeat(8 * 1024)}.txt`, + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_1', + data: Buffer.from('cd'), + info: { + filename: `${'b'.repeat(8 * 1024)}.txt`, + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + { type: 'file', + name: 'upload_file_2', + data: Buffer.from('ef'), + info: { + filename: `${'c'.repeat(8 * 1024)}.txt`, + encoding: '7bit', + mimeType: 'text/plain', + }, + limited: false, + }, + ], + what: 'Header size limit should be per part' + }, + { source: [ + '\r\n--d1bf46b3-aa33-4061-b28d-6c5ced8b08ee\r\n', + 'Content-Type: application/gzip\r\n' + + 'Content-Encoding: gzip\r\n' + + 'Content-Disposition: form-data; name=batch-1; filename=batch-1' + + '\r\n\r\n', + '\r\n--d1bf46b3-aa33-4061-b28d-6c5ced8b08ee--', + ], + boundary: 'd1bf46b3-aa33-4061-b28d-6c5ced8b08ee', + expected: [ + { type: 'file', + name: 'batch-1', + data: Buffer.alloc(0), + info: { + filename: 'batch-1', + encoding: '7bit', + mimeType: 'application/gzip', + }, + limited: false, + }, + ], + what: 'Empty part' + }, +]; + +for (const test of tests) { + active.set(test, 1); + + const { what, boundary, events, limits, preservePath, fileHwm } = test; + const bb = busboy({ + fileHwm, + limits, + preservePath, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + } + }); + const results = []; + + if (events === undefined || events.includes('field')) { + bb.on('field', (name, val, info) => { + results.push({ type: 'field', name, val, info }); + }); + } + + if (events === undefined || events.includes('file')) { + bb.on('file', (name, stream, info) => { + const data = []; + let nb = 0; + const file = { + type: 'file', + name, + data: null, + info, + limited: false, + }; + results.push(file); + stream.on('data', (d) => { + data.push(d); + nb += d.length; + }).on('limit', () => { + file.limited = true; + }).on('close', () => { + file.data = Buffer.concat(data, nb); + assert.strictEqual(stream.truncated, file.limited); + }).once('error', (err) => { + file.err = err.message; + }); + }); + } + + bb.on('error', (err) => { + results.push({ error: err.message }); + }); + + bb.on('partsLimit', () => { + results.push('partsLimit'); + }); + + bb.on('filesLimit', () => { + results.push('filesLimit'); + }); + + bb.on('fieldsLimit', () => { + results.push('fieldsLimit'); + }); + + bb.on('close', () => { + active.delete(test); + + assert.deepStrictEqual( + results, + test.expected, + `[${what}] Results mismatch.\n` + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(test.expected)}` + ); + }); + + for (const src of test.source) { + const buf = (typeof src === 'string' ? Buffer.from(src, 'utf8') : src); + bb.write(buf); + } + bb.end(); +} + +// Byte-by-byte versions +for (let test of tests) { + test = { ...test }; + test.what += ' (byte-by-byte)'; + active.set(test, 1); + + const { what, boundary, events, limits, preservePath, fileHwm } = test; + const bb = busboy({ + fileHwm, + limits, + preservePath, + headers: { + 'content-type': `multipart/form-data; boundary=${boundary}`, + } + }); + const results = []; + + if (events === undefined || events.includes('field')) { + bb.on('field', (name, val, info) => { + results.push({ type: 'field', name, val, info }); + }); + } + + if (events === undefined || events.includes('file')) { + bb.on('file', (name, stream, info) => { + const data = []; + let nb = 0; + const file = { + type: 'file', + name, + data: null, + info, + limited: false, + }; + results.push(file); + stream.on('data', (d) => { + data.push(d); + nb += d.length; + }).on('limit', () => { + file.limited = true; + }).on('close', () => { + file.data = Buffer.concat(data, nb); + assert.strictEqual(stream.truncated, file.limited); + }).once('error', (err) => { + file.err = err.message; + }); + }); + } + + bb.on('error', (err) => { + results.push({ error: err.message }); + }); + + bb.on('partsLimit', () => { + results.push('partsLimit'); + }); + + bb.on('filesLimit', () => { + results.push('filesLimit'); + }); + + bb.on('fieldsLimit', () => { + results.push('fieldsLimit'); + }); + + bb.on('close', () => { + active.delete(test); + + assert.deepStrictEqual( + results, + test.expected, + `[${what}] Results mismatch.\n` + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(test.expected)}` + ); + }); + + for (const src of test.source) { + const buf = (typeof src === 'string' ? Buffer.from(src, 'utf8') : src); + for (let i = 0; i < buf.length; ++i) + bb.write(buf.slice(i, i + 1)); + } + bb.end(); +} + +{ + let exception = false; + process.once('uncaughtException', (ex) => { + exception = true; + throw ex; + }); + process.on('exit', () => { + if (exception || active.size === 0) + return; + process.exitCode = 1; + console.error('=========================='); + console.error(`${active.size} test(s) did not finish:`); + console.error('=========================='); + console.error(Array.from(active.keys()).map((v) => v.what).join('\n')); + }); +} diff --git a/node_modules/busboy/test/test-types-urlencoded.js b/node_modules/busboy/test/test-types-urlencoded.js new file mode 100644 index 0000000..c35962b --- /dev/null +++ b/node_modules/busboy/test/test-types-urlencoded.js @@ -0,0 +1,488 @@ +'use strict'; + +const assert = require('assert'); +const { transcode } = require('buffer'); +const { inspect } = require('util'); + +const busboy = require('..'); + +const active = new Map(); + +const tests = [ + { source: ['foo'], + expected: [ + ['foo', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Unassigned value' + }, + { source: ['foo=bar'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned value' + }, + { source: ['foo&bar=baz'], + expected: [ + ['foo', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['bar', + 'baz', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Unassigned and assigned value' + }, + { source: ['foo=bar&baz'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['baz', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned and unassigned value' + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['baz', + 'bla', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Two assigned values' + }, + { source: ['foo&bar'], + expected: [ + ['foo', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['bar', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Two unassigned values' + }, + { source: ['foo&bar&'], + expected: [ + ['foo', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['bar', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Two unassigned values and ampersand' + }, + { source: ['foo+1=bar+baz%2Bquux'], + expected: [ + ['foo 1', + 'bar baz+quux', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned key and value with (plus) space' + }, + { source: ['foo=bar%20baz%21'], + expected: [ + ['foo', + 'bar baz!', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned value with encoded bytes' + }, + { source: ['foo%20bar=baz%20bla%21'], + expected: [ + ['foo bar', + 'baz bla!', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned value with encoded bytes #2' + }, + { source: ['foo=bar%20baz%21&num=1000'], + expected: [ + ['foo', + 'bar baz!', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['num', + '1000', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Two assigned values, one with encoded bytes' + }, + { source: [ + Array.from(transcode(Buffer.from('foo'), 'utf8', 'utf16le')).map( + (n) => `%${n.toString(16).padStart(2, '0')}` + ).join(''), + '=', + Array.from(transcode(Buffer.from('😀!'), 'utf8', 'utf16le')).map( + (n) => `%${n.toString(16).padStart(2, '0')}` + ).join(''), + ], + expected: [ + ['foo', + '😀!', + { nameTruncated: false, + valueTruncated: false, + encoding: 'UTF-16LE', + mimeType: 'text/plain' }, + ], + ], + charset: 'UTF-16LE', + what: 'Encoded value with multi-byte charset' + }, + { source: [ + 'foo=<', + Array.from(transcode(Buffer.from('©:^þ'), 'utf8', 'latin1')).map( + (n) => `%${n.toString(16).padStart(2, '0')}` + ).join(''), + ], + expected: [ + ['foo', + '<©:^þ', + { nameTruncated: false, + valueTruncated: false, + encoding: 'ISO-8859-1', + mimeType: 'text/plain' }, + ], + ], + charset: 'ISO-8859-1', + what: 'Encoded value with single-byte, ASCII-compatible, non-UTF8 charset' + }, + { source: ['foo=bar&baz=bla'], + expected: [], + what: 'Limits: zero fields', + limits: { fields: 0 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: one field', + limits: { fields: 1 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['foo', + 'bar', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['baz', + 'bla', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: field part lengths match limits', + limits: { fieldNameSize: 3, fieldSize: 3 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['fo', + 'bar', + { nameTruncated: true, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['ba', + 'bla', + { nameTruncated: true, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated field name', + limits: { fieldNameSize: 2 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['foo', + 'ba', + { nameTruncated: false, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['baz', + 'bl', + { nameTruncated: false, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated field value', + limits: { fieldSize: 2 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['fo', + 'ba', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['ba', + 'bl', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated field name and value', + limits: { fieldNameSize: 2, fieldSize: 2 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['fo', + '', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['ba', + '', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated field name and zero value limit', + limits: { fieldNameSize: 2, fieldSize: 0 } + }, + { source: ['foo=bar&baz=bla'], + expected: [ + ['', + '', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ['', + '', + { nameTruncated: true, + valueTruncated: true, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Limits: truncated zero field name and zero value limit', + limits: { fieldNameSize: 0, fieldSize: 0 } + }, + { source: ['&'], + expected: [], + what: 'Ampersand' + }, + { source: ['&&&&&'], + expected: [], + what: 'Many ampersands' + }, + { source: ['='], + expected: [ + ['', + '', + { nameTruncated: false, + valueTruncated: false, + encoding: 'utf-8', + mimeType: 'text/plain' }, + ], + ], + what: 'Assigned value, empty name and value' + }, + { source: [''], + expected: [], + what: 'Nothing' + }, +]; + +for (const test of tests) { + active.set(test, 1); + + const { what } = test; + const charset = test.charset || 'utf-8'; + const bb = busboy({ + limits: test.limits, + headers: { + 'content-type': `application/x-www-form-urlencoded; charset=${charset}`, + }, + }); + const results = []; + + bb.on('field', (key, val, info) => { + results.push([key, val, info]); + }); + + bb.on('file', () => { + throw new Error(`[${what}] Unexpected file`); + }); + + bb.on('close', () => { + active.delete(test); + + assert.deepStrictEqual( + results, + test.expected, + `[${what}] Results mismatch.\n` + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(test.expected)}` + ); + }); + + for (const src of test.source) { + const buf = (typeof src === 'string' ? Buffer.from(src, 'utf8') : src); + bb.write(buf); + } + bb.end(); +} + +// Byte-by-byte versions +for (let test of tests) { + test = { ...test }; + test.what += ' (byte-by-byte)'; + active.set(test, 1); + + const { what } = test; + const charset = test.charset || 'utf-8'; + const bb = busboy({ + limits: test.limits, + headers: { + 'content-type': `application/x-www-form-urlencoded; charset="${charset}"`, + }, + }); + const results = []; + + bb.on('field', (key, val, info) => { + results.push([key, val, info]); + }); + + bb.on('file', () => { + throw new Error(`[${what}] Unexpected file`); + }); + + bb.on('close', () => { + active.delete(test); + + assert.deepStrictEqual( + results, + test.expected, + `[${what}] Results mismatch.\n` + + `Parsed: ${inspect(results)}\n` + + `Expected: ${inspect(test.expected)}` + ); + }); + + for (const src of test.source) { + const buf = (typeof src === 'string' ? Buffer.from(src, 'utf8') : src); + for (let i = 0; i < buf.length; ++i) + bb.write(buf.slice(i, i + 1)); + } + bb.end(); +} + +{ + let exception = false; + process.once('uncaughtException', (ex) => { + exception = true; + throw ex; + }); + process.on('exit', () => { + if (exception || active.size === 0) + return; + process.exitCode = 1; + console.error('=========================='); + console.error(`${active.size} test(s) did not finish:`); + console.error('=========================='); + console.error(Array.from(active.keys()).map((v) => v.what).join('\n')); + }); +} diff --git a/node_modules/busboy/test/test.js b/node_modules/busboy/test/test.js new file mode 100644 index 0000000..d0380f2 --- /dev/null +++ b/node_modules/busboy/test/test.js @@ -0,0 +1,20 @@ +'use strict'; + +const { spawnSync } = require('child_process'); +const { readdirSync } = require('fs'); +const { join } = require('path'); + +const files = readdirSync(__dirname).sort(); +for (const filename of files) { + if (filename.startsWith('test-')) { + const path = join(__dirname, filename); + console.log(`> Running ${filename} ...`); + const result = spawnSync(`${process.argv0} ${path}`, { + shell: true, + stdio: 'inherit', + windowsHide: true + }); + if (result.status !== 0) + process.exitCode = 1; + } +} diff --git a/node_modules/cacheable-request/LICENSE b/node_modules/cacheable-request/LICENSE new file mode 100644 index 0000000..f27ee9b --- /dev/null +++ b/node_modules/cacheable-request/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Luke Childs + +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/cacheable-request/README.md b/node_modules/cacheable-request/README.md new file mode 100644 index 0000000..725e7e0 --- /dev/null +++ b/node_modules/cacheable-request/README.md @@ -0,0 +1,206 @@ +# cacheable-request + +> Wrap native HTTP requests with RFC compliant cache support + +[![Build Status](https://travis-ci.org/lukechilds/cacheable-request.svg?branch=master)](https://travis-ci.org/lukechilds/cacheable-request) +[![Coverage Status](https://coveralls.io/repos/github/lukechilds/cacheable-request/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/cacheable-request?branch=master) +[![npm](https://img.shields.io/npm/dm/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) +[![npm](https://img.shields.io/npm/v/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) + +[RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching for native Node.js HTTP/HTTPS requests. Caching works out of the box in memory or is easily pluggable with a wide range of storage adapters. + +**Note:** This is a low level wrapper around the core HTTP modules, it's not a high level request library. + +## Features + +- Only stores cacheable responses as defined by RFC 7234 +- Fresh cache entries are served directly from cache +- Stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers +- 304 responses from revalidation requests use cached body +- Updates `Age` header on cached responses +- Can completely bypass cache on a per request basis +- In memory cache by default +- Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters +- Easily plug in your own or third-party storage adapters +- If DB connection fails, cache is automatically bypassed ([disabled by default](#optsautomaticfailover)) +- Adds cache support to any existing HTTP code with minimal changes +- Uses [http-cache-semantics](https://github.com/pornel/http-cache-semantics) internally for HTTP RFC 7234 compliance + +## Install + +```shell +npm install cacheable-request +``` + +## Usage + +```js +const http = require('http'); +const CacheableRequest = require('cacheable-request'); + +// Then instead of +const req = http.request('http://example.com', cb); +req.end(); + +// You can do +const cacheableRequest = new CacheableRequest(http.request); +const cacheReq = cacheableRequest('http://example.com', cb); +cacheReq.on('request', req => req.end()); +// Future requests to 'example.com' will be returned from cache if still valid + +// You pass in any other http.request API compatible method to be wrapped with cache support: +const cacheableRequest = new CacheableRequest(https.request); +const cacheableRequest = new CacheableRequest(electron.net); +``` + +## Storage Adapters + +`cacheable-request` uses [Keyv](https://github.com/lukechilds/keyv) to support a wide range of storage adapters. + +For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter: + +``` +npm install @keyv/redis +``` + +And then you can pass `CacheableRequest` your connection string: + +```js +const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379'); +``` + +[View all official Keyv storage adapters.](https://github.com/lukechilds/keyv#official-storage-adapters) + +Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution. + +e.g The following are all valid storage adapters + +```js +const storageAdapter = new Map(); +// or +const storageAdapter = require('./my-storage-adapter'); +// or +const QuickLRU = require('quick-lru'); +const storageAdapter = new QuickLRU({ maxSize: 1000 }); + +const cacheableRequest = new CacheableRequest(http.request, storageAdapter); +``` + +View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters. + +## API + +### new cacheableRequest(request, [storageAdapter]) + +Returns the provided request function wrapped with cache support. + +#### request + +Type: `function` + +Request function to wrap with cache support. Should be [`http.request`](https://nodejs.org/api/http.html#http_http_request_options_callback) or a similar API compatible request function. + +#### storageAdapter + +Type: `Keyv storage adapter`
+Default: `new Map()` + +A [Keyv](https://github.com/lukechilds/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter. + +### Instance + +#### cacheableRequest(opts, [cb]) + +Returns an event emitter. + +##### opts + +Type: `object`, `string` + +- Any of the default request functions options. +- Any [`http-cache-semantics`](https://github.com/kornelski/http-cache-semantics#constructor-options) options. +- Any of the following: + +###### opts.cache + +Type: `boolean`
+Default: `true` + +If the cache should be used. Setting this to false will completely bypass the cache for the current request. + +###### opts.strictTtl + +Type: `boolean`
+Default: `false` + +If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. + +If set to `false` (default), after a cached resource's TTL expires it is kept in the cache and will be revalidated on the next request with `If-None-Match`/`If-Modified-Since` headers. + +###### opts.maxTtl + +Type: `number`
+Default: `undefined` + +Limits TTL. The `number` represents milliseconds. + +###### opts.automaticFailover + +Type: `boolean`
+Default: `false` + +When set to `true`, if the DB connection fails we will automatically fallback to a network request. DB errors will still be emitted to notify you of the problem even though the request callback may succeed. + +###### opts.forceRefresh + +Type: `boolean`
+Default: `false` + +Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a new request and override the cache instead. + +##### cb + +Type: `function` + +The callback function which will receive the response as an argument. + +The response can be either a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) or a [responselike object](https://github.com/lukechilds/responselike). The response will also have a `fromCache` property set with a boolean value. + +##### .on('request', request) + +`request` event to get the request object of the request. + +**Note:** This event will only fire if an HTTP request is actually made, not when a response is retrieved from cache. However, you should always handle the `request` event to end the request and handle any potential request errors. + +##### .on('response', response) + +`response` event to get the response object from the HTTP request or cache. + +##### .on('error', error) + +`error` event emitted in case of an error with the cache. + +Errors emitted here will be an instance of `CacheableRequest.RequestError` or `CacheableRequest.CacheError`. You will only ever receive a `RequestError` if the request function throws (normally caused by invalid user input). Normal request errors should be handled inside the `request` event. + +To properly handle all error scenarios you should use the following pattern: + +```js +cacheableRequest('example.com', cb) + .on('error', err => { + if (err instanceof CacheableRequest.CacheError) { + handleCacheError(err); // Cache error + } else if (err instanceof CacheableRequest.RequestError) { + handleRequestError(err); // Request function thrown + } + }) + .on('request', req => { + req.on('error', handleRequestError); // Request error emitted + req.end(); + }); +``` + +**Note:** Database connection errors are emitted here, however `cacheable-request` will attempt to re-request the resource and bypass the cache on a connection error. Therefore a database connection error doesn't necessarily mean the request won't be fulfilled. + +## License + +MIT © Luke Childs diff --git a/node_modules/cacheable-request/node_modules/get-stream/buffer-stream.js b/node_modules/cacheable-request/node_modules/get-stream/buffer-stream.js new file mode 100644 index 0000000..2dd7574 --- /dev/null +++ b/node_modules/cacheable-request/node_modules/get-stream/buffer-stream.js @@ -0,0 +1,52 @@ +'use strict'; +const {PassThrough: PassThroughStream} = require('stream'); + +module.exports = options => { + options = {...options}; + + const {array} = options; + let {encoding} = options; + const isBuffer = encoding === 'buffer'; + let objectMode = false; + + if (array) { + objectMode = !(encoding || isBuffer); + } else { + encoding = encoding || 'utf8'; + } + + if (isBuffer) { + encoding = null; + } + + const stream = new PassThroughStream({objectMode}); + + if (encoding) { + stream.setEncoding(encoding); + } + + let length = 0; + const chunks = []; + + stream.on('data', chunk => { + chunks.push(chunk); + + if (objectMode) { + length = chunks.length; + } else { + length += chunk.length; + } + }); + + stream.getBufferedValue = () => { + if (array) { + return chunks; + } + + return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); + }; + + stream.getBufferedLength = () => length; + + return stream; +}; diff --git a/node_modules/cacheable-request/node_modules/get-stream/index.d.ts b/node_modules/cacheable-request/node_modules/get-stream/index.d.ts new file mode 100644 index 0000000..7b98134 --- /dev/null +++ b/node_modules/cacheable-request/node_modules/get-stream/index.d.ts @@ -0,0 +1,108 @@ +/// +import {Stream} from 'stream'; + +declare class MaxBufferErrorClass extends Error { + readonly name: 'MaxBufferError'; + constructor(); +} + +declare namespace getStream { + interface Options { + /** + Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `MaxBufferError` error. + + @default Infinity + */ + readonly maxBuffer?: number; + } + + interface OptionsWithEncoding extends Options { + /** + [Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream. + + @default 'utf8' + */ + readonly encoding?: EncodingType; + } + + type MaxBufferError = MaxBufferErrorClass; +} + +declare const getStream: { + /** + Get the `stream` as a string. + + @returns A promise that resolves when the end event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode. + + @example + ``` + import * as fs from 'fs'; + import getStream = require('get-stream'); + + (async () => { + const stream = fs.createReadStream('unicorn.txt'); + + console.log(await getStream(stream)); + // ,,))))))));, + // __)))))))))))))), + // \|/ -\(((((''''((((((((. + // -*-==//////(('' . `)))))), + // /|\ ))| o ;-. '((((( ,(, + // ( `| / ) ;))))' ,_))^;(~ + // | | | ,))((((_ _____------~~~-. %,;(;(>';'~ + // o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ + // ; ''''```` `: `:::|\,__,%% );`'; ~ + // | _ ) / `:|`----' `-' + // ______/\/~ | / / + // /~;;.____/;;' / ___--,-( `;;;/ + // / // _;______;'------~~~~~ /;;/\ / + // // | | / ; \;;,\ + // (<_ | ; /',/-----' _> + // \_| ||_ //~;~~~~~~~~~ + // `\_| (,~~ + // \~\ + // ~~ + })(); + ``` + */ + (stream: Stream, options?: getStream.OptionsWithEncoding): Promise; + + /** + Get the `stream` as a buffer. + + It honors the `maxBuffer` option as above, but it refers to byte length rather than string length. + */ + buffer( + stream: Stream, + options?: getStream.OptionsWithEncoding + ): Promise; + + /** + Get the `stream` as an array of values. + + It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen: + + - When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes). + - When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array. + - When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array. + */ + array( + stream: Stream, + options?: getStream.Options + ): Promise; + array( + stream: Stream, + options: getStream.OptionsWithEncoding<'buffer'> + ): Promise; + array( + stream: Stream, + options: getStream.OptionsWithEncoding + ): Promise; + + MaxBufferError: typeof MaxBufferErrorClass; + + // TODO: Remove this for the next major release + default: typeof getStream; +}; + +export = getStream; diff --git a/node_modules/cacheable-request/node_modules/get-stream/index.js b/node_modules/cacheable-request/node_modules/get-stream/index.js new file mode 100644 index 0000000..71f3991 --- /dev/null +++ b/node_modules/cacheable-request/node_modules/get-stream/index.js @@ -0,0 +1,60 @@ +'use strict'; +const {constants: BufferConstants} = require('buffer'); +const pump = require('pump'); +const bufferStream = require('./buffer-stream'); + +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} + +async function getStream(inputStream, options) { + if (!inputStream) { + return Promise.reject(new Error('Expected a stream')); + } + + options = { + maxBuffer: Infinity, + ...options + }; + + const {maxBuffer} = options; + + let stream; + await new Promise((resolve, reject) => { + const rejectPromise = error => { + // Don't retrieve an oversized buffer. + if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { + error.bufferedData = stream.getBufferedValue(); + } + + reject(error); + }; + + stream = pump(inputStream, bufferStream(options), error => { + if (error) { + rejectPromise(error); + return; + } + + resolve(); + }); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }); + + return stream.getBufferedValue(); +} + +module.exports = getStream; +// TODO: Remove this for the next major release +module.exports.default = getStream; +module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); +module.exports.array = (stream, options) => getStream(stream, {...options, array: true}); +module.exports.MaxBufferError = MaxBufferError; diff --git a/node_modules/cacheable-request/node_modules/get-stream/license b/node_modules/cacheable-request/node_modules/get-stream/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/cacheable-request/node_modules/get-stream/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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/cacheable-request/node_modules/get-stream/package.json b/node_modules/cacheable-request/node_modules/get-stream/package.json new file mode 100644 index 0000000..4b95591 --- /dev/null +++ b/node_modules/cacheable-request/node_modules/get-stream/package.json @@ -0,0 +1,85 @@ +{ + "_args": [ + [ + "get-stream@5.2.0", + "/home/other/discord_bot" + ] + ], + "_from": "get-stream@5.2.0", + "_id": "get-stream@5.2.0", + "_inBundle": false, + "_integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "_location": "/cacheable-request/get-stream", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "get-stream@5.2.0", + "name": "get-stream", + "escapedName": "get-stream", + "rawSpec": "5.2.0", + "saveSpec": null, + "fetchSpec": "5.2.0" + }, + "_requiredBy": [ + "/cacheable-request" + ], + "_resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "_spec": "5.2.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/get-stream/issues" + }, + "dependencies": { + "pump": "^3.0.0" + }, + "description": "Get a stream as a string, buffer, or array", + "devDependencies": { + "@types/node": "^12.0.7", + "ava": "^2.0.0", + "into-stream": "^5.0.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts", + "buffer-stream.js" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/get-stream#readme", + "keywords": [ + "get", + "stream", + "promise", + "concat", + "string", + "text", + "buffer", + "read", + "data", + "consume", + "readable", + "readablestream", + "array", + "object" + ], + "license": "MIT", + "name": "get-stream", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/get-stream.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "5.2.0" +} diff --git a/node_modules/cacheable-request/node_modules/get-stream/readme.md b/node_modules/cacheable-request/node_modules/get-stream/readme.md new file mode 100644 index 0000000..7d7565d --- /dev/null +++ b/node_modules/cacheable-request/node_modules/get-stream/readme.md @@ -0,0 +1,124 @@ +# get-stream [![Build Status](https://travis-ci.com/sindresorhus/get-stream.svg?branch=master)](https://travis-ci.com/github/sindresorhus/get-stream) + +> Get a stream as a string, buffer, or array + +## Install + +``` +$ npm install get-stream +``` + +## Usage + +```js +const fs = require('fs'); +const getStream = require('get-stream'); + +(async () => { + const stream = fs.createReadStream('unicorn.txt'); + + console.log(await getStream(stream)); + /* + ,,))))))));, + __)))))))))))))), + \|/ -\(((((''''((((((((. + -*-==//////(('' . `)))))), + /|\ ))| o ;-. '((((( ,(, + ( `| / ) ;))))' ,_))^;(~ + | | | ,))((((_ _____------~~~-. %,;(;(>';'~ + o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ + ; ''''```` `: `:::|\,__,%% );`'; ~ + | _ ) / `:|`----' `-' + ______/\/~ | / / + /~;;.____/;;' / ___--,-( `;;;/ + / // _;______;'------~~~~~ /;;/\ / + // | | / ; \;;,\ + (<_ | ; /',/-----' _> + \_| ||_ //~;~~~~~~~~~ + `\_| (,~~ + \~\ + ~~ + */ +})(); +``` + +## API + +The methods returns a promise that resolves when the `end` event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode. + +### getStream(stream, options?) + +Get the `stream` as a string. + +#### options + +Type: `object` + +##### encoding + +Type: `string`\ +Default: `'utf8'` + +[Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream. + +##### maxBuffer + +Type: `number`\ +Default: `Infinity` + +Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `getStream.MaxBufferError` error. + +### getStream.buffer(stream, options?) + +Get the `stream` as a buffer. + +It honors the `maxBuffer` option as above, but it refers to byte length rather than string length. + +### getStream.array(stream, options?) + +Get the `stream` as an array of values. + +It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen: + +- When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes). + +- When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array. + +- When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array. + +## Errors + +If the input stream emits an `error` event, the promise will be rejected with the error. The buffered data will be attached to the `bufferedData` property of the error. + +```js +(async () => { + try { + await getStream(streamThatErrorsAtTheEnd('unicorn')); + } catch (error) { + console.log(error.bufferedData); + //=> 'unicorn' + } +})() +``` + +## FAQ + +### How is this different from [`concat-stream`](https://github.com/maxogden/concat-stream)? + +This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, buffer, or array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge `readable-stream` package. + +## Related + +- [get-stdin](https://github.com/sindresorhus/get-stdin) - Get stdin as a string or buffer + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/cacheable-request/node_modules/lowercase-keys/index.d.ts b/node_modules/cacheable-request/node_modules/lowercase-keys/index.d.ts new file mode 100644 index 0000000..dc90a75 --- /dev/null +++ b/node_modules/cacheable-request/node_modules/lowercase-keys/index.d.ts @@ -0,0 +1,16 @@ +/** +Lowercase the keys of an object. + +@returns A new object with the keys lowercased. + +@example +``` +import lowercaseKeys = require('lowercase-keys'); + +lowercaseKeys({FOO: true, bAr: false}); +//=> {foo: true, bar: false} +``` +*/ +declare function lowercaseKeys(object: {[key: string]: T}): {[key: string]: T}; + +export = lowercaseKeys; diff --git a/node_modules/cacheable-request/node_modules/lowercase-keys/index.js b/node_modules/cacheable-request/node_modules/lowercase-keys/index.js new file mode 100644 index 0000000..357fb8f --- /dev/null +++ b/node_modules/cacheable-request/node_modules/lowercase-keys/index.js @@ -0,0 +1,10 @@ +'use strict'; +module.exports = object => { + const result = {}; + + for (const [key, value] of Object.entries(object)) { + result[key.toLowerCase()] = value; + } + + return result; +}; diff --git a/node_modules/cacheable-request/node_modules/lowercase-keys/license b/node_modules/cacheable-request/node_modules/lowercase-keys/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/cacheable-request/node_modules/lowercase-keys/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/cacheable-request/node_modules/lowercase-keys/package.json b/node_modules/cacheable-request/node_modules/lowercase-keys/package.json new file mode 100644 index 0000000..b6fb38f --- /dev/null +++ b/node_modules/cacheable-request/node_modules/lowercase-keys/package.json @@ -0,0 +1,73 @@ +{ + "_args": [ + [ + "lowercase-keys@2.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "lowercase-keys@2.0.0", + "_id": "lowercase-keys@2.0.0", + "_inBundle": false, + "_integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==", + "_location": "/cacheable-request/lowercase-keys", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "lowercase-keys@2.0.0", + "name": "lowercase-keys", + "escapedName": "lowercase-keys", + "rawSpec": "2.0.0", + "saveSpec": null, + "fetchSpec": "2.0.0" + }, + "_requiredBy": [ + "/cacheable-request" + ], + "_resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "_spec": "2.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/lowercase-keys/issues" + }, + "description": "Lowercase the keys of an object", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/lowercase-keys#readme", + "keywords": [ + "object", + "assign", + "extend", + "properties", + "lowercase", + "lower-case", + "case", + "keys", + "key" + ], + "license": "MIT", + "name": "lowercase-keys", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/lowercase-keys.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.0.0" +} diff --git a/node_modules/cacheable-request/node_modules/lowercase-keys/readme.md b/node_modules/cacheable-request/node_modules/lowercase-keys/readme.md new file mode 100644 index 0000000..b1ed061 --- /dev/null +++ b/node_modules/cacheable-request/node_modules/lowercase-keys/readme.md @@ -0,0 +1,32 @@ +# lowercase-keys [![Build Status](https://travis-ci.org/sindresorhus/lowercase-keys.svg?branch=master)](https://travis-ci.org/sindresorhus/lowercase-keys) + +> Lowercase the keys of an object + + +## Install + +``` +$ npm install lowercase-keys +``` + + +## Usage + +```js +const lowercaseKeys = require('lowercase-keys'); + +lowercaseKeys({FOO: true, bAr: false}); +//=> {foo: true, bar: false} +``` + + +## API + +### lowercaseKeys(object) + +Returns a new object with the keys lowercased. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/cacheable-request/package.json b/node_modules/cacheable-request/package.json new file mode 100644 index 0000000..c883179 --- /dev/null +++ b/node_modules/cacheable-request/package.json @@ -0,0 +1,97 @@ +{ + "_args": [ + [ + "cacheable-request@6.1.0", + "/home/other/discord_bot" + ] + ], + "_from": "cacheable-request@6.1.0", + "_id": "cacheable-request@6.1.0", + "_inBundle": false, + "_integrity": "sha512-Oj3cAGPCqOZX7Rz64Uny2GYAZNliQSqfbePrgAQ1wKAihYmCUnraBtJtKcGR4xz7wF+LoJC+ssFZvv5BgF9Igg==", + "_location": "/cacheable-request", + "_phantomChildren": { + "pump": "3.0.0" + }, + "_requested": { + "type": "version", + "registry": true, + "raw": "cacheable-request@6.1.0", + "name": "cacheable-request", + "escapedName": "cacheable-request", + "rawSpec": "6.1.0", + "saveSpec": null, + "fetchSpec": "6.1.0" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-6.1.0.tgz", + "_spec": "6.1.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Luke Childs", + "email": "lukechilds123@gmail.com", + "url": "http://lukechilds.co.uk" + }, + "bugs": { + "url": "https://github.com/lukechilds/cacheable-request/issues" + }, + "dependencies": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^3.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^4.1.0", + "responselike": "^1.0.2" + }, + "description": "Wrap native HTTP requests with RFC compliant cache support", + "devDependencies": { + "@keyv/sqlite": "^2.0.0", + "ava": "^1.1.0", + "coveralls": "^3.0.0", + "create-test-server": "3.0.0", + "delay": "^4.0.0", + "eslint-config-xo-lukechilds": "^1.0.0", + "nyc": "^14.1.1", + "pify": "^4.0.0", + "sqlite3": "^4.0.2", + "this": "^1.0.2", + "xo": "^0.23.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "src" + ], + "homepage": "https://github.com/lukechilds/cacheable-request#readme", + "keywords": [ + "HTTP", + "HTTPS", + "cache", + "caching", + "layer", + "cacheable", + "RFC 7234", + "RFC", + "7234", + "compliant" + ], + "license": "MIT", + "main": "src/index.js", + "name": "cacheable-request", + "repository": { + "type": "git", + "url": "git+https://github.com/lukechilds/cacheable-request.git" + }, + "scripts": { + "coverage": "nyc report --reporter=text-lcov | coveralls", + "test": "xo && nyc ava" + }, + "version": "6.1.0", + "xo": { + "extends": "xo-lukechilds" + } +} diff --git a/node_modules/cacheable-request/src/index.js b/node_modules/cacheable-request/src/index.js new file mode 100644 index 0000000..3fcea3f --- /dev/null +++ b/node_modules/cacheable-request/src/index.js @@ -0,0 +1,251 @@ +'use strict'; + +const EventEmitter = require('events'); +const urlLib = require('url'); +const normalizeUrl = require('normalize-url'); +const getStream = require('get-stream'); +const CachePolicy = require('http-cache-semantics'); +const Response = require('responselike'); +const lowercaseKeys = require('lowercase-keys'); +const cloneResponse = require('clone-response'); +const Keyv = require('keyv'); + +class CacheableRequest { + constructor(request, cacheAdapter) { + if (typeof request !== 'function') { + throw new TypeError('Parameter `request` must be a function'); + } + + this.cache = new Keyv({ + uri: typeof cacheAdapter === 'string' && cacheAdapter, + store: typeof cacheAdapter !== 'string' && cacheAdapter, + namespace: 'cacheable-request' + }); + + return this.createCacheableRequest(request); + } + + createCacheableRequest(request) { + return (opts, cb) => { + let url; + if (typeof opts === 'string') { + url = normalizeUrlObject(urlLib.parse(opts)); + opts = {}; + } else if (opts instanceof urlLib.URL) { + url = normalizeUrlObject(urlLib.parse(opts.toString())); + opts = {}; + } else { + const [pathname, ...searchParts] = (opts.path || '').split('?'); + const search = searchParts.length > 0 ? + `?${searchParts.join('?')}` : + ''; + url = normalizeUrlObject({ ...opts, pathname, search }); + } + + opts = { + headers: {}, + method: 'GET', + cache: true, + strictTtl: false, + automaticFailover: false, + ...opts, + ...urlObjectToRequestOptions(url) + }; + opts.headers = lowercaseKeys(opts.headers); + + const ee = new EventEmitter(); + const normalizedUrlString = normalizeUrl( + urlLib.format(url), + { + stripWWW: false, + removeTrailingSlash: false, + stripAuthentication: false + } + ); + const key = `${opts.method}:${normalizedUrlString}`; + let revalidate = false; + let madeRequest = false; + + const makeRequest = opts => { + madeRequest = true; + let requestErrored = false; + let requestErrorCallback; + + const requestErrorPromise = new Promise(resolve => { + requestErrorCallback = () => { + if (!requestErrored) { + requestErrored = true; + resolve(); + } + }; + }); + + const handler = response => { + if (revalidate && !opts.forceRefresh) { + response.status = response.statusCode; + const revalidatedPolicy = CachePolicy.fromObject(revalidate.cachePolicy).revalidatedPolicy(opts, response); + if (!revalidatedPolicy.modified) { + const headers = revalidatedPolicy.policy.responseHeaders(); + response = new Response(revalidate.statusCode, headers, revalidate.body, revalidate.url); + response.cachePolicy = revalidatedPolicy.policy; + response.fromCache = true; + } + } + + if (!response.fromCache) { + response.cachePolicy = new CachePolicy(opts, response, opts); + response.fromCache = false; + } + + let clonedResponse; + if (opts.cache && response.cachePolicy.storable()) { + clonedResponse = cloneResponse(response); + + (async () => { + try { + const bodyPromise = getStream.buffer(response); + + await Promise.race([ + requestErrorPromise, + new Promise(resolve => response.once('end', resolve)) + ]); + + if (requestErrored) { + return; + } + + const body = await bodyPromise; + + const value = { + cachePolicy: response.cachePolicy.toObject(), + url: response.url, + statusCode: response.fromCache ? revalidate.statusCode : response.statusCode, + body + }; + + let ttl = opts.strictTtl ? response.cachePolicy.timeToLive() : undefined; + if (opts.maxTtl) { + ttl = ttl ? Math.min(ttl, opts.maxTtl) : opts.maxTtl; + } + + await this.cache.set(key, value, ttl); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } else if (opts.cache && revalidate) { + (async () => { + try { + await this.cache.delete(key); + } catch (error) { + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + } + + ee.emit('response', clonedResponse || response); + if (typeof cb === 'function') { + cb(clonedResponse || response); + } + }; + + try { + const req = request(opts, handler); + req.once('error', requestErrorCallback); + req.once('abort', requestErrorCallback); + ee.emit('request', req); + } catch (error) { + ee.emit('error', new CacheableRequest.RequestError(error)); + } + }; + + (async () => { + const get = async opts => { + await Promise.resolve(); + + const cacheEntry = opts.cache ? await this.cache.get(key) : undefined; + if (typeof cacheEntry === 'undefined') { + return makeRequest(opts); + } + + const policy = CachePolicy.fromObject(cacheEntry.cachePolicy); + if (policy.satisfiesWithoutRevalidation(opts) && !opts.forceRefresh) { + const headers = policy.responseHeaders(); + const response = new Response(cacheEntry.statusCode, headers, cacheEntry.body, cacheEntry.url); + response.cachePolicy = policy; + response.fromCache = true; + + ee.emit('response', response); + if (typeof cb === 'function') { + cb(response); + } + } else { + revalidate = cacheEntry; + opts.headers = policy.revalidationHeaders(opts); + makeRequest(opts); + } + }; + + const errorHandler = error => ee.emit('error', new CacheableRequest.CacheError(error)); + this.cache.once('error', errorHandler); + ee.on('response', () => this.cache.removeListener('error', errorHandler)); + + try { + await get(opts); + } catch (error) { + if (opts.automaticFailover && !madeRequest) { + makeRequest(opts); + } + + ee.emit('error', new CacheableRequest.CacheError(error)); + } + })(); + + return ee; + }; + } +} + +function urlObjectToRequestOptions(url) { + const options = { ...url }; + options.path = `${url.pathname || '/'}${url.search || ''}`; + delete options.pathname; + delete options.search; + return options; +} + +function normalizeUrlObject(url) { + // If url was parsed by url.parse or new URL: + // - hostname will be set + // - host will be hostname[:port] + // - port will be set if it was explicit in the parsed string + // Otherwise, url was from request options: + // - hostname or host may be set + // - host shall not have port encoded + return { + protocol: url.protocol, + auth: url.auth, + hostname: url.hostname || url.host || 'localhost', + port: url.port, + pathname: url.pathname, + search: url.search + }; +} + +CacheableRequest.RequestError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'RequestError'; + Object.assign(this, error); + } +}; + +CacheableRequest.CacheError = class extends Error { + constructor(error) { + super(error.message); + this.name = 'CacheError'; + Object.assign(this, error); + } +}; + +module.exports = CacheableRequest; diff --git a/node_modules/call-bind/.eslintignore b/node_modules/call-bind/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/call-bind/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/call-bind/.eslintrc b/node_modules/call-bind/.eslintrc new file mode 100644 index 0000000..e5d3c9a --- /dev/null +++ b/node_modules/call-bind/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + "no-magic-numbers": 0, + "operator-linebreak": [2, "before"], + }, +} diff --git a/node_modules/call-bind/.github/FUNDING.yml b/node_modules/call-bind/.github/FUNDING.yml new file mode 100644 index 0000000..c70c2ec --- /dev/null +++ b/node_modules/call-bind/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/call-bind +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/call-bind/.nycrc b/node_modules/call-bind/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/call-bind/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/call-bind/CHANGELOG.md b/node_modules/call-bind/CHANGELOG.md new file mode 100644 index 0000000..62a3727 --- /dev/null +++ b/node_modules/call-bind/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/call-bind/compare/v1.0.1...v1.0.2) - 2021-01-11 + +### Commits + +- [Fix] properly include the receiver in the bound length [`dbae7bc`](https://github.com/ljharb/call-bind/commit/dbae7bc676c079a0d33c0a43e9ef92cb7b01345d) + +## [v1.0.1](https://github.com/ljharb/call-bind/compare/v1.0.0...v1.0.1) - 2021-01-08 + +### Commits + +- [Tests] migrate tests to Github Actions [`b6db284`](https://github.com/ljharb/call-bind/commit/b6db284c36f8ccd195b88a6764fe84b7223a0da1) +- [meta] do not publish github action workflow files [`ec7fe46`](https://github.com/ljharb/call-bind/commit/ec7fe46e60cfa4764ee943d2755f5e5a366e578e) +- [Fix] preserve original function’s length when possible [`adbceaa`](https://github.com/ljharb/call-bind/commit/adbceaa3cac4b41ea78bb19d7ccdbaaf7e0bdadb) +- [Tests] gather coverage data on every job [`d69e23c`](https://github.com/ljharb/call-bind/commit/d69e23cc65f101ba1d4c19bb07fa8eb0ec624be8) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`2fd3586`](https://github.com/ljharb/call-bind/commit/2fd3586c5d47b335364c14293114c6b625ae1f71) +- [Deps] update `get-intrinsic` [`f23e931`](https://github.com/ljharb/call-bind/commit/f23e9318cc271c2add8bb38cfded85ee7baf8eee) +- [Deps] update `get-intrinsic` [`72d9f44`](https://github.com/ljharb/call-bind/commit/72d9f44e184465ba8dd3fb48260bbcff234985f2) +- [meta] fix FUNDING.yml [`e723573`](https://github.com/ljharb/call-bind/commit/e723573438c5a68dcec31fb5d96ea6b7e4a93be8) +- [eslint] ignore coverage output [`15e76d2`](https://github.com/ljharb/call-bind/commit/15e76d28a5f43e504696401e5b31ebb78ee1b532) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`8fa4dab`](https://github.com/ljharb/call-bind/commit/8fa4dabb23ba3dd7bb92c9571c1241c08b56e4b6) + +## v1.0.0 - 2020-10-30 + +### Commits + +- Initial commit [`306cf98`](https://github.com/ljharb/call-bind/commit/306cf98c7ec9e7ef66b653ec152277ac1381eb50) +- Tests [`e10d0bb`](https://github.com/ljharb/call-bind/commit/e10d0bbdadc7a10ecedc9a1c035112d3e368b8df) +- Implementation [`43852ed`](https://github.com/ljharb/call-bind/commit/43852eda0f187327b7fad2423ca972149a52bd65) +- npm init [`408f860`](https://github.com/ljharb/call-bind/commit/408f860b773a2f610805fd3613d0d71bac1b6249) +- [meta] add Automatic Rebase and Require Allow Edits workflows [`fb349b2`](https://github.com/ljharb/call-bind/commit/fb349b2e48defbec8b5ec8a8395cc8f69f220b13) +- [meta] add `auto-changelog` [`c4001fc`](https://github.com/ljharb/call-bind/commit/c4001fc43031799ef908211c98d3b0fb2b60fde4) +- [meta] add "funding"; create `FUNDING.yml` [`d4d6d29`](https://github.com/ljharb/call-bind/commit/d4d6d2974a14bc2e98830468eda7fe6d6a776717) +- [Tests] add `npm run lint` [`dedfb98`](https://github.com/ljharb/call-bind/commit/dedfb98bd0ecefb08ddb9a94061bd10cde4332af) +- Only apps should have lockfiles [`54ac776`](https://github.com/ljharb/call-bind/commit/54ac77653db45a7361dc153d2f478e743f110650) +- [meta] add `safe-publish-latest` [`9ea8e43`](https://github.com/ljharb/call-bind/commit/9ea8e435b950ce9b705559cd651039f9bf40140f) diff --git a/node_modules/call-bind/LICENSE b/node_modules/call-bind/LICENSE new file mode 100644 index 0000000..48f05d0 --- /dev/null +++ b/node_modules/call-bind/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Jordan Harband + +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/call-bind/README.md b/node_modules/call-bind/README.md new file mode 100644 index 0000000..53649eb --- /dev/null +++ b/node_modules/call-bind/README.md @@ -0,0 +1,2 @@ +# call-bind +Robustly `.call.bind()` a function. diff --git a/node_modules/call-bind/callBound.js b/node_modules/call-bind/callBound.js new file mode 100644 index 0000000..8374adf --- /dev/null +++ b/node_modules/call-bind/callBound.js @@ -0,0 +1,15 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; diff --git a/node_modules/call-bind/index.js b/node_modules/call-bind/index.js new file mode 100644 index 0000000..6fa3e4a --- /dev/null +++ b/node_modules/call-bind/index.js @@ -0,0 +1,47 @@ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); + +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); + +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} + +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} diff --git a/node_modules/call-bind/package.json b/node_modules/call-bind/package.json new file mode 100644 index 0000000..aa26c76 --- /dev/null +++ b/node_modules/call-bind/package.json @@ -0,0 +1,111 @@ +{ + "_args": [ + [ + "call-bind@1.0.2", + "/home/other/discord_bot" + ] + ], + "_from": "call-bind@1.0.2", + "_id": "call-bind@1.0.2", + "_inBundle": false, + "_integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "_location": "/call-bind", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "call-bind@1.0.2", + "name": "call-bind", + "escapedName": "call-bind", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/side-channel" + ], + "_resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "_spec": "1.0.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "bugs": { + "url": "https://github.com/ljharb/call-bind/issues" + }, + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "description": "Robustly `.call.bind()` a function", + "devDependencies": { + "@ljharb/eslint-config": "^17.3.0", + "aud": "^1.1.3", + "auto-changelog": "^2.2.1", + "eslint": "^7.17.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.1.1" + }, + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./callBound": [ + { + "default": "./callBound.js" + }, + "./callBound.js" + ], + "./package.json": "./package.json" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/ljharb/call-bind#readme", + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "callbind", + "callbound", + "call", + "bind", + "bound", + "call-bind", + "call-bound", + "function", + "es-abstract" + ], + "license": "MIT", + "main": "index.js", + "name": "call-bind", + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/call-bind.git" + }, + "scripts": { + "lint": "eslint --ext=.js,.mjs .", + "posttest": "aud --production", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublish": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/*'", + "version": "auto-changelog && git add CHANGELOG.md" + }, + "version": "1.0.2" +} diff --git a/node_modules/call-bind/test/callBound.js b/node_modules/call-bind/test/callBound.js new file mode 100644 index 0000000..209ce3c --- /dev/null +++ b/node_modules/call-bind/test/callBound.js @@ -0,0 +1,55 @@ +'use strict'; + +var test = require('tape'); + +var callBound = require('../callBound'); + +test('callBound', function (t) { + // static primitive + t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); + t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); + + // static non-function object + t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); + t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); + t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); + t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); + + // static function + t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); + t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); + + // prototype primitive + t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); + t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); + + // prototype function + t.notEqual(callBound('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString does not yield itself'); + t.notEqual(callBound('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); + t.equal(callBound('Object.prototype.toString')(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); + t.equal(callBound('%Object.prototype.toString%')(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); + + t['throws']( + function () { callBound('does not exist'); }, + SyntaxError, + 'nonexistent intrinsic throws' + ); + t['throws']( + function () { callBound('does not exist', true); }, + SyntaxError, + 'allowMissing arg still throws for unknown intrinsic' + ); + + /* globals WeakRef: false */ + t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { + st['throws']( + function () { callBound('WeakRef'); }, + TypeError, + 'real but absent intrinsic throws' + ); + st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/call-bind/test/index.js b/node_modules/call-bind/test/index.js new file mode 100644 index 0000000..bf6769c --- /dev/null +++ b/node_modules/call-bind/test/index.js @@ -0,0 +1,66 @@ +'use strict'; + +var callBind = require('../'); +var bind = require('function-bind'); + +var test = require('tape'); + +/* + * older engines have length nonconfigurable + * in io.js v3, it is configurable except on bound functions, hence the .bind() + */ +var functionsHaveConfigurableLengths = !!( + Object.getOwnPropertyDescriptor + && Object.getOwnPropertyDescriptor(bind.call(function () {}), 'length').configurable +); + +test('callBind', function (t) { + var sentinel = { sentinel: true }; + var func = function (a, b) { + // eslint-disable-next-line no-invalid-this + return [this, a, b]; + }; + t.equal(func.length, 2, 'original function length is 2'); + t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); + t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); + t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); + + var bound = callBind(func); + t.equal(bound.length, func.length + 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with too few args'); + t.deepEqual(bound(1, 2), [1, 2, undefined], 'bound func with right args'); + t.deepEqual(bound(1, 2, 3), [1, 2, 3], 'bound func with too many args'); + + var boundR = callBind(func, sentinel); + t.equal(boundR.length, func.length, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); + t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); + t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); + + var boundArg = callBind(func, sentinel, 1); + t.equal(boundArg.length, func.length - 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); + t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); + t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); + t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); + + t.test('callBind.apply', function (st) { + var aBound = callBind.apply(func); + st.deepEqual(aBound(sentinel), [sentinel, undefined, undefined], 'apply-bound func with no args'); + st.deepEqual(aBound(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + st.deepEqual(aBound(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + + var aBoundArg = callBind.apply(func); + st.deepEqual(aBoundArg(sentinel, [1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with too many args'); + st.deepEqual(aBoundArg(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); + st.deepEqual(aBoundArg(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); + + var aBoundR = callBind.apply(func, sentinel); + st.deepEqual(aBoundR([1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with receiver and too many args'); + st.deepEqual(aBoundR([1, 2], 4), [sentinel, 1, 2], 'apply-bound func with receiver and right args'); + st.deepEqual(aBoundR([1], 4), [sentinel, 1, undefined], 'apply-bound func with receiver and too few args'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/camelcase/index.d.ts b/node_modules/camelcase/index.d.ts new file mode 100644 index 0000000..169b634 --- /dev/null +++ b/node_modules/camelcase/index.d.ts @@ -0,0 +1,101 @@ +declare namespace camelcase { + interface Options { + /** + Uppercase the first character: `foo-bar` → `FooBar`. + + @default false + */ + readonly pascalCase?: boolean; + + /** + Preserve the consecutive uppercase characters: `foo-BAR` → `FooBAR`. + + @default false + */ + readonly preserveConsecutiveUppercase?: boolean; + + /** + The locale parameter indicates the locale to be used to convert to upper/lower case according to any locale-specific case mappings. If multiple locales are given in an array, the best available locale is used. + + Default: The host environment’s current locale. + + @example + ``` + import camelCase = require('camelcase'); + + camelCase('lorem-ipsum', {locale: 'en-US'}); + //=> 'loremIpsum' + camelCase('lorem-ipsum', {locale: 'tr-TR'}); + //=> 'loremİpsum' + camelCase('lorem-ipsum', {locale: ['en-US', 'en-GB']}); + //=> 'loremIpsum' + camelCase('lorem-ipsum', {locale: ['tr', 'TR', 'tr-TR']}); + //=> 'loremİpsum' + ``` + */ + readonly locale?: string | readonly string[]; + } +} + +/** +Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`. + +Correctly handles Unicode strings. + +@param input - String to convert to camel case. + +@example +``` +import camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('розовый_пушистый_единороги'); +//=> 'розовыйПушистыйЕдинороги' + +camelCase('Foo-Bar', {pascalCase: true}); +//=> 'FooBar' + +camelCase('--foo.bar', {pascalCase: false}); +//=> 'fooBar' + +camelCase('Foo-BAR', {preserveConsecutiveUppercase: true}); +//=> 'fooBAR' + +camelCase('fooBAR', {pascalCase: true, preserveConsecutiveUppercase: true})); +//=> 'FooBAR' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase(['foo', 'bar']); +//=> 'fooBar' + +camelCase(['__foo__', '--bar'], {pascalCase: true}); +//=> 'FooBar' + +camelCase(['foo', 'BAR'], {pascalCase: true, preserveConsecutiveUppercase: true}) +//=> 'FooBAR' + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' +``` +*/ +declare function camelcase( + input: string | readonly string[], + options?: camelcase.Options +): string; + +export = camelcase; diff --git a/node_modules/camelcase/index.js b/node_modules/camelcase/index.js new file mode 100644 index 0000000..cdb5511 --- /dev/null +++ b/node_modules/camelcase/index.js @@ -0,0 +1,91 @@ +'use strict'; + +const preserveCamelCase = (string, locale) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && /[\p{Lu}]/u.test(character)) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character; + } + } + + return string; +}; + +const preserveConsecutiveUppercase = input => { + return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, m1 => m1.toLowerCase()); +}; + +const postProcess = (input, options) => { + return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale)) + .replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase(options.locale)); +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options + }; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + if (input.length === 1) { + return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale); + } + + const hasUpperCase = input !== input.toLocaleLowerCase(options.locale); + + if (hasUpperCase) { + input = preserveCamelCase(input, options.locale); + } + + input = input.replace(/^[_.\- ]+/, ''); + + if (options.preserveConsecutiveUppercase) { + input = preserveConsecutiveUppercase(input); + } else { + input = input.toLocaleLowerCase(); + } + + if (options.pascalCase) { + input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1); + } + + return postProcess(input, options); +}; + +module.exports = camelCase; +// TODO: Remove this for the next major release +module.exports.default = camelCase; diff --git a/node_modules/camelcase/license b/node_modules/camelcase/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/camelcase/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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/camelcase/package.json b/node_modules/camelcase/package.json new file mode 100644 index 0000000..dc6ee56 --- /dev/null +++ b/node_modules/camelcase/package.json @@ -0,0 +1,79 @@ +{ + "_args": [ + [ + "camelcase@6.2.0", + "/home/other/discord_bot" + ] + ], + "_from": "camelcase@6.2.0", + "_id": "camelcase@6.2.0", + "_inBundle": false, + "_integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==", + "_location": "/camelcase", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "camelcase@6.2.0", + "name": "camelcase", + "escapedName": "camelcase", + "rawSpec": "6.2.0", + "saveSpec": null, + "fetchSpec": "6.2.0" + }, + "_requiredBy": [ + "/boxen" + ], + "_resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz", + "_spec": "6.2.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/camelcase/issues" + }, + "description": "Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.11.0", + "xo": "^0.28.3" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/camelcase#readme", + "keywords": [ + "camelcase", + "camel-case", + "camel", + "case", + "dash", + "hyphen", + "dot", + "underscore", + "separator", + "string", + "text", + "convert", + "pascalcase", + "pascal-case" + ], + "license": "MIT", + "name": "camelcase", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/camelcase.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "6.2.0" +} diff --git a/node_modules/camelcase/readme.md b/node_modules/camelcase/readme.md new file mode 100644 index 0000000..dbfc0de --- /dev/null +++ b/node_modules/camelcase/readme.md @@ -0,0 +1,128 @@ +# camelcase [![Build Status](https://travis-ci.com/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.com/sindresorhus/camelcase) + +> Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar` + +Correctly handles Unicode strings. + +## Install + +``` +$ npm install camelcase +``` + +*If you need to support Firefox, stay on version 5 as version 6 uses regex features not available in Firefox.* + +## Usage + +```js +const camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('розовый_пушистый_единороги'); +//=> 'розовыйПушистыйЕдинороги' + +camelCase('Foo-Bar', {pascalCase: true}); +//=> 'FooBar' + +camelCase('--foo.bar', {pascalCase: false}); +//=> 'fooBar' + +camelCase('Foo-BAR', {preserveConsecutiveUppercase: true}); +//=> 'fooBAR' + +camelCase('fooBAR', {pascalCase: true, preserveConsecutiveUppercase: true})); +//=> 'FooBAR' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase(['foo', 'bar']); +//=> 'fooBar' + +camelCase(['__foo__', '--bar'], {pascalCase: true}); +//=> 'FooBar' + +camelCase(['foo', 'BAR'], {pascalCase: true, preserveConsecutiveUppercase: true}) +//=> 'FooBAR' + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' +``` + +## API + +### camelCase(input, options?) + +#### input + +Type: `string | string[]` + +String to convert to camel case. + +#### options + +Type: `object` + +##### pascalCase + +Type: `boolean`\ +Default: `false` + +Uppercase the first character: `foo-bar` → `FooBar` + +##### preserveConsecutiveUppercase + +Type: `boolean`\ +Default: `false` + +Preserve the consecutive uppercase characters: `foo-BAR` → `FooBAR`. + +##### locale + +Type: `string | string[]`\ +Default: The host environment’s current locale. + +The locale parameter indicates the locale to be used to convert to upper/lower case according to any locale-specific case mappings. If multiple locales are given in an array, the best available locale is used. + +```js +const camelCase = require('camelcase'); + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' + +camelCase('lorem-ipsum', {locale: 'tr-TR'}); +//=> 'loremİpsum' + +camelCase('lorem-ipsum', {locale: ['en-US', 'en-GB']}); +//=> 'loremIpsum' + +camelCase('lorem-ipsum', {locale: ['tr', 'TR', 'tr-TR']}); +//=> 'loremİpsum' +``` + +## camelcase for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of camelcase and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-camelcase?utm_source=npm-camelcase&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Related + +- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module +- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase +- [titleize](https://github.com/sindresorhus/titleize) - Capitalize every word in string +- [humanize-string](https://github.com/sindresorhus/humanize-string) - Convert a camelized/dasherized/underscored string into a humanized one +- [camelcase-keys](https://github.com/sindresorhus/camelcase-keys) - Convert object keys to camel case diff --git a/node_modules/chalk/index.d.ts b/node_modules/chalk/index.d.ts new file mode 100644 index 0000000..9cd88f3 --- /dev/null +++ b/node_modules/chalk/index.d.ts @@ -0,0 +1,415 @@ +/** +Basic foreground colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type ForegroundColor = + | 'black' + | 'red' + | 'green' + | 'yellow' + | 'blue' + | 'magenta' + | 'cyan' + | 'white' + | 'gray' + | 'grey' + | 'blackBright' + | 'redBright' + | 'greenBright' + | 'yellowBright' + | 'blueBright' + | 'magentaBright' + | 'cyanBright' + | 'whiteBright'; + +/** +Basic background colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type BackgroundColor = + | 'bgBlack' + | 'bgRed' + | 'bgGreen' + | 'bgYellow' + | 'bgBlue' + | 'bgMagenta' + | 'bgCyan' + | 'bgWhite' + | 'bgGray' + | 'bgGrey' + | 'bgBlackBright' + | 'bgRedBright' + | 'bgGreenBright' + | 'bgYellowBright' + | 'bgBlueBright' + | 'bgMagentaBright' + | 'bgCyanBright' + | 'bgWhiteBright'; + +/** +Basic colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type Color = ForegroundColor | BackgroundColor; + +declare type Modifiers = + | 'reset' + | 'bold' + | 'dim' + | 'italic' + | 'underline' + | 'inverse' + | 'hidden' + | 'strikethrough' + | 'visible'; + +declare namespace chalk { + /** + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + type Level = 0 | 1 | 2 | 3; + + interface Options { + /** + Specify the color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level?: Level; + } + + /** + Return a new Chalk instance. + */ + type Instance = new (options?: Options) => Chalk; + + /** + Detect whether the terminal supports color. + */ + interface ColorSupport { + /** + The color level used by Chalk. + */ + level: Level; + + /** + Return whether Chalk supports basic 16 colors. + */ + hasBasic: boolean; + + /** + Return whether Chalk supports ANSI 256 colors. + */ + has256: boolean; + + /** + Return whether Chalk supports Truecolor 16 million colors. + */ + has16m: boolean; + } + + interface ChalkFunction { + /** + Use a template string. + + @remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341)) + + @example + ``` + import chalk = require('chalk'); + + log(chalk` + CPU: {red ${cpu.totalPercent}%} + RAM: {green ${ram.used / ram.total * 100}%} + DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} + `); + ``` + + @example + ``` + import chalk = require('chalk'); + + log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`) + ``` + */ + (text: TemplateStringsArray, ...placeholders: unknown[]): string; + + (...text: unknown[]): string; + } + + interface Chalk extends ChalkFunction { + /** + Return a new Chalk instance. + */ + Instance: Instance; + + /** + The color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level: Level; + + /** + Use HEX value to set text color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.hex('#DEADED'); + ``` + */ + hex(color: string): Chalk; + + /** + Use keyword color value to set text color. + + @param color - Keyword value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.keyword('orange'); + ``` + */ + keyword(color: string): Chalk; + + /** + Use RGB values to set text color. + */ + rgb(red: number, green: number, blue: number): Chalk; + + /** + Use HSL values to set text color. + */ + hsl(hue: number, saturation: number, lightness: number): Chalk; + + /** + Use HSV values to set text color. + */ + hsv(hue: number, saturation: number, value: number): Chalk; + + /** + Use HWB values to set text color. + */ + hwb(hue: number, whiteness: number, blackness: number): Chalk; + + /** + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color. + + 30 <= code && code < 38 || 90 <= code && code < 98 + For example, 31 for red, 91 for redBright. + */ + ansi(code: number): Chalk; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + */ + ansi256(index: number): Chalk; + + /** + Use HEX value to set background color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.bgHex('#DEADED'); + ``` + */ + bgHex(color: string): Chalk; + + /** + Use keyword color value to set background color. + + @param color - Keyword value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.bgKeyword('orange'); + ``` + */ + bgKeyword(color: string): Chalk; + + /** + Use RGB values to set background color. + */ + bgRgb(red: number, green: number, blue: number): Chalk; + + /** + Use HSL values to set background color. + */ + bgHsl(hue: number, saturation: number, lightness: number): Chalk; + + /** + Use HSV values to set background color. + */ + bgHsv(hue: number, saturation: number, value: number): Chalk; + + /** + Use HWB values to set background color. + */ + bgHwb(hue: number, whiteness: number, blackness: number): Chalk; + + /** + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color. + + 30 <= code && code < 38 || 90 <= code && code < 98 + For example, 31 for red, 91 for redBright. + Use the foreground code, not the background code (for example, not 41, nor 101). + */ + bgAnsi(code: number): Chalk; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. + */ + bgAnsi256(index: number): Chalk; + + /** + Modifier: Resets the current color chain. + */ + readonly reset: Chalk; + + /** + Modifier: Make text bold. + */ + readonly bold: Chalk; + + /** + Modifier: Emitting only a small amount of light. + */ + readonly dim: Chalk; + + /** + Modifier: Make text italic. (Not widely supported) + */ + readonly italic: Chalk; + + /** + Modifier: Make text underline. (Not widely supported) + */ + readonly underline: Chalk; + + /** + Modifier: Inverse background and foreground colors. + */ + readonly inverse: Chalk; + + /** + Modifier: Prints the text, but makes it invisible. + */ + readonly hidden: Chalk; + + /** + Modifier: Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: Chalk; + + /** + Modifier: Prints the text only when Chalk has a color support level > 0. + Can be useful for things that are purely cosmetic. + */ + readonly visible: Chalk; + + readonly black: Chalk; + readonly red: Chalk; + readonly green: Chalk; + readonly yellow: Chalk; + readonly blue: Chalk; + readonly magenta: Chalk; + readonly cyan: Chalk; + readonly white: Chalk; + + /* + Alias for `blackBright`. + */ + readonly gray: Chalk; + + /* + Alias for `blackBright`. + */ + readonly grey: Chalk; + + readonly blackBright: Chalk; + readonly redBright: Chalk; + readonly greenBright: Chalk; + readonly yellowBright: Chalk; + readonly blueBright: Chalk; + readonly magentaBright: Chalk; + readonly cyanBright: Chalk; + readonly whiteBright: Chalk; + + readonly bgBlack: Chalk; + readonly bgRed: Chalk; + readonly bgGreen: Chalk; + readonly bgYellow: Chalk; + readonly bgBlue: Chalk; + readonly bgMagenta: Chalk; + readonly bgCyan: Chalk; + readonly bgWhite: Chalk; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGray: Chalk; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGrey: Chalk; + + readonly bgBlackBright: Chalk; + readonly bgRedBright: Chalk; + readonly bgGreenBright: Chalk; + readonly bgYellowBright: Chalk; + readonly bgBlueBright: Chalk; + readonly bgMagentaBright: Chalk; + readonly bgCyanBright: Chalk; + readonly bgWhiteBright: Chalk; + } +} + +/** +Main Chalk object that allows to chain styles together. +Call the last one as a method with a string argument. +Order doesn't matter, and later styles take precedent in case of a conflict. +This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. +*/ +declare const chalk: chalk.Chalk & chalk.ChalkFunction & { + supportsColor: chalk.ColorSupport | false; + Level: chalk.Level; + Color: Color; + ForegroundColor: ForegroundColor; + BackgroundColor: BackgroundColor; + Modifiers: Modifiers; + stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false}; +}; + +export = chalk; diff --git a/node_modules/chalk/license b/node_modules/chalk/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/chalk/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/chalk/node_modules/has-flag/index.d.ts b/node_modules/chalk/node_modules/has-flag/index.d.ts new file mode 100644 index 0000000..a0a48c8 --- /dev/null +++ b/node_modules/chalk/node_modules/has-flag/index.d.ts @@ -0,0 +1,39 @@ +/** +Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag. + +@param flag - CLI flag to look for. The `--` prefix is optional. +@param argv - CLI arguments. Default: `process.argv`. +@returns Whether the flag exists. + +@example +``` +// $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow + +// foo.ts +import hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` +*/ +declare function hasFlag(flag: string, argv?: string[]): boolean; + +export = hasFlag; diff --git a/node_modules/chalk/node_modules/has-flag/index.js b/node_modules/chalk/node_modules/has-flag/index.js new file mode 100644 index 0000000..b6f80b1 --- /dev/null +++ b/node_modules/chalk/node_modules/has-flag/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; diff --git a/node_modules/chalk/node_modules/has-flag/license b/node_modules/chalk/node_modules/has-flag/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/chalk/node_modules/has-flag/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/chalk/node_modules/has-flag/package.json b/node_modules/chalk/node_modules/has-flag/package.json new file mode 100644 index 0000000..140e4d7 --- /dev/null +++ b/node_modules/chalk/node_modules/has-flag/package.json @@ -0,0 +1,81 @@ +{ + "_args": [ + [ + "has-flag@4.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "has-flag@4.0.0", + "_id": "has-flag@4.0.0", + "_inBundle": false, + "_integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "_location": "/chalk/has-flag", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "has-flag@4.0.0", + "name": "has-flag", + "escapedName": "has-flag", + "rawSpec": "4.0.0", + "saveSpec": null, + "fetchSpec": "4.0.0" + }, + "_requiredBy": [ + "/chalk/supports-color" + ], + "_resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "_spec": "4.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/has-flag/issues" + }, + "description": "Check if argv has a specific flag", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/has-flag#readme", + "keywords": [ + "has", + "check", + "detect", + "contains", + "find", + "flag", + "cli", + "command-line", + "argv", + "process", + "arg", + "args", + "argument", + "arguments", + "getopt", + "minimist", + "optimist" + ], + "license": "MIT", + "name": "has-flag", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/has-flag.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "4.0.0" +} diff --git a/node_modules/chalk/node_modules/has-flag/readme.md b/node_modules/chalk/node_modules/has-flag/readme.md new file mode 100644 index 0000000..3f72dff --- /dev/null +++ b/node_modules/chalk/node_modules/has-flag/readme.md @@ -0,0 +1,89 @@ +# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag) + +> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag + +Correctly stops looking after an `--` argument terminator. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + + +## Install + +``` +$ npm install has-flag +``` + + +## Usage + +```js +// foo.js +const hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` + +``` +$ node foo.js -f --unicorn --foo=bar -- --rainbow +``` + + +## API + +### hasFlag(flag, [argv]) + +Returns a boolean for whether the flag exists. + +#### flag + +Type: `string` + +CLI flag to look for. The `--` prefix is optional. + +#### argv + +Type: `string[]`
+Default: `process.argv` + +CLI arguments. + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/chalk/node_modules/supports-color/browser.js b/node_modules/chalk/node_modules/supports-color/browser.js new file mode 100644 index 0000000..62afa3a --- /dev/null +++ b/node_modules/chalk/node_modules/supports-color/browser.js @@ -0,0 +1,5 @@ +'use strict'; +module.exports = { + stdout: false, + stderr: false +}; diff --git a/node_modules/chalk/node_modules/supports-color/index.js b/node_modules/chalk/node_modules/supports-color/index.js new file mode 100644 index 0000000..6fada39 --- /dev/null +++ b/node_modules/chalk/node_modules/supports-color/index.js @@ -0,0 +1,135 @@ +'use strict'; +const os = require('os'); +const tty = require('tty'); +const hasFlag = require('has-flag'); + +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; +} + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; diff --git a/node_modules/chalk/node_modules/supports-color/license b/node_modules/chalk/node_modules/supports-color/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/chalk/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/chalk/node_modules/supports-color/package.json b/node_modules/chalk/node_modules/supports-color/package.json new file mode 100644 index 0000000..cfb0935 --- /dev/null +++ b/node_modules/chalk/node_modules/supports-color/package.json @@ -0,0 +1,88 @@ +{ + "_args": [ + [ + "supports-color@7.2.0", + "/home/other/discord_bot" + ] + ], + "_from": "supports-color@7.2.0", + "_id": "supports-color@7.2.0", + "_inBundle": false, + "_integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "_location": "/chalk/supports-color", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "supports-color@7.2.0", + "name": "supports-color", + "escapedName": "supports-color", + "rawSpec": "7.2.0", + "saveSpec": null, + "fetchSpec": "7.2.0" + }, + "_requiredBy": [ + "/chalk" + ], + "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "_spec": "7.2.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/chalk/supports-color/issues" + }, + "dependencies": { + "has-flag": "^4.0.0" + }, + "description": "Detect whether a terminal supports color", + "devDependencies": { + "ava": "^1.4.1", + "import-fresh": "^3.0.0", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "browser.js" + ], + "homepage": "https://github.com/chalk/supports-color#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "license": "MIT", + "name": "supports-color", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/supports-color.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "7.2.0" +} diff --git a/node_modules/chalk/node_modules/supports-color/readme.md b/node_modules/chalk/node_modules/supports-color/readme.md new file mode 100644 index 0000000..3654228 --- /dev/null +++ b/node_modules/chalk/node_modules/supports-color/readme.md @@ -0,0 +1,76 @@ +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install supports-color +``` + + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- diff --git a/node_modules/chalk/package.json b/node_modules/chalk/package.json new file mode 100644 index 0000000..41214e4 --- /dev/null +++ b/node_modules/chalk/package.json @@ -0,0 +1,104 @@ +{ + "_args": [ + [ + "chalk@4.1.2", + "/home/other/discord_bot" + ] + ], + "_from": "chalk@4.1.2", + "_id": "chalk@4.1.2", + "_inBundle": false, + "_integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "_location": "/chalk", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "chalk@4.1.2", + "name": "chalk", + "escapedName": "chalk", + "rawSpec": "4.1.2", + "saveSpec": null, + "fetchSpec": "4.1.2" + }, + "_requiredBy": [ + "/boxen", + "/update-notifier" + ], + "_resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "_spec": "4.1.2", + "_where": "/home/other/discord_bot", + "bugs": { + "url": "https://github.com/chalk/chalk/issues" + }, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "description": "Terminal string styling done right", + "devDependencies": { + "ava": "^2.4.0", + "coveralls": "^3.0.7", + "execa": "^4.0.0", + "import-fresh": "^3.1.0", + "matcha": "^0.7.0", + "nyc": "^15.0.0", + "resolve-from": "^5.0.0", + "tsd": "^0.7.4", + "xo": "^0.28.2" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "source", + "index.d.ts" + ], + "funding": "https://github.com/chalk/chalk?sponsor=1", + "homepage": "https://github.com/chalk/chalk#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "str", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "main": "source", + "name": "chalk", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/chalk.git" + }, + "scripts": { + "bench": "matcha benchmark.js", + "test": "xo && nyc ava && tsd" + }, + "version": "4.1.2", + "xo": { + "rules": { + "unicorn/prefer-string-slice": "off", + "unicorn/prefer-includes": "off", + "@typescript-eslint/member-ordering": "off", + "no-redeclare": "off", + "unicorn/string-content": "off", + "unicorn/better-regex": "off" + } + } +} diff --git a/node_modules/chalk/readme.md b/node_modules/chalk/readme.md new file mode 100644 index 0000000..a055d21 --- /dev/null +++ b/node_modules/chalk/readme.md @@ -0,0 +1,341 @@ +

+
+
+ Chalk +
+
+
+

+ +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk) + + + +
+ +--- + + + +--- + +
+ +## Highlights + +- Expressive API +- Highly performant +- Ability to nest styles +- [256/Truecolor color support](#256-and-truecolor-color-support) +- Auto-detects color support +- Doesn't extend `String.prototype` +- Clean and focused +- Actively maintained +- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020 + +## Install + +```console +$ npm install chalk +``` + +## Usage + +```js +const chalk = require('chalk'); + +console.log(chalk.blue('Hello world!')); +``` + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +const chalk = require('chalk'); +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// ES2015 tagged template literal +log(chalk` +CPU: {red ${cpu.totalPercent}%} +RAM: {green ${ram.used / ram.total * 100}%} +DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.keyword('orange')('Yay for orange colored text!')); +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); +``` + +Easily define your own themes: + +```js +const chalk = require('chalk'); + +const error = chalk.bold.red; +const warning = chalk.keyword('orange'); + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` + +## API + +### chalk.` +Browserstack-logo-white + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/node_modules/psl/data/rules.json b/node_modules/psl/data/rules.json new file mode 100644 index 0000000..e19abdc --- /dev/null +++ b/node_modules/psl/data/rules.json @@ -0,0 +1,8834 @@ +[ +"ac", +"com.ac", +"edu.ac", +"gov.ac", +"net.ac", +"mil.ac", +"org.ac", +"ad", +"nom.ad", +"ae", +"co.ae", +"net.ae", +"org.ae", +"sch.ae", +"ac.ae", +"gov.ae", +"mil.ae", +"aero", +"accident-investigation.aero", +"accident-prevention.aero", +"aerobatic.aero", +"aeroclub.aero", +"aerodrome.aero", +"agents.aero", +"aircraft.aero", +"airline.aero", +"airport.aero", +"air-surveillance.aero", +"airtraffic.aero", +"air-traffic-control.aero", +"ambulance.aero", +"amusement.aero", +"association.aero", +"author.aero", +"ballooning.aero", +"broker.aero", +"caa.aero", +"cargo.aero", +"catering.aero", +"certification.aero", +"championship.aero", +"charter.aero", +"civilaviation.aero", +"club.aero", +"conference.aero", +"consultant.aero", +"consulting.aero", +"control.aero", +"council.aero", +"crew.aero", +"design.aero", +"dgca.aero", +"educator.aero", +"emergency.aero", +"engine.aero", +"engineer.aero", +"entertainment.aero", +"equipment.aero", +"exchange.aero", +"express.aero", +"federation.aero", +"flight.aero", +"freight.aero", +"fuel.aero", +"gliding.aero", +"government.aero", +"groundhandling.aero", +"group.aero", +"hanggliding.aero", +"homebuilt.aero", +"insurance.aero", +"journal.aero", +"journalist.aero", +"leasing.aero", +"logistics.aero", +"magazine.aero", +"maintenance.aero", +"media.aero", +"microlight.aero", +"modelling.aero", +"navigation.aero", +"parachuting.aero", +"paragliding.aero", +"passenger-association.aero", +"pilot.aero", +"press.aero", +"production.aero", +"recreation.aero", +"repbody.aero", +"res.aero", +"research.aero", +"rotorcraft.aero", +"safety.aero", +"scientist.aero", +"services.aero", +"show.aero", +"skydiving.aero", +"software.aero", +"student.aero", +"trader.aero", +"trading.aero", +"trainer.aero", +"union.aero", +"workinggroup.aero", +"works.aero", +"af", +"gov.af", +"com.af", +"org.af", +"net.af", +"edu.af", +"ag", +"com.ag", +"org.ag", +"net.ag", +"co.ag", +"nom.ag", +"ai", +"off.ai", +"com.ai", +"net.ai", +"org.ai", +"al", +"com.al", +"edu.al", +"gov.al", +"mil.al", +"net.al", +"org.al", +"am", +"co.am", +"com.am", +"commune.am", +"net.am", +"org.am", +"ao", +"ed.ao", +"gv.ao", +"og.ao", +"co.ao", +"pb.ao", +"it.ao", +"aq", +"ar", +"com.ar", +"edu.ar", +"gob.ar", +"gov.ar", +"int.ar", +"mil.ar", +"musica.ar", +"net.ar", +"org.ar", +"tur.ar", +"arpa", +"e164.arpa", +"in-addr.arpa", +"ip6.arpa", +"iris.arpa", +"uri.arpa", +"urn.arpa", +"as", +"gov.as", +"asia", +"at", +"ac.at", +"co.at", +"gv.at", +"or.at", +"au", +"com.au", +"net.au", +"org.au", +"edu.au", +"gov.au", +"asn.au", +"id.au", +"info.au", +"conf.au", +"oz.au", +"act.au", +"nsw.au", +"nt.au", +"qld.au", +"sa.au", +"tas.au", +"vic.au", +"wa.au", +"act.edu.au", +"catholic.edu.au", +"nsw.edu.au", +"nt.edu.au", +"qld.edu.au", +"sa.edu.au", +"tas.edu.au", +"vic.edu.au", +"wa.edu.au", +"qld.gov.au", +"sa.gov.au", +"tas.gov.au", +"vic.gov.au", +"wa.gov.au", +"education.tas.edu.au", +"schools.nsw.edu.au", +"aw", +"com.aw", +"ax", +"az", +"com.az", +"net.az", +"int.az", +"gov.az", +"org.az", +"edu.az", +"info.az", +"pp.az", +"mil.az", +"name.az", +"pro.az", +"biz.az", +"ba", +"com.ba", +"edu.ba", +"gov.ba", +"mil.ba", +"net.ba", +"org.ba", +"bb", +"biz.bb", +"co.bb", +"com.bb", +"edu.bb", +"gov.bb", +"info.bb", +"net.bb", +"org.bb", +"store.bb", +"tv.bb", +"*.bd", +"be", +"ac.be", +"bf", +"gov.bf", +"bg", +"a.bg", +"b.bg", +"c.bg", +"d.bg", +"e.bg", +"f.bg", +"g.bg", +"h.bg", +"i.bg", +"j.bg", +"k.bg", +"l.bg", +"m.bg", +"n.bg", +"o.bg", +"p.bg", +"q.bg", +"r.bg", +"s.bg", +"t.bg", +"u.bg", +"v.bg", +"w.bg", +"x.bg", +"y.bg", +"z.bg", +"0.bg", +"1.bg", +"2.bg", +"3.bg", +"4.bg", +"5.bg", +"6.bg", +"7.bg", +"8.bg", +"9.bg", +"bh", +"com.bh", +"edu.bh", +"net.bh", +"org.bh", +"gov.bh", +"bi", +"co.bi", +"com.bi", +"edu.bi", +"or.bi", +"org.bi", +"biz", +"bj", +"asso.bj", +"barreau.bj", +"gouv.bj", +"bm", +"com.bm", +"edu.bm", +"gov.bm", +"net.bm", +"org.bm", +"bn", +"com.bn", +"edu.bn", +"gov.bn", +"net.bn", +"org.bn", +"bo", +"com.bo", +"edu.bo", +"gob.bo", +"int.bo", +"org.bo", +"net.bo", +"mil.bo", +"tv.bo", +"web.bo", +"academia.bo", +"agro.bo", +"arte.bo", +"blog.bo", +"bolivia.bo", +"ciencia.bo", +"cooperativa.bo", +"democracia.bo", +"deporte.bo", +"ecologia.bo", +"economia.bo", +"empresa.bo", +"indigena.bo", +"industria.bo", +"info.bo", +"medicina.bo", +"movimiento.bo", +"musica.bo", +"natural.bo", +"nombre.bo", +"noticias.bo", +"patria.bo", +"politica.bo", +"profesional.bo", +"plurinacional.bo", +"pueblo.bo", +"revista.bo", +"salud.bo", +"tecnologia.bo", +"tksat.bo", +"transporte.bo", +"wiki.bo", +"br", +"9guacu.br", +"abc.br", +"adm.br", +"adv.br", +"agr.br", +"aju.br", +"am.br", +"anani.br", +"aparecida.br", +"arq.br", +"art.br", +"ato.br", +"b.br", +"barueri.br", +"belem.br", +"bhz.br", +"bio.br", +"blog.br", +"bmd.br", +"boavista.br", +"bsb.br", +"campinagrande.br", +"campinas.br", +"caxias.br", +"cim.br", +"cng.br", +"cnt.br", +"com.br", +"contagem.br", +"coop.br", +"cri.br", +"cuiaba.br", +"curitiba.br", +"def.br", +"ecn.br", +"eco.br", +"edu.br", +"emp.br", +"eng.br", +"esp.br", +"etc.br", +"eti.br", +"far.br", +"feira.br", +"flog.br", +"floripa.br", +"fm.br", +"fnd.br", +"fortal.br", +"fot.br", +"foz.br", +"fst.br", +"g12.br", +"ggf.br", +"goiania.br", +"gov.br", +"ac.gov.br", +"al.gov.br", +"am.gov.br", +"ap.gov.br", +"ba.gov.br", +"ce.gov.br", +"df.gov.br", +"es.gov.br", +"go.gov.br", +"ma.gov.br", +"mg.gov.br", +"ms.gov.br", +"mt.gov.br", +"pa.gov.br", +"pb.gov.br", +"pe.gov.br", +"pi.gov.br", +"pr.gov.br", +"rj.gov.br", +"rn.gov.br", +"ro.gov.br", +"rr.gov.br", +"rs.gov.br", +"sc.gov.br", +"se.gov.br", +"sp.gov.br", +"to.gov.br", +"gru.br", +"imb.br", +"ind.br", +"inf.br", +"jab.br", +"jampa.br", +"jdf.br", +"joinville.br", +"jor.br", +"jus.br", +"leg.br", +"lel.br", +"londrina.br", +"macapa.br", +"maceio.br", +"manaus.br", +"maringa.br", +"mat.br", +"med.br", +"mil.br", +"morena.br", +"mp.br", +"mus.br", +"natal.br", +"net.br", +"niteroi.br", +"*.nom.br", +"not.br", +"ntr.br", +"odo.br", +"ong.br", +"org.br", +"osasco.br", +"palmas.br", +"poa.br", +"ppg.br", +"pro.br", +"psc.br", +"psi.br", +"pvh.br", +"qsl.br", +"radio.br", +"rec.br", +"recife.br", +"ribeirao.br", +"rio.br", +"riobranco.br", +"riopreto.br", +"salvador.br", +"sampa.br", +"santamaria.br", +"santoandre.br", +"saobernardo.br", +"saogonca.br", +"sjc.br", +"slg.br", +"slz.br", +"sorocaba.br", +"srv.br", +"taxi.br", +"tc.br", +"teo.br", +"the.br", +"tmp.br", +"trd.br", +"tur.br", +"tv.br", +"udi.br", +"vet.br", +"vix.br", +"vlog.br", +"wiki.br", +"zlg.br", +"bs", +"com.bs", +"net.bs", +"org.bs", +"edu.bs", +"gov.bs", +"bt", +"com.bt", +"edu.bt", +"gov.bt", +"net.bt", +"org.bt", +"bv", +"bw", +"co.bw", +"org.bw", +"by", +"gov.by", +"mil.by", +"com.by", +"of.by", +"bz", +"com.bz", +"net.bz", +"org.bz", +"edu.bz", +"gov.bz", +"ca", +"ab.ca", +"bc.ca", +"mb.ca", +"nb.ca", +"nf.ca", +"nl.ca", +"ns.ca", +"nt.ca", +"nu.ca", +"on.ca", +"pe.ca", +"qc.ca", +"sk.ca", +"yk.ca", +"gc.ca", +"cat", +"cc", +"cd", +"gov.cd", +"cf", +"cg", +"ch", +"ci", +"org.ci", +"or.ci", +"com.ci", +"co.ci", +"edu.ci", +"ed.ci", +"ac.ci", +"net.ci", +"go.ci", +"asso.ci", +"aéroport.ci", +"int.ci", +"presse.ci", +"md.ci", +"gouv.ci", +"*.ck", +"!www.ck", +"cl", +"aprendemas.cl", +"co.cl", +"gob.cl", +"gov.cl", +"mil.cl", +"cm", +"co.cm", +"com.cm", +"gov.cm", +"net.cm", +"cn", +"ac.cn", +"com.cn", +"edu.cn", +"gov.cn", +"net.cn", +"org.cn", +"mil.cn", +"公司.cn", +"网络.cn", +"網絡.cn", +"ah.cn", +"bj.cn", +"cq.cn", +"fj.cn", +"gd.cn", +"gs.cn", +"gz.cn", +"gx.cn", +"ha.cn", +"hb.cn", +"he.cn", +"hi.cn", +"hl.cn", +"hn.cn", +"jl.cn", +"js.cn", +"jx.cn", +"ln.cn", +"nm.cn", +"nx.cn", +"qh.cn", +"sc.cn", +"sd.cn", +"sh.cn", +"sn.cn", +"sx.cn", +"tj.cn", +"xj.cn", +"xz.cn", +"yn.cn", +"zj.cn", +"hk.cn", +"mo.cn", +"tw.cn", +"co", +"arts.co", +"com.co", +"edu.co", +"firm.co", +"gov.co", +"info.co", +"int.co", +"mil.co", +"net.co", +"nom.co", +"org.co", +"rec.co", +"web.co", +"com", +"coop", +"cr", +"ac.cr", +"co.cr", +"ed.cr", +"fi.cr", +"go.cr", +"or.cr", +"sa.cr", +"cu", +"com.cu", +"edu.cu", +"org.cu", +"net.cu", +"gov.cu", +"inf.cu", +"cv", +"cw", +"com.cw", +"edu.cw", +"net.cw", +"org.cw", +"cx", +"gov.cx", +"cy", +"ac.cy", +"biz.cy", +"com.cy", +"ekloges.cy", +"gov.cy", +"ltd.cy", +"name.cy", +"net.cy", +"org.cy", +"parliament.cy", +"press.cy", +"pro.cy", +"tm.cy", +"cz", +"de", +"dj", +"dk", +"dm", +"com.dm", +"net.dm", +"org.dm", +"edu.dm", +"gov.dm", +"do", +"art.do", +"com.do", +"edu.do", +"gob.do", +"gov.do", +"mil.do", +"net.do", +"org.do", +"sld.do", +"web.do", +"dz", +"com.dz", +"org.dz", +"net.dz", +"gov.dz", +"edu.dz", +"asso.dz", +"pol.dz", +"art.dz", +"ec", +"com.ec", +"info.ec", +"net.ec", +"fin.ec", +"k12.ec", +"med.ec", +"pro.ec", +"org.ec", +"edu.ec", +"gov.ec", +"gob.ec", +"mil.ec", +"edu", +"ee", +"edu.ee", +"gov.ee", +"riik.ee", +"lib.ee", +"med.ee", +"com.ee", +"pri.ee", +"aip.ee", +"org.ee", +"fie.ee", +"eg", +"com.eg", +"edu.eg", +"eun.eg", +"gov.eg", +"mil.eg", +"name.eg", +"net.eg", +"org.eg", +"sci.eg", +"*.er", +"es", +"com.es", +"nom.es", +"org.es", +"gob.es", +"edu.es", +"et", +"com.et", +"gov.et", +"org.et", +"edu.et", +"biz.et", +"name.et", +"info.et", +"net.et", +"eu", +"fi", +"aland.fi", +"fj", +"ac.fj", +"biz.fj", +"com.fj", +"gov.fj", +"info.fj", +"mil.fj", +"name.fj", +"net.fj", +"org.fj", +"pro.fj", +"*.fk", +"fm", +"fo", +"fr", +"asso.fr", +"com.fr", +"gouv.fr", +"nom.fr", +"prd.fr", +"tm.fr", +"aeroport.fr", +"avocat.fr", +"avoues.fr", +"cci.fr", +"chambagri.fr", +"chirurgiens-dentistes.fr", +"experts-comptables.fr", +"geometre-expert.fr", +"greta.fr", +"huissier-justice.fr", +"medecin.fr", +"notaires.fr", +"pharmacien.fr", +"port.fr", +"veterinaire.fr", +"ga", +"gb", +"gd", +"ge", +"com.ge", +"edu.ge", +"gov.ge", +"org.ge", +"mil.ge", +"net.ge", +"pvt.ge", +"gf", +"gg", +"co.gg", +"net.gg", +"org.gg", +"gh", +"com.gh", +"edu.gh", +"gov.gh", +"org.gh", +"mil.gh", +"gi", +"com.gi", +"ltd.gi", +"gov.gi", +"mod.gi", +"edu.gi", +"org.gi", +"gl", +"co.gl", +"com.gl", +"edu.gl", +"net.gl", +"org.gl", +"gm", +"gn", +"ac.gn", +"com.gn", +"edu.gn", +"gov.gn", +"org.gn", +"net.gn", +"gov", +"gp", +"com.gp", +"net.gp", +"mobi.gp", +"edu.gp", +"org.gp", +"asso.gp", +"gq", +"gr", +"com.gr", +"edu.gr", +"net.gr", +"org.gr", +"gov.gr", +"gs", +"gt", +"com.gt", +"edu.gt", +"gob.gt", +"ind.gt", +"mil.gt", +"net.gt", +"org.gt", +"gu", +"com.gu", +"edu.gu", +"gov.gu", +"guam.gu", +"info.gu", +"net.gu", +"org.gu", +"web.gu", +"gw", +"gy", +"co.gy", +"com.gy", +"edu.gy", +"gov.gy", +"net.gy", +"org.gy", +"hk", +"com.hk", +"edu.hk", +"gov.hk", +"idv.hk", +"net.hk", +"org.hk", +"公司.hk", +"教育.hk", +"敎育.hk", +"政府.hk", +"個人.hk", +"个人.hk", +"箇人.hk", +"網络.hk", +"网络.hk", +"组織.hk", +"網絡.hk", +"网絡.hk", +"组织.hk", +"組織.hk", +"組织.hk", +"hm", +"hn", +"com.hn", +"edu.hn", +"org.hn", +"net.hn", +"mil.hn", +"gob.hn", +"hr", +"iz.hr", +"from.hr", +"name.hr", +"com.hr", +"ht", +"com.ht", +"shop.ht", +"firm.ht", +"info.ht", +"adult.ht", +"net.ht", +"pro.ht", +"org.ht", +"med.ht", +"art.ht", +"coop.ht", +"pol.ht", +"asso.ht", +"edu.ht", +"rel.ht", +"gouv.ht", +"perso.ht", +"hu", +"co.hu", +"info.hu", +"org.hu", +"priv.hu", +"sport.hu", +"tm.hu", +"2000.hu", +"agrar.hu", +"bolt.hu", +"casino.hu", +"city.hu", +"erotica.hu", +"erotika.hu", +"film.hu", +"forum.hu", +"games.hu", +"hotel.hu", +"ingatlan.hu", +"jogasz.hu", +"konyvelo.hu", +"lakas.hu", +"media.hu", +"news.hu", +"reklam.hu", +"sex.hu", +"shop.hu", +"suli.hu", +"szex.hu", +"tozsde.hu", +"utazas.hu", +"video.hu", +"id", +"ac.id", +"biz.id", +"co.id", +"desa.id", +"go.id", +"mil.id", +"my.id", +"net.id", +"or.id", +"ponpes.id", +"sch.id", +"web.id", +"ie", +"gov.ie", +"il", +"ac.il", +"co.il", +"gov.il", +"idf.il", +"k12.il", +"muni.il", +"net.il", +"org.il", +"im", +"ac.im", +"co.im", +"com.im", +"ltd.co.im", +"net.im", +"org.im", +"plc.co.im", +"tt.im", +"tv.im", +"in", +"co.in", +"firm.in", +"net.in", +"org.in", +"gen.in", +"ind.in", +"nic.in", +"ac.in", +"edu.in", +"res.in", +"gov.in", +"mil.in", +"info", +"int", +"eu.int", +"io", +"com.io", +"iq", +"gov.iq", +"edu.iq", +"mil.iq", +"com.iq", +"org.iq", +"net.iq", +"ir", +"ac.ir", +"co.ir", +"gov.ir", +"id.ir", +"net.ir", +"org.ir", +"sch.ir", +"ایران.ir", +"ايران.ir", +"is", +"net.is", +"com.is", +"edu.is", +"gov.is", +"org.is", +"int.is", +"it", +"gov.it", +"edu.it", +"abr.it", +"abruzzo.it", +"aosta-valley.it", +"aostavalley.it", +"bas.it", +"basilicata.it", +"cal.it", +"calabria.it", +"cam.it", +"campania.it", +"emilia-romagna.it", +"emiliaromagna.it", +"emr.it", +"friuli-v-giulia.it", +"friuli-ve-giulia.it", +"friuli-vegiulia.it", +"friuli-venezia-giulia.it", +"friuli-veneziagiulia.it", +"friuli-vgiulia.it", +"friuliv-giulia.it", +"friulive-giulia.it", +"friulivegiulia.it", +"friulivenezia-giulia.it", +"friuliveneziagiulia.it", +"friulivgiulia.it", +"fvg.it", +"laz.it", +"lazio.it", +"lig.it", +"liguria.it", +"lom.it", +"lombardia.it", +"lombardy.it", +"lucania.it", +"mar.it", +"marche.it", +"mol.it", +"molise.it", +"piedmont.it", +"piemonte.it", +"pmn.it", +"pug.it", +"puglia.it", +"sar.it", +"sardegna.it", +"sardinia.it", +"sic.it", +"sicilia.it", +"sicily.it", +"taa.it", +"tos.it", +"toscana.it", +"trentin-sud-tirol.it", +"trentin-süd-tirol.it", +"trentin-sudtirol.it", +"trentin-südtirol.it", +"trentin-sued-tirol.it", +"trentin-suedtirol.it", +"trentino-a-adige.it", +"trentino-aadige.it", +"trentino-alto-adige.it", +"trentino-altoadige.it", +"trentino-s-tirol.it", +"trentino-stirol.it", +"trentino-sud-tirol.it", +"trentino-süd-tirol.it", +"trentino-sudtirol.it", +"trentino-südtirol.it", +"trentino-sued-tirol.it", +"trentino-suedtirol.it", +"trentino.it", +"trentinoa-adige.it", +"trentinoaadige.it", +"trentinoalto-adige.it", +"trentinoaltoadige.it", +"trentinos-tirol.it", +"trentinostirol.it", +"trentinosud-tirol.it", +"trentinosüd-tirol.it", +"trentinosudtirol.it", +"trentinosüdtirol.it", +"trentinosued-tirol.it", +"trentinosuedtirol.it", +"trentinsud-tirol.it", +"trentinsüd-tirol.it", +"trentinsudtirol.it", +"trentinsüdtirol.it", +"trentinsued-tirol.it", +"trentinsuedtirol.it", +"tuscany.it", +"umb.it", +"umbria.it", +"val-d-aosta.it", +"val-daosta.it", +"vald-aosta.it", +"valdaosta.it", +"valle-aosta.it", +"valle-d-aosta.it", +"valle-daosta.it", +"valleaosta.it", +"valled-aosta.it", +"valledaosta.it", +"vallee-aoste.it", +"vallée-aoste.it", +"vallee-d-aoste.it", +"vallée-d-aoste.it", +"valleeaoste.it", +"valléeaoste.it", +"valleedaoste.it", +"valléedaoste.it", +"vao.it", +"vda.it", +"ven.it", +"veneto.it", +"ag.it", +"agrigento.it", +"al.it", +"alessandria.it", +"alto-adige.it", +"altoadige.it", +"an.it", +"ancona.it", +"andria-barletta-trani.it", +"andria-trani-barletta.it", +"andriabarlettatrani.it", +"andriatranibarletta.it", +"ao.it", +"aosta.it", +"aoste.it", +"ap.it", +"aq.it", +"aquila.it", +"ar.it", +"arezzo.it", +"ascoli-piceno.it", +"ascolipiceno.it", +"asti.it", +"at.it", +"av.it", +"avellino.it", +"ba.it", +"balsan-sudtirol.it", +"balsan-südtirol.it", +"balsan-suedtirol.it", +"balsan.it", +"bari.it", +"barletta-trani-andria.it", +"barlettatraniandria.it", +"belluno.it", +"benevento.it", +"bergamo.it", +"bg.it", +"bi.it", +"biella.it", +"bl.it", +"bn.it", +"bo.it", +"bologna.it", +"bolzano-altoadige.it", +"bolzano.it", +"bozen-sudtirol.it", +"bozen-südtirol.it", +"bozen-suedtirol.it", +"bozen.it", +"br.it", +"brescia.it", +"brindisi.it", +"bs.it", +"bt.it", +"bulsan-sudtirol.it", +"bulsan-südtirol.it", +"bulsan-suedtirol.it", +"bulsan.it", +"bz.it", +"ca.it", +"cagliari.it", +"caltanissetta.it", +"campidano-medio.it", +"campidanomedio.it", +"campobasso.it", +"carbonia-iglesias.it", +"carboniaiglesias.it", +"carrara-massa.it", +"carraramassa.it", +"caserta.it", +"catania.it", +"catanzaro.it", +"cb.it", +"ce.it", +"cesena-forli.it", +"cesena-forlì.it", +"cesenaforli.it", +"cesenaforlì.it", +"ch.it", +"chieti.it", +"ci.it", +"cl.it", +"cn.it", +"co.it", +"como.it", +"cosenza.it", +"cr.it", +"cremona.it", +"crotone.it", +"cs.it", +"ct.it", +"cuneo.it", +"cz.it", +"dell-ogliastra.it", +"dellogliastra.it", +"en.it", +"enna.it", +"fc.it", +"fe.it", +"fermo.it", +"ferrara.it", +"fg.it", +"fi.it", +"firenze.it", +"florence.it", +"fm.it", +"foggia.it", +"forli-cesena.it", +"forlì-cesena.it", +"forlicesena.it", +"forlìcesena.it", +"fr.it", +"frosinone.it", +"ge.it", +"genoa.it", +"genova.it", +"go.it", +"gorizia.it", +"gr.it", +"grosseto.it", +"iglesias-carbonia.it", +"iglesiascarbonia.it", +"im.it", +"imperia.it", +"is.it", +"isernia.it", +"kr.it", +"la-spezia.it", +"laquila.it", +"laspezia.it", +"latina.it", +"lc.it", +"le.it", +"lecce.it", +"lecco.it", +"li.it", +"livorno.it", +"lo.it", +"lodi.it", +"lt.it", +"lu.it", +"lucca.it", +"macerata.it", +"mantova.it", +"massa-carrara.it", +"massacarrara.it", +"matera.it", +"mb.it", +"mc.it", +"me.it", +"medio-campidano.it", +"mediocampidano.it", +"messina.it", +"mi.it", +"milan.it", +"milano.it", +"mn.it", +"mo.it", +"modena.it", +"monza-brianza.it", +"monza-e-della-brianza.it", +"monza.it", +"monzabrianza.it", +"monzaebrianza.it", +"monzaedellabrianza.it", +"ms.it", +"mt.it", +"na.it", +"naples.it", +"napoli.it", +"no.it", +"novara.it", +"nu.it", +"nuoro.it", +"og.it", +"ogliastra.it", +"olbia-tempio.it", +"olbiatempio.it", +"or.it", +"oristano.it", +"ot.it", +"pa.it", +"padova.it", +"padua.it", +"palermo.it", +"parma.it", +"pavia.it", +"pc.it", +"pd.it", +"pe.it", +"perugia.it", +"pesaro-urbino.it", +"pesarourbino.it", +"pescara.it", +"pg.it", +"pi.it", +"piacenza.it", +"pisa.it", +"pistoia.it", +"pn.it", +"po.it", +"pordenone.it", +"potenza.it", +"pr.it", +"prato.it", +"pt.it", +"pu.it", +"pv.it", +"pz.it", +"ra.it", +"ragusa.it", +"ravenna.it", +"rc.it", +"re.it", +"reggio-calabria.it", +"reggio-emilia.it", +"reggiocalabria.it", +"reggioemilia.it", +"rg.it", +"ri.it", +"rieti.it", +"rimini.it", +"rm.it", +"rn.it", +"ro.it", +"roma.it", +"rome.it", +"rovigo.it", +"sa.it", +"salerno.it", +"sassari.it", +"savona.it", +"si.it", +"siena.it", +"siracusa.it", +"so.it", +"sondrio.it", +"sp.it", +"sr.it", +"ss.it", +"suedtirol.it", +"südtirol.it", +"sv.it", +"ta.it", +"taranto.it", +"te.it", +"tempio-olbia.it", +"tempioolbia.it", +"teramo.it", +"terni.it", +"tn.it", +"to.it", +"torino.it", +"tp.it", +"tr.it", +"trani-andria-barletta.it", +"trani-barletta-andria.it", +"traniandriabarletta.it", +"tranibarlettaandria.it", +"trapani.it", +"trento.it", +"treviso.it", +"trieste.it", +"ts.it", +"turin.it", +"tv.it", +"ud.it", +"udine.it", +"urbino-pesaro.it", +"urbinopesaro.it", +"va.it", +"varese.it", +"vb.it", +"vc.it", +"ve.it", +"venezia.it", +"venice.it", +"verbania.it", +"vercelli.it", +"verona.it", +"vi.it", +"vibo-valentia.it", +"vibovalentia.it", +"vicenza.it", +"viterbo.it", +"vr.it", +"vs.it", +"vt.it", +"vv.it", +"je", +"co.je", +"net.je", +"org.je", +"*.jm", +"jo", +"com.jo", +"org.jo", +"net.jo", +"edu.jo", +"sch.jo", +"gov.jo", +"mil.jo", +"name.jo", +"jobs", +"jp", +"ac.jp", +"ad.jp", +"co.jp", +"ed.jp", +"go.jp", +"gr.jp", +"lg.jp", +"ne.jp", +"or.jp", +"aichi.jp", +"akita.jp", +"aomori.jp", +"chiba.jp", +"ehime.jp", +"fukui.jp", +"fukuoka.jp", +"fukushima.jp", +"gifu.jp", +"gunma.jp", +"hiroshima.jp", +"hokkaido.jp", +"hyogo.jp", +"ibaraki.jp", +"ishikawa.jp", +"iwate.jp", +"kagawa.jp", +"kagoshima.jp", +"kanagawa.jp", +"kochi.jp", +"kumamoto.jp", +"kyoto.jp", +"mie.jp", +"miyagi.jp", +"miyazaki.jp", +"nagano.jp", +"nagasaki.jp", +"nara.jp", +"niigata.jp", +"oita.jp", +"okayama.jp", +"okinawa.jp", +"osaka.jp", +"saga.jp", +"saitama.jp", +"shiga.jp", +"shimane.jp", +"shizuoka.jp", +"tochigi.jp", +"tokushima.jp", +"tokyo.jp", +"tottori.jp", +"toyama.jp", +"wakayama.jp", +"yamagata.jp", +"yamaguchi.jp", +"yamanashi.jp", +"栃木.jp", +"愛知.jp", +"愛媛.jp", +"兵庫.jp", +"熊本.jp", +"茨城.jp", +"北海道.jp", +"千葉.jp", +"和歌山.jp", +"長崎.jp", +"長野.jp", +"新潟.jp", +"青森.jp", +"静岡.jp", +"東京.jp", +"石川.jp", +"埼玉.jp", +"三重.jp", +"京都.jp", +"佐賀.jp", +"大分.jp", +"大阪.jp", +"奈良.jp", +"宮城.jp", +"宮崎.jp", +"富山.jp", +"山口.jp", +"山形.jp", +"山梨.jp", +"岩手.jp", +"岐阜.jp", +"岡山.jp", +"島根.jp", +"広島.jp", +"徳島.jp", +"沖縄.jp", +"滋賀.jp", +"神奈川.jp", +"福井.jp", +"福岡.jp", +"福島.jp", +"秋田.jp", +"群馬.jp", +"香川.jp", +"高知.jp", +"鳥取.jp", +"鹿児島.jp", +"*.kawasaki.jp", +"*.kitakyushu.jp", +"*.kobe.jp", +"*.nagoya.jp", +"*.sapporo.jp", +"*.sendai.jp", +"*.yokohama.jp", +"!city.kawasaki.jp", +"!city.kitakyushu.jp", +"!city.kobe.jp", +"!city.nagoya.jp", +"!city.sapporo.jp", +"!city.sendai.jp", +"!city.yokohama.jp", +"aisai.aichi.jp", +"ama.aichi.jp", +"anjo.aichi.jp", +"asuke.aichi.jp", +"chiryu.aichi.jp", +"chita.aichi.jp", +"fuso.aichi.jp", +"gamagori.aichi.jp", +"handa.aichi.jp", +"hazu.aichi.jp", +"hekinan.aichi.jp", +"higashiura.aichi.jp", +"ichinomiya.aichi.jp", +"inazawa.aichi.jp", +"inuyama.aichi.jp", +"isshiki.aichi.jp", +"iwakura.aichi.jp", +"kanie.aichi.jp", +"kariya.aichi.jp", +"kasugai.aichi.jp", +"kira.aichi.jp", +"kiyosu.aichi.jp", +"komaki.aichi.jp", +"konan.aichi.jp", +"kota.aichi.jp", +"mihama.aichi.jp", +"miyoshi.aichi.jp", +"nishio.aichi.jp", +"nisshin.aichi.jp", +"obu.aichi.jp", +"oguchi.aichi.jp", +"oharu.aichi.jp", +"okazaki.aichi.jp", +"owariasahi.aichi.jp", +"seto.aichi.jp", +"shikatsu.aichi.jp", +"shinshiro.aichi.jp", +"shitara.aichi.jp", +"tahara.aichi.jp", +"takahama.aichi.jp", +"tobishima.aichi.jp", +"toei.aichi.jp", +"togo.aichi.jp", +"tokai.aichi.jp", +"tokoname.aichi.jp", +"toyoake.aichi.jp", +"toyohashi.aichi.jp", +"toyokawa.aichi.jp", +"toyone.aichi.jp", +"toyota.aichi.jp", +"tsushima.aichi.jp", +"yatomi.aichi.jp", +"akita.akita.jp", +"daisen.akita.jp", +"fujisato.akita.jp", +"gojome.akita.jp", +"hachirogata.akita.jp", +"happou.akita.jp", +"higashinaruse.akita.jp", +"honjo.akita.jp", +"honjyo.akita.jp", +"ikawa.akita.jp", +"kamikoani.akita.jp", +"kamioka.akita.jp", +"katagami.akita.jp", +"kazuno.akita.jp", +"kitaakita.akita.jp", +"kosaka.akita.jp", +"kyowa.akita.jp", +"misato.akita.jp", +"mitane.akita.jp", +"moriyoshi.akita.jp", +"nikaho.akita.jp", +"noshiro.akita.jp", +"odate.akita.jp", +"oga.akita.jp", +"ogata.akita.jp", +"semboku.akita.jp", +"yokote.akita.jp", +"yurihonjo.akita.jp", +"aomori.aomori.jp", +"gonohe.aomori.jp", +"hachinohe.aomori.jp", +"hashikami.aomori.jp", +"hiranai.aomori.jp", +"hirosaki.aomori.jp", +"itayanagi.aomori.jp", +"kuroishi.aomori.jp", +"misawa.aomori.jp", +"mutsu.aomori.jp", +"nakadomari.aomori.jp", +"noheji.aomori.jp", +"oirase.aomori.jp", +"owani.aomori.jp", +"rokunohe.aomori.jp", +"sannohe.aomori.jp", +"shichinohe.aomori.jp", +"shingo.aomori.jp", +"takko.aomori.jp", +"towada.aomori.jp", +"tsugaru.aomori.jp", +"tsuruta.aomori.jp", +"abiko.chiba.jp", +"asahi.chiba.jp", +"chonan.chiba.jp", +"chosei.chiba.jp", +"choshi.chiba.jp", +"chuo.chiba.jp", +"funabashi.chiba.jp", +"futtsu.chiba.jp", +"hanamigawa.chiba.jp", +"ichihara.chiba.jp", +"ichikawa.chiba.jp", +"ichinomiya.chiba.jp", +"inzai.chiba.jp", +"isumi.chiba.jp", +"kamagaya.chiba.jp", +"kamogawa.chiba.jp", +"kashiwa.chiba.jp", +"katori.chiba.jp", +"katsuura.chiba.jp", +"kimitsu.chiba.jp", +"kisarazu.chiba.jp", +"kozaki.chiba.jp", +"kujukuri.chiba.jp", +"kyonan.chiba.jp", +"matsudo.chiba.jp", +"midori.chiba.jp", +"mihama.chiba.jp", +"minamiboso.chiba.jp", +"mobara.chiba.jp", +"mutsuzawa.chiba.jp", +"nagara.chiba.jp", +"nagareyama.chiba.jp", +"narashino.chiba.jp", +"narita.chiba.jp", +"noda.chiba.jp", +"oamishirasato.chiba.jp", +"omigawa.chiba.jp", +"onjuku.chiba.jp", +"otaki.chiba.jp", +"sakae.chiba.jp", +"sakura.chiba.jp", +"shimofusa.chiba.jp", +"shirako.chiba.jp", +"shiroi.chiba.jp", +"shisui.chiba.jp", +"sodegaura.chiba.jp", +"sosa.chiba.jp", +"tako.chiba.jp", +"tateyama.chiba.jp", +"togane.chiba.jp", +"tohnosho.chiba.jp", +"tomisato.chiba.jp", +"urayasu.chiba.jp", +"yachimata.chiba.jp", +"yachiyo.chiba.jp", +"yokaichiba.chiba.jp", +"yokoshibahikari.chiba.jp", +"yotsukaido.chiba.jp", +"ainan.ehime.jp", +"honai.ehime.jp", +"ikata.ehime.jp", +"imabari.ehime.jp", +"iyo.ehime.jp", +"kamijima.ehime.jp", +"kihoku.ehime.jp", +"kumakogen.ehime.jp", +"masaki.ehime.jp", +"matsuno.ehime.jp", +"matsuyama.ehime.jp", +"namikata.ehime.jp", +"niihama.ehime.jp", +"ozu.ehime.jp", +"saijo.ehime.jp", +"seiyo.ehime.jp", +"shikokuchuo.ehime.jp", +"tobe.ehime.jp", +"toon.ehime.jp", +"uchiko.ehime.jp", +"uwajima.ehime.jp", +"yawatahama.ehime.jp", +"echizen.fukui.jp", +"eiheiji.fukui.jp", +"fukui.fukui.jp", +"ikeda.fukui.jp", +"katsuyama.fukui.jp", +"mihama.fukui.jp", +"minamiechizen.fukui.jp", +"obama.fukui.jp", +"ohi.fukui.jp", +"ono.fukui.jp", +"sabae.fukui.jp", +"sakai.fukui.jp", +"takahama.fukui.jp", +"tsuruga.fukui.jp", +"wakasa.fukui.jp", +"ashiya.fukuoka.jp", +"buzen.fukuoka.jp", +"chikugo.fukuoka.jp", +"chikuho.fukuoka.jp", +"chikujo.fukuoka.jp", +"chikushino.fukuoka.jp", +"chikuzen.fukuoka.jp", +"chuo.fukuoka.jp", +"dazaifu.fukuoka.jp", +"fukuchi.fukuoka.jp", +"hakata.fukuoka.jp", +"higashi.fukuoka.jp", +"hirokawa.fukuoka.jp", +"hisayama.fukuoka.jp", +"iizuka.fukuoka.jp", +"inatsuki.fukuoka.jp", +"kaho.fukuoka.jp", +"kasuga.fukuoka.jp", +"kasuya.fukuoka.jp", +"kawara.fukuoka.jp", +"keisen.fukuoka.jp", +"koga.fukuoka.jp", +"kurate.fukuoka.jp", +"kurogi.fukuoka.jp", +"kurume.fukuoka.jp", +"minami.fukuoka.jp", +"miyako.fukuoka.jp", +"miyama.fukuoka.jp", +"miyawaka.fukuoka.jp", +"mizumaki.fukuoka.jp", +"munakata.fukuoka.jp", +"nakagawa.fukuoka.jp", +"nakama.fukuoka.jp", +"nishi.fukuoka.jp", +"nogata.fukuoka.jp", +"ogori.fukuoka.jp", +"okagaki.fukuoka.jp", +"okawa.fukuoka.jp", +"oki.fukuoka.jp", +"omuta.fukuoka.jp", +"onga.fukuoka.jp", +"onojo.fukuoka.jp", +"oto.fukuoka.jp", +"saigawa.fukuoka.jp", +"sasaguri.fukuoka.jp", +"shingu.fukuoka.jp", +"shinyoshitomi.fukuoka.jp", +"shonai.fukuoka.jp", +"soeda.fukuoka.jp", +"sue.fukuoka.jp", +"tachiarai.fukuoka.jp", +"tagawa.fukuoka.jp", +"takata.fukuoka.jp", +"toho.fukuoka.jp", +"toyotsu.fukuoka.jp", +"tsuiki.fukuoka.jp", +"ukiha.fukuoka.jp", +"umi.fukuoka.jp", +"usui.fukuoka.jp", +"yamada.fukuoka.jp", +"yame.fukuoka.jp", +"yanagawa.fukuoka.jp", +"yukuhashi.fukuoka.jp", +"aizubange.fukushima.jp", +"aizumisato.fukushima.jp", +"aizuwakamatsu.fukushima.jp", +"asakawa.fukushima.jp", +"bandai.fukushima.jp", +"date.fukushima.jp", +"fukushima.fukushima.jp", +"furudono.fukushima.jp", +"futaba.fukushima.jp", +"hanawa.fukushima.jp", +"higashi.fukushima.jp", +"hirata.fukushima.jp", +"hirono.fukushima.jp", +"iitate.fukushima.jp", +"inawashiro.fukushima.jp", +"ishikawa.fukushima.jp", +"iwaki.fukushima.jp", +"izumizaki.fukushima.jp", +"kagamiishi.fukushima.jp", +"kaneyama.fukushima.jp", +"kawamata.fukushima.jp", +"kitakata.fukushima.jp", +"kitashiobara.fukushima.jp", +"koori.fukushima.jp", +"koriyama.fukushima.jp", +"kunimi.fukushima.jp", +"miharu.fukushima.jp", +"mishima.fukushima.jp", +"namie.fukushima.jp", +"nango.fukushima.jp", +"nishiaizu.fukushima.jp", +"nishigo.fukushima.jp", +"okuma.fukushima.jp", +"omotego.fukushima.jp", +"ono.fukushima.jp", +"otama.fukushima.jp", +"samegawa.fukushima.jp", +"shimogo.fukushima.jp", +"shirakawa.fukushima.jp", +"showa.fukushima.jp", +"soma.fukushima.jp", +"sukagawa.fukushima.jp", +"taishin.fukushima.jp", +"tamakawa.fukushima.jp", +"tanagura.fukushima.jp", +"tenei.fukushima.jp", +"yabuki.fukushima.jp", +"yamato.fukushima.jp", +"yamatsuri.fukushima.jp", +"yanaizu.fukushima.jp", +"yugawa.fukushima.jp", +"anpachi.gifu.jp", +"ena.gifu.jp", +"gifu.gifu.jp", +"ginan.gifu.jp", +"godo.gifu.jp", +"gujo.gifu.jp", +"hashima.gifu.jp", +"hichiso.gifu.jp", +"hida.gifu.jp", +"higashishirakawa.gifu.jp", +"ibigawa.gifu.jp", +"ikeda.gifu.jp", +"kakamigahara.gifu.jp", +"kani.gifu.jp", +"kasahara.gifu.jp", +"kasamatsu.gifu.jp", +"kawaue.gifu.jp", +"kitagata.gifu.jp", +"mino.gifu.jp", +"minokamo.gifu.jp", +"mitake.gifu.jp", +"mizunami.gifu.jp", +"motosu.gifu.jp", +"nakatsugawa.gifu.jp", +"ogaki.gifu.jp", +"sakahogi.gifu.jp", +"seki.gifu.jp", +"sekigahara.gifu.jp", +"shirakawa.gifu.jp", +"tajimi.gifu.jp", +"takayama.gifu.jp", +"tarui.gifu.jp", +"toki.gifu.jp", +"tomika.gifu.jp", +"wanouchi.gifu.jp", +"yamagata.gifu.jp", +"yaotsu.gifu.jp", +"yoro.gifu.jp", +"annaka.gunma.jp", +"chiyoda.gunma.jp", +"fujioka.gunma.jp", +"higashiagatsuma.gunma.jp", +"isesaki.gunma.jp", +"itakura.gunma.jp", +"kanna.gunma.jp", +"kanra.gunma.jp", +"katashina.gunma.jp", +"kawaba.gunma.jp", +"kiryu.gunma.jp", +"kusatsu.gunma.jp", +"maebashi.gunma.jp", +"meiwa.gunma.jp", +"midori.gunma.jp", +"minakami.gunma.jp", +"naganohara.gunma.jp", +"nakanojo.gunma.jp", +"nanmoku.gunma.jp", +"numata.gunma.jp", +"oizumi.gunma.jp", +"ora.gunma.jp", +"ota.gunma.jp", +"shibukawa.gunma.jp", +"shimonita.gunma.jp", +"shinto.gunma.jp", +"showa.gunma.jp", +"takasaki.gunma.jp", +"takayama.gunma.jp", +"tamamura.gunma.jp", +"tatebayashi.gunma.jp", +"tomioka.gunma.jp", +"tsukiyono.gunma.jp", +"tsumagoi.gunma.jp", +"ueno.gunma.jp", +"yoshioka.gunma.jp", +"asaminami.hiroshima.jp", +"daiwa.hiroshima.jp", +"etajima.hiroshima.jp", +"fuchu.hiroshima.jp", +"fukuyama.hiroshima.jp", +"hatsukaichi.hiroshima.jp", +"higashihiroshima.hiroshima.jp", +"hongo.hiroshima.jp", +"jinsekikogen.hiroshima.jp", +"kaita.hiroshima.jp", +"kui.hiroshima.jp", +"kumano.hiroshima.jp", +"kure.hiroshima.jp", +"mihara.hiroshima.jp", +"miyoshi.hiroshima.jp", +"naka.hiroshima.jp", +"onomichi.hiroshima.jp", +"osakikamijima.hiroshima.jp", +"otake.hiroshima.jp", +"saka.hiroshima.jp", +"sera.hiroshima.jp", +"seranishi.hiroshima.jp", +"shinichi.hiroshima.jp", +"shobara.hiroshima.jp", +"takehara.hiroshima.jp", +"abashiri.hokkaido.jp", +"abira.hokkaido.jp", +"aibetsu.hokkaido.jp", +"akabira.hokkaido.jp", +"akkeshi.hokkaido.jp", +"asahikawa.hokkaido.jp", +"ashibetsu.hokkaido.jp", +"ashoro.hokkaido.jp", +"assabu.hokkaido.jp", +"atsuma.hokkaido.jp", +"bibai.hokkaido.jp", +"biei.hokkaido.jp", +"bifuka.hokkaido.jp", +"bihoro.hokkaido.jp", +"biratori.hokkaido.jp", +"chippubetsu.hokkaido.jp", +"chitose.hokkaido.jp", +"date.hokkaido.jp", +"ebetsu.hokkaido.jp", +"embetsu.hokkaido.jp", +"eniwa.hokkaido.jp", +"erimo.hokkaido.jp", +"esan.hokkaido.jp", +"esashi.hokkaido.jp", +"fukagawa.hokkaido.jp", +"fukushima.hokkaido.jp", +"furano.hokkaido.jp", +"furubira.hokkaido.jp", +"haboro.hokkaido.jp", +"hakodate.hokkaido.jp", +"hamatonbetsu.hokkaido.jp", +"hidaka.hokkaido.jp", +"higashikagura.hokkaido.jp", +"higashikawa.hokkaido.jp", +"hiroo.hokkaido.jp", +"hokuryu.hokkaido.jp", +"hokuto.hokkaido.jp", +"honbetsu.hokkaido.jp", +"horokanai.hokkaido.jp", +"horonobe.hokkaido.jp", +"ikeda.hokkaido.jp", +"imakane.hokkaido.jp", +"ishikari.hokkaido.jp", +"iwamizawa.hokkaido.jp", +"iwanai.hokkaido.jp", +"kamifurano.hokkaido.jp", +"kamikawa.hokkaido.jp", +"kamishihoro.hokkaido.jp", +"kamisunagawa.hokkaido.jp", +"kamoenai.hokkaido.jp", +"kayabe.hokkaido.jp", +"kembuchi.hokkaido.jp", +"kikonai.hokkaido.jp", +"kimobetsu.hokkaido.jp", +"kitahiroshima.hokkaido.jp", +"kitami.hokkaido.jp", +"kiyosato.hokkaido.jp", +"koshimizu.hokkaido.jp", +"kunneppu.hokkaido.jp", +"kuriyama.hokkaido.jp", +"kuromatsunai.hokkaido.jp", +"kushiro.hokkaido.jp", +"kutchan.hokkaido.jp", +"kyowa.hokkaido.jp", +"mashike.hokkaido.jp", +"matsumae.hokkaido.jp", +"mikasa.hokkaido.jp", +"minamifurano.hokkaido.jp", +"mombetsu.hokkaido.jp", +"moseushi.hokkaido.jp", +"mukawa.hokkaido.jp", +"muroran.hokkaido.jp", +"naie.hokkaido.jp", +"nakagawa.hokkaido.jp", +"nakasatsunai.hokkaido.jp", +"nakatombetsu.hokkaido.jp", +"nanae.hokkaido.jp", +"nanporo.hokkaido.jp", +"nayoro.hokkaido.jp", +"nemuro.hokkaido.jp", +"niikappu.hokkaido.jp", +"niki.hokkaido.jp", +"nishiokoppe.hokkaido.jp", +"noboribetsu.hokkaido.jp", +"numata.hokkaido.jp", +"obihiro.hokkaido.jp", +"obira.hokkaido.jp", +"oketo.hokkaido.jp", +"okoppe.hokkaido.jp", +"otaru.hokkaido.jp", +"otobe.hokkaido.jp", +"otofuke.hokkaido.jp", +"otoineppu.hokkaido.jp", +"oumu.hokkaido.jp", +"ozora.hokkaido.jp", +"pippu.hokkaido.jp", +"rankoshi.hokkaido.jp", +"rebun.hokkaido.jp", +"rikubetsu.hokkaido.jp", +"rishiri.hokkaido.jp", +"rishirifuji.hokkaido.jp", +"saroma.hokkaido.jp", +"sarufutsu.hokkaido.jp", +"shakotan.hokkaido.jp", +"shari.hokkaido.jp", +"shibecha.hokkaido.jp", +"shibetsu.hokkaido.jp", +"shikabe.hokkaido.jp", +"shikaoi.hokkaido.jp", +"shimamaki.hokkaido.jp", +"shimizu.hokkaido.jp", +"shimokawa.hokkaido.jp", +"shinshinotsu.hokkaido.jp", +"shintoku.hokkaido.jp", +"shiranuka.hokkaido.jp", +"shiraoi.hokkaido.jp", +"shiriuchi.hokkaido.jp", +"sobetsu.hokkaido.jp", +"sunagawa.hokkaido.jp", +"taiki.hokkaido.jp", +"takasu.hokkaido.jp", +"takikawa.hokkaido.jp", +"takinoue.hokkaido.jp", +"teshikaga.hokkaido.jp", +"tobetsu.hokkaido.jp", +"tohma.hokkaido.jp", +"tomakomai.hokkaido.jp", +"tomari.hokkaido.jp", +"toya.hokkaido.jp", +"toyako.hokkaido.jp", +"toyotomi.hokkaido.jp", +"toyoura.hokkaido.jp", +"tsubetsu.hokkaido.jp", +"tsukigata.hokkaido.jp", +"urakawa.hokkaido.jp", +"urausu.hokkaido.jp", +"uryu.hokkaido.jp", +"utashinai.hokkaido.jp", +"wakkanai.hokkaido.jp", +"wassamu.hokkaido.jp", +"yakumo.hokkaido.jp", +"yoichi.hokkaido.jp", +"aioi.hyogo.jp", +"akashi.hyogo.jp", +"ako.hyogo.jp", +"amagasaki.hyogo.jp", +"aogaki.hyogo.jp", +"asago.hyogo.jp", +"ashiya.hyogo.jp", +"awaji.hyogo.jp", +"fukusaki.hyogo.jp", +"goshiki.hyogo.jp", +"harima.hyogo.jp", +"himeji.hyogo.jp", +"ichikawa.hyogo.jp", +"inagawa.hyogo.jp", +"itami.hyogo.jp", +"kakogawa.hyogo.jp", +"kamigori.hyogo.jp", +"kamikawa.hyogo.jp", +"kasai.hyogo.jp", +"kasuga.hyogo.jp", +"kawanishi.hyogo.jp", +"miki.hyogo.jp", +"minamiawaji.hyogo.jp", +"nishinomiya.hyogo.jp", +"nishiwaki.hyogo.jp", +"ono.hyogo.jp", +"sanda.hyogo.jp", +"sannan.hyogo.jp", +"sasayama.hyogo.jp", +"sayo.hyogo.jp", +"shingu.hyogo.jp", +"shinonsen.hyogo.jp", +"shiso.hyogo.jp", +"sumoto.hyogo.jp", +"taishi.hyogo.jp", +"taka.hyogo.jp", +"takarazuka.hyogo.jp", +"takasago.hyogo.jp", +"takino.hyogo.jp", +"tamba.hyogo.jp", +"tatsuno.hyogo.jp", +"toyooka.hyogo.jp", +"yabu.hyogo.jp", +"yashiro.hyogo.jp", +"yoka.hyogo.jp", +"yokawa.hyogo.jp", +"ami.ibaraki.jp", +"asahi.ibaraki.jp", +"bando.ibaraki.jp", +"chikusei.ibaraki.jp", +"daigo.ibaraki.jp", +"fujishiro.ibaraki.jp", +"hitachi.ibaraki.jp", +"hitachinaka.ibaraki.jp", +"hitachiomiya.ibaraki.jp", +"hitachiota.ibaraki.jp", +"ibaraki.ibaraki.jp", +"ina.ibaraki.jp", +"inashiki.ibaraki.jp", +"itako.ibaraki.jp", +"iwama.ibaraki.jp", +"joso.ibaraki.jp", +"kamisu.ibaraki.jp", +"kasama.ibaraki.jp", +"kashima.ibaraki.jp", +"kasumigaura.ibaraki.jp", +"koga.ibaraki.jp", +"miho.ibaraki.jp", +"mito.ibaraki.jp", +"moriya.ibaraki.jp", +"naka.ibaraki.jp", +"namegata.ibaraki.jp", +"oarai.ibaraki.jp", +"ogawa.ibaraki.jp", +"omitama.ibaraki.jp", +"ryugasaki.ibaraki.jp", +"sakai.ibaraki.jp", +"sakuragawa.ibaraki.jp", +"shimodate.ibaraki.jp", +"shimotsuma.ibaraki.jp", +"shirosato.ibaraki.jp", +"sowa.ibaraki.jp", +"suifu.ibaraki.jp", +"takahagi.ibaraki.jp", +"tamatsukuri.ibaraki.jp", +"tokai.ibaraki.jp", +"tomobe.ibaraki.jp", +"tone.ibaraki.jp", +"toride.ibaraki.jp", +"tsuchiura.ibaraki.jp", +"tsukuba.ibaraki.jp", +"uchihara.ibaraki.jp", +"ushiku.ibaraki.jp", +"yachiyo.ibaraki.jp", +"yamagata.ibaraki.jp", +"yawara.ibaraki.jp", +"yuki.ibaraki.jp", +"anamizu.ishikawa.jp", +"hakui.ishikawa.jp", +"hakusan.ishikawa.jp", +"kaga.ishikawa.jp", +"kahoku.ishikawa.jp", +"kanazawa.ishikawa.jp", +"kawakita.ishikawa.jp", +"komatsu.ishikawa.jp", +"nakanoto.ishikawa.jp", +"nanao.ishikawa.jp", +"nomi.ishikawa.jp", +"nonoichi.ishikawa.jp", +"noto.ishikawa.jp", +"shika.ishikawa.jp", +"suzu.ishikawa.jp", +"tsubata.ishikawa.jp", +"tsurugi.ishikawa.jp", +"uchinada.ishikawa.jp", +"wajima.ishikawa.jp", +"fudai.iwate.jp", +"fujisawa.iwate.jp", +"hanamaki.iwate.jp", +"hiraizumi.iwate.jp", +"hirono.iwate.jp", +"ichinohe.iwate.jp", +"ichinoseki.iwate.jp", +"iwaizumi.iwate.jp", +"iwate.iwate.jp", +"joboji.iwate.jp", +"kamaishi.iwate.jp", +"kanegasaki.iwate.jp", +"karumai.iwate.jp", +"kawai.iwate.jp", +"kitakami.iwate.jp", +"kuji.iwate.jp", +"kunohe.iwate.jp", +"kuzumaki.iwate.jp", +"miyako.iwate.jp", +"mizusawa.iwate.jp", +"morioka.iwate.jp", +"ninohe.iwate.jp", +"noda.iwate.jp", +"ofunato.iwate.jp", +"oshu.iwate.jp", +"otsuchi.iwate.jp", +"rikuzentakata.iwate.jp", +"shiwa.iwate.jp", +"shizukuishi.iwate.jp", +"sumita.iwate.jp", +"tanohata.iwate.jp", +"tono.iwate.jp", +"yahaba.iwate.jp", +"yamada.iwate.jp", +"ayagawa.kagawa.jp", +"higashikagawa.kagawa.jp", +"kanonji.kagawa.jp", +"kotohira.kagawa.jp", +"manno.kagawa.jp", +"marugame.kagawa.jp", +"mitoyo.kagawa.jp", +"naoshima.kagawa.jp", +"sanuki.kagawa.jp", +"tadotsu.kagawa.jp", +"takamatsu.kagawa.jp", +"tonosho.kagawa.jp", +"uchinomi.kagawa.jp", +"utazu.kagawa.jp", +"zentsuji.kagawa.jp", +"akune.kagoshima.jp", +"amami.kagoshima.jp", +"hioki.kagoshima.jp", +"isa.kagoshima.jp", +"isen.kagoshima.jp", +"izumi.kagoshima.jp", +"kagoshima.kagoshima.jp", +"kanoya.kagoshima.jp", +"kawanabe.kagoshima.jp", +"kinko.kagoshima.jp", +"kouyama.kagoshima.jp", +"makurazaki.kagoshima.jp", +"matsumoto.kagoshima.jp", +"minamitane.kagoshima.jp", +"nakatane.kagoshima.jp", +"nishinoomote.kagoshima.jp", +"satsumasendai.kagoshima.jp", +"soo.kagoshima.jp", +"tarumizu.kagoshima.jp", +"yusui.kagoshima.jp", +"aikawa.kanagawa.jp", +"atsugi.kanagawa.jp", +"ayase.kanagawa.jp", +"chigasaki.kanagawa.jp", +"ebina.kanagawa.jp", +"fujisawa.kanagawa.jp", +"hadano.kanagawa.jp", +"hakone.kanagawa.jp", +"hiratsuka.kanagawa.jp", +"isehara.kanagawa.jp", +"kaisei.kanagawa.jp", +"kamakura.kanagawa.jp", +"kiyokawa.kanagawa.jp", +"matsuda.kanagawa.jp", +"minamiashigara.kanagawa.jp", +"miura.kanagawa.jp", +"nakai.kanagawa.jp", +"ninomiya.kanagawa.jp", +"odawara.kanagawa.jp", +"oi.kanagawa.jp", +"oiso.kanagawa.jp", +"sagamihara.kanagawa.jp", +"samukawa.kanagawa.jp", +"tsukui.kanagawa.jp", +"yamakita.kanagawa.jp", +"yamato.kanagawa.jp", +"yokosuka.kanagawa.jp", +"yugawara.kanagawa.jp", +"zama.kanagawa.jp", +"zushi.kanagawa.jp", +"aki.kochi.jp", +"geisei.kochi.jp", +"hidaka.kochi.jp", +"higashitsuno.kochi.jp", +"ino.kochi.jp", +"kagami.kochi.jp", +"kami.kochi.jp", +"kitagawa.kochi.jp", +"kochi.kochi.jp", +"mihara.kochi.jp", +"motoyama.kochi.jp", +"muroto.kochi.jp", +"nahari.kochi.jp", +"nakamura.kochi.jp", +"nankoku.kochi.jp", +"nishitosa.kochi.jp", +"niyodogawa.kochi.jp", +"ochi.kochi.jp", +"okawa.kochi.jp", +"otoyo.kochi.jp", +"otsuki.kochi.jp", +"sakawa.kochi.jp", +"sukumo.kochi.jp", +"susaki.kochi.jp", +"tosa.kochi.jp", +"tosashimizu.kochi.jp", +"toyo.kochi.jp", +"tsuno.kochi.jp", +"umaji.kochi.jp", +"yasuda.kochi.jp", +"yusuhara.kochi.jp", +"amakusa.kumamoto.jp", +"arao.kumamoto.jp", +"aso.kumamoto.jp", +"choyo.kumamoto.jp", +"gyokuto.kumamoto.jp", +"kamiamakusa.kumamoto.jp", +"kikuchi.kumamoto.jp", +"kumamoto.kumamoto.jp", +"mashiki.kumamoto.jp", +"mifune.kumamoto.jp", +"minamata.kumamoto.jp", +"minamioguni.kumamoto.jp", +"nagasu.kumamoto.jp", +"nishihara.kumamoto.jp", +"oguni.kumamoto.jp", +"ozu.kumamoto.jp", +"sumoto.kumamoto.jp", +"takamori.kumamoto.jp", +"uki.kumamoto.jp", +"uto.kumamoto.jp", +"yamaga.kumamoto.jp", +"yamato.kumamoto.jp", +"yatsushiro.kumamoto.jp", +"ayabe.kyoto.jp", +"fukuchiyama.kyoto.jp", +"higashiyama.kyoto.jp", +"ide.kyoto.jp", +"ine.kyoto.jp", +"joyo.kyoto.jp", +"kameoka.kyoto.jp", +"kamo.kyoto.jp", +"kita.kyoto.jp", +"kizu.kyoto.jp", +"kumiyama.kyoto.jp", +"kyotamba.kyoto.jp", +"kyotanabe.kyoto.jp", +"kyotango.kyoto.jp", +"maizuru.kyoto.jp", +"minami.kyoto.jp", +"minamiyamashiro.kyoto.jp", +"miyazu.kyoto.jp", +"muko.kyoto.jp", +"nagaokakyo.kyoto.jp", +"nakagyo.kyoto.jp", +"nantan.kyoto.jp", +"oyamazaki.kyoto.jp", +"sakyo.kyoto.jp", +"seika.kyoto.jp", +"tanabe.kyoto.jp", +"uji.kyoto.jp", +"ujitawara.kyoto.jp", +"wazuka.kyoto.jp", +"yamashina.kyoto.jp", +"yawata.kyoto.jp", +"asahi.mie.jp", +"inabe.mie.jp", +"ise.mie.jp", +"kameyama.mie.jp", +"kawagoe.mie.jp", +"kiho.mie.jp", +"kisosaki.mie.jp", +"kiwa.mie.jp", +"komono.mie.jp", +"kumano.mie.jp", +"kuwana.mie.jp", +"matsusaka.mie.jp", +"meiwa.mie.jp", +"mihama.mie.jp", +"minamiise.mie.jp", +"misugi.mie.jp", +"miyama.mie.jp", +"nabari.mie.jp", +"shima.mie.jp", +"suzuka.mie.jp", +"tado.mie.jp", +"taiki.mie.jp", +"taki.mie.jp", +"tamaki.mie.jp", +"toba.mie.jp", +"tsu.mie.jp", +"udono.mie.jp", +"ureshino.mie.jp", +"watarai.mie.jp", +"yokkaichi.mie.jp", +"furukawa.miyagi.jp", +"higashimatsushima.miyagi.jp", +"ishinomaki.miyagi.jp", +"iwanuma.miyagi.jp", +"kakuda.miyagi.jp", +"kami.miyagi.jp", +"kawasaki.miyagi.jp", +"marumori.miyagi.jp", +"matsushima.miyagi.jp", +"minamisanriku.miyagi.jp", +"misato.miyagi.jp", +"murata.miyagi.jp", +"natori.miyagi.jp", +"ogawara.miyagi.jp", +"ohira.miyagi.jp", +"onagawa.miyagi.jp", +"osaki.miyagi.jp", +"rifu.miyagi.jp", +"semine.miyagi.jp", +"shibata.miyagi.jp", +"shichikashuku.miyagi.jp", +"shikama.miyagi.jp", +"shiogama.miyagi.jp", +"shiroishi.miyagi.jp", +"tagajo.miyagi.jp", +"taiwa.miyagi.jp", +"tome.miyagi.jp", +"tomiya.miyagi.jp", +"wakuya.miyagi.jp", +"watari.miyagi.jp", +"yamamoto.miyagi.jp", +"zao.miyagi.jp", +"aya.miyazaki.jp", +"ebino.miyazaki.jp", +"gokase.miyazaki.jp", +"hyuga.miyazaki.jp", +"kadogawa.miyazaki.jp", +"kawaminami.miyazaki.jp", +"kijo.miyazaki.jp", +"kitagawa.miyazaki.jp", +"kitakata.miyazaki.jp", +"kitaura.miyazaki.jp", +"kobayashi.miyazaki.jp", +"kunitomi.miyazaki.jp", +"kushima.miyazaki.jp", +"mimata.miyazaki.jp", +"miyakonojo.miyazaki.jp", +"miyazaki.miyazaki.jp", +"morotsuka.miyazaki.jp", +"nichinan.miyazaki.jp", +"nishimera.miyazaki.jp", +"nobeoka.miyazaki.jp", +"saito.miyazaki.jp", +"shiiba.miyazaki.jp", +"shintomi.miyazaki.jp", +"takaharu.miyazaki.jp", +"takanabe.miyazaki.jp", +"takazaki.miyazaki.jp", +"tsuno.miyazaki.jp", +"achi.nagano.jp", +"agematsu.nagano.jp", +"anan.nagano.jp", +"aoki.nagano.jp", +"asahi.nagano.jp", +"azumino.nagano.jp", +"chikuhoku.nagano.jp", +"chikuma.nagano.jp", +"chino.nagano.jp", +"fujimi.nagano.jp", +"hakuba.nagano.jp", +"hara.nagano.jp", +"hiraya.nagano.jp", +"iida.nagano.jp", +"iijima.nagano.jp", +"iiyama.nagano.jp", +"iizuna.nagano.jp", +"ikeda.nagano.jp", +"ikusaka.nagano.jp", +"ina.nagano.jp", +"karuizawa.nagano.jp", +"kawakami.nagano.jp", +"kiso.nagano.jp", +"kisofukushima.nagano.jp", +"kitaaiki.nagano.jp", +"komagane.nagano.jp", +"komoro.nagano.jp", +"matsukawa.nagano.jp", +"matsumoto.nagano.jp", +"miasa.nagano.jp", +"minamiaiki.nagano.jp", +"minamimaki.nagano.jp", +"minamiminowa.nagano.jp", +"minowa.nagano.jp", +"miyada.nagano.jp", +"miyota.nagano.jp", +"mochizuki.nagano.jp", +"nagano.nagano.jp", +"nagawa.nagano.jp", +"nagiso.nagano.jp", +"nakagawa.nagano.jp", +"nakano.nagano.jp", +"nozawaonsen.nagano.jp", +"obuse.nagano.jp", +"ogawa.nagano.jp", +"okaya.nagano.jp", +"omachi.nagano.jp", +"omi.nagano.jp", +"ookuwa.nagano.jp", +"ooshika.nagano.jp", +"otaki.nagano.jp", +"otari.nagano.jp", +"sakae.nagano.jp", +"sakaki.nagano.jp", +"saku.nagano.jp", +"sakuho.nagano.jp", +"shimosuwa.nagano.jp", +"shinanomachi.nagano.jp", +"shiojiri.nagano.jp", +"suwa.nagano.jp", +"suzaka.nagano.jp", +"takagi.nagano.jp", +"takamori.nagano.jp", +"takayama.nagano.jp", +"tateshina.nagano.jp", +"tatsuno.nagano.jp", +"togakushi.nagano.jp", +"togura.nagano.jp", +"tomi.nagano.jp", +"ueda.nagano.jp", +"wada.nagano.jp", +"yamagata.nagano.jp", +"yamanouchi.nagano.jp", +"yasaka.nagano.jp", +"yasuoka.nagano.jp", +"chijiwa.nagasaki.jp", +"futsu.nagasaki.jp", +"goto.nagasaki.jp", +"hasami.nagasaki.jp", +"hirado.nagasaki.jp", +"iki.nagasaki.jp", +"isahaya.nagasaki.jp", +"kawatana.nagasaki.jp", +"kuchinotsu.nagasaki.jp", +"matsuura.nagasaki.jp", +"nagasaki.nagasaki.jp", +"obama.nagasaki.jp", +"omura.nagasaki.jp", +"oseto.nagasaki.jp", +"saikai.nagasaki.jp", +"sasebo.nagasaki.jp", +"seihi.nagasaki.jp", +"shimabara.nagasaki.jp", +"shinkamigoto.nagasaki.jp", +"togitsu.nagasaki.jp", +"tsushima.nagasaki.jp", +"unzen.nagasaki.jp", +"ando.nara.jp", +"gose.nara.jp", +"heguri.nara.jp", +"higashiyoshino.nara.jp", +"ikaruga.nara.jp", +"ikoma.nara.jp", +"kamikitayama.nara.jp", +"kanmaki.nara.jp", +"kashiba.nara.jp", +"kashihara.nara.jp", +"katsuragi.nara.jp", +"kawai.nara.jp", +"kawakami.nara.jp", +"kawanishi.nara.jp", +"koryo.nara.jp", +"kurotaki.nara.jp", +"mitsue.nara.jp", +"miyake.nara.jp", +"nara.nara.jp", +"nosegawa.nara.jp", +"oji.nara.jp", +"ouda.nara.jp", +"oyodo.nara.jp", +"sakurai.nara.jp", +"sango.nara.jp", +"shimoichi.nara.jp", +"shimokitayama.nara.jp", +"shinjo.nara.jp", +"soni.nara.jp", +"takatori.nara.jp", +"tawaramoto.nara.jp", +"tenkawa.nara.jp", +"tenri.nara.jp", +"uda.nara.jp", +"yamatokoriyama.nara.jp", +"yamatotakada.nara.jp", +"yamazoe.nara.jp", +"yoshino.nara.jp", +"aga.niigata.jp", +"agano.niigata.jp", +"gosen.niigata.jp", +"itoigawa.niigata.jp", +"izumozaki.niigata.jp", +"joetsu.niigata.jp", +"kamo.niigata.jp", +"kariwa.niigata.jp", +"kashiwazaki.niigata.jp", +"minamiuonuma.niigata.jp", +"mitsuke.niigata.jp", +"muika.niigata.jp", +"murakami.niigata.jp", +"myoko.niigata.jp", +"nagaoka.niigata.jp", +"niigata.niigata.jp", +"ojiya.niigata.jp", +"omi.niigata.jp", +"sado.niigata.jp", +"sanjo.niigata.jp", +"seiro.niigata.jp", +"seirou.niigata.jp", +"sekikawa.niigata.jp", +"shibata.niigata.jp", +"tagami.niigata.jp", +"tainai.niigata.jp", +"tochio.niigata.jp", +"tokamachi.niigata.jp", +"tsubame.niigata.jp", +"tsunan.niigata.jp", +"uonuma.niigata.jp", +"yahiko.niigata.jp", +"yoita.niigata.jp", +"yuzawa.niigata.jp", +"beppu.oita.jp", +"bungoono.oita.jp", +"bungotakada.oita.jp", +"hasama.oita.jp", +"hiji.oita.jp", +"himeshima.oita.jp", +"hita.oita.jp", +"kamitsue.oita.jp", +"kokonoe.oita.jp", +"kuju.oita.jp", +"kunisaki.oita.jp", +"kusu.oita.jp", +"oita.oita.jp", +"saiki.oita.jp", +"taketa.oita.jp", +"tsukumi.oita.jp", +"usa.oita.jp", +"usuki.oita.jp", +"yufu.oita.jp", +"akaiwa.okayama.jp", +"asakuchi.okayama.jp", +"bizen.okayama.jp", +"hayashima.okayama.jp", +"ibara.okayama.jp", +"kagamino.okayama.jp", +"kasaoka.okayama.jp", +"kibichuo.okayama.jp", +"kumenan.okayama.jp", +"kurashiki.okayama.jp", +"maniwa.okayama.jp", +"misaki.okayama.jp", +"nagi.okayama.jp", +"niimi.okayama.jp", +"nishiawakura.okayama.jp", +"okayama.okayama.jp", +"satosho.okayama.jp", +"setouchi.okayama.jp", +"shinjo.okayama.jp", +"shoo.okayama.jp", +"soja.okayama.jp", +"takahashi.okayama.jp", +"tamano.okayama.jp", +"tsuyama.okayama.jp", +"wake.okayama.jp", +"yakage.okayama.jp", +"aguni.okinawa.jp", +"ginowan.okinawa.jp", +"ginoza.okinawa.jp", +"gushikami.okinawa.jp", +"haebaru.okinawa.jp", +"higashi.okinawa.jp", +"hirara.okinawa.jp", +"iheya.okinawa.jp", +"ishigaki.okinawa.jp", +"ishikawa.okinawa.jp", +"itoman.okinawa.jp", +"izena.okinawa.jp", +"kadena.okinawa.jp", +"kin.okinawa.jp", +"kitadaito.okinawa.jp", +"kitanakagusuku.okinawa.jp", +"kumejima.okinawa.jp", +"kunigami.okinawa.jp", +"minamidaito.okinawa.jp", +"motobu.okinawa.jp", +"nago.okinawa.jp", +"naha.okinawa.jp", +"nakagusuku.okinawa.jp", +"nakijin.okinawa.jp", +"nanjo.okinawa.jp", +"nishihara.okinawa.jp", +"ogimi.okinawa.jp", +"okinawa.okinawa.jp", +"onna.okinawa.jp", +"shimoji.okinawa.jp", +"taketomi.okinawa.jp", +"tarama.okinawa.jp", +"tokashiki.okinawa.jp", +"tomigusuku.okinawa.jp", +"tonaki.okinawa.jp", +"urasoe.okinawa.jp", +"uruma.okinawa.jp", +"yaese.okinawa.jp", +"yomitan.okinawa.jp", +"yonabaru.okinawa.jp", +"yonaguni.okinawa.jp", +"zamami.okinawa.jp", +"abeno.osaka.jp", +"chihayaakasaka.osaka.jp", +"chuo.osaka.jp", +"daito.osaka.jp", +"fujiidera.osaka.jp", +"habikino.osaka.jp", +"hannan.osaka.jp", +"higashiosaka.osaka.jp", +"higashisumiyoshi.osaka.jp", +"higashiyodogawa.osaka.jp", +"hirakata.osaka.jp", +"ibaraki.osaka.jp", +"ikeda.osaka.jp", +"izumi.osaka.jp", +"izumiotsu.osaka.jp", +"izumisano.osaka.jp", +"kadoma.osaka.jp", +"kaizuka.osaka.jp", +"kanan.osaka.jp", +"kashiwara.osaka.jp", +"katano.osaka.jp", +"kawachinagano.osaka.jp", +"kishiwada.osaka.jp", +"kita.osaka.jp", +"kumatori.osaka.jp", +"matsubara.osaka.jp", +"minato.osaka.jp", +"minoh.osaka.jp", +"misaki.osaka.jp", +"moriguchi.osaka.jp", +"neyagawa.osaka.jp", +"nishi.osaka.jp", +"nose.osaka.jp", +"osakasayama.osaka.jp", +"sakai.osaka.jp", +"sayama.osaka.jp", +"sennan.osaka.jp", +"settsu.osaka.jp", +"shijonawate.osaka.jp", +"shimamoto.osaka.jp", +"suita.osaka.jp", +"tadaoka.osaka.jp", +"taishi.osaka.jp", +"tajiri.osaka.jp", +"takaishi.osaka.jp", +"takatsuki.osaka.jp", +"tondabayashi.osaka.jp", +"toyonaka.osaka.jp", +"toyono.osaka.jp", +"yao.osaka.jp", +"ariake.saga.jp", +"arita.saga.jp", +"fukudomi.saga.jp", +"genkai.saga.jp", +"hamatama.saga.jp", +"hizen.saga.jp", +"imari.saga.jp", +"kamimine.saga.jp", +"kanzaki.saga.jp", +"karatsu.saga.jp", +"kashima.saga.jp", +"kitagata.saga.jp", +"kitahata.saga.jp", +"kiyama.saga.jp", +"kouhoku.saga.jp", +"kyuragi.saga.jp", +"nishiarita.saga.jp", +"ogi.saga.jp", +"omachi.saga.jp", +"ouchi.saga.jp", +"saga.saga.jp", +"shiroishi.saga.jp", +"taku.saga.jp", +"tara.saga.jp", +"tosu.saga.jp", +"yoshinogari.saga.jp", +"arakawa.saitama.jp", +"asaka.saitama.jp", +"chichibu.saitama.jp", +"fujimi.saitama.jp", +"fujimino.saitama.jp", +"fukaya.saitama.jp", +"hanno.saitama.jp", +"hanyu.saitama.jp", +"hasuda.saitama.jp", +"hatogaya.saitama.jp", +"hatoyama.saitama.jp", +"hidaka.saitama.jp", +"higashichichibu.saitama.jp", +"higashimatsuyama.saitama.jp", +"honjo.saitama.jp", +"ina.saitama.jp", +"iruma.saitama.jp", +"iwatsuki.saitama.jp", +"kamiizumi.saitama.jp", +"kamikawa.saitama.jp", +"kamisato.saitama.jp", +"kasukabe.saitama.jp", +"kawagoe.saitama.jp", +"kawaguchi.saitama.jp", +"kawajima.saitama.jp", +"kazo.saitama.jp", +"kitamoto.saitama.jp", +"koshigaya.saitama.jp", +"kounosu.saitama.jp", +"kuki.saitama.jp", +"kumagaya.saitama.jp", +"matsubushi.saitama.jp", +"minano.saitama.jp", +"misato.saitama.jp", +"miyashiro.saitama.jp", +"miyoshi.saitama.jp", +"moroyama.saitama.jp", +"nagatoro.saitama.jp", +"namegawa.saitama.jp", +"niiza.saitama.jp", +"ogano.saitama.jp", +"ogawa.saitama.jp", +"ogose.saitama.jp", +"okegawa.saitama.jp", +"omiya.saitama.jp", +"otaki.saitama.jp", +"ranzan.saitama.jp", +"ryokami.saitama.jp", +"saitama.saitama.jp", +"sakado.saitama.jp", +"satte.saitama.jp", +"sayama.saitama.jp", +"shiki.saitama.jp", +"shiraoka.saitama.jp", +"soka.saitama.jp", +"sugito.saitama.jp", +"toda.saitama.jp", +"tokigawa.saitama.jp", +"tokorozawa.saitama.jp", +"tsurugashima.saitama.jp", +"urawa.saitama.jp", +"warabi.saitama.jp", +"yashio.saitama.jp", +"yokoze.saitama.jp", +"yono.saitama.jp", +"yorii.saitama.jp", +"yoshida.saitama.jp", +"yoshikawa.saitama.jp", +"yoshimi.saitama.jp", +"aisho.shiga.jp", +"gamo.shiga.jp", +"higashiomi.shiga.jp", +"hikone.shiga.jp", +"koka.shiga.jp", +"konan.shiga.jp", +"kosei.shiga.jp", +"koto.shiga.jp", +"kusatsu.shiga.jp", +"maibara.shiga.jp", +"moriyama.shiga.jp", +"nagahama.shiga.jp", +"nishiazai.shiga.jp", +"notogawa.shiga.jp", +"omihachiman.shiga.jp", +"otsu.shiga.jp", +"ritto.shiga.jp", +"ryuoh.shiga.jp", +"takashima.shiga.jp", +"takatsuki.shiga.jp", +"torahime.shiga.jp", +"toyosato.shiga.jp", +"yasu.shiga.jp", +"akagi.shimane.jp", +"ama.shimane.jp", +"gotsu.shimane.jp", +"hamada.shimane.jp", +"higashiizumo.shimane.jp", +"hikawa.shimane.jp", +"hikimi.shimane.jp", +"izumo.shimane.jp", +"kakinoki.shimane.jp", +"masuda.shimane.jp", +"matsue.shimane.jp", +"misato.shimane.jp", +"nishinoshima.shimane.jp", +"ohda.shimane.jp", +"okinoshima.shimane.jp", +"okuizumo.shimane.jp", +"shimane.shimane.jp", +"tamayu.shimane.jp", +"tsuwano.shimane.jp", +"unnan.shimane.jp", +"yakumo.shimane.jp", +"yasugi.shimane.jp", +"yatsuka.shimane.jp", +"arai.shizuoka.jp", +"atami.shizuoka.jp", +"fuji.shizuoka.jp", +"fujieda.shizuoka.jp", +"fujikawa.shizuoka.jp", +"fujinomiya.shizuoka.jp", +"fukuroi.shizuoka.jp", +"gotemba.shizuoka.jp", +"haibara.shizuoka.jp", +"hamamatsu.shizuoka.jp", +"higashiizu.shizuoka.jp", +"ito.shizuoka.jp", +"iwata.shizuoka.jp", +"izu.shizuoka.jp", +"izunokuni.shizuoka.jp", +"kakegawa.shizuoka.jp", +"kannami.shizuoka.jp", +"kawanehon.shizuoka.jp", +"kawazu.shizuoka.jp", +"kikugawa.shizuoka.jp", +"kosai.shizuoka.jp", +"makinohara.shizuoka.jp", +"matsuzaki.shizuoka.jp", +"minamiizu.shizuoka.jp", +"mishima.shizuoka.jp", +"morimachi.shizuoka.jp", +"nishiizu.shizuoka.jp", +"numazu.shizuoka.jp", +"omaezaki.shizuoka.jp", +"shimada.shizuoka.jp", +"shimizu.shizuoka.jp", +"shimoda.shizuoka.jp", +"shizuoka.shizuoka.jp", +"susono.shizuoka.jp", +"yaizu.shizuoka.jp", +"yoshida.shizuoka.jp", +"ashikaga.tochigi.jp", +"bato.tochigi.jp", +"haga.tochigi.jp", +"ichikai.tochigi.jp", +"iwafune.tochigi.jp", +"kaminokawa.tochigi.jp", +"kanuma.tochigi.jp", +"karasuyama.tochigi.jp", +"kuroiso.tochigi.jp", +"mashiko.tochigi.jp", +"mibu.tochigi.jp", +"moka.tochigi.jp", +"motegi.tochigi.jp", +"nasu.tochigi.jp", +"nasushiobara.tochigi.jp", +"nikko.tochigi.jp", +"nishikata.tochigi.jp", +"nogi.tochigi.jp", +"ohira.tochigi.jp", +"ohtawara.tochigi.jp", +"oyama.tochigi.jp", +"sakura.tochigi.jp", +"sano.tochigi.jp", +"shimotsuke.tochigi.jp", +"shioya.tochigi.jp", +"takanezawa.tochigi.jp", +"tochigi.tochigi.jp", +"tsuga.tochigi.jp", +"ujiie.tochigi.jp", +"utsunomiya.tochigi.jp", +"yaita.tochigi.jp", +"aizumi.tokushima.jp", +"anan.tokushima.jp", +"ichiba.tokushima.jp", +"itano.tokushima.jp", +"kainan.tokushima.jp", +"komatsushima.tokushima.jp", +"matsushige.tokushima.jp", +"mima.tokushima.jp", +"minami.tokushima.jp", +"miyoshi.tokushima.jp", +"mugi.tokushima.jp", +"nakagawa.tokushima.jp", +"naruto.tokushima.jp", +"sanagochi.tokushima.jp", +"shishikui.tokushima.jp", +"tokushima.tokushima.jp", +"wajiki.tokushima.jp", +"adachi.tokyo.jp", +"akiruno.tokyo.jp", +"akishima.tokyo.jp", +"aogashima.tokyo.jp", +"arakawa.tokyo.jp", +"bunkyo.tokyo.jp", +"chiyoda.tokyo.jp", +"chofu.tokyo.jp", +"chuo.tokyo.jp", +"edogawa.tokyo.jp", +"fuchu.tokyo.jp", +"fussa.tokyo.jp", +"hachijo.tokyo.jp", +"hachioji.tokyo.jp", +"hamura.tokyo.jp", +"higashikurume.tokyo.jp", +"higashimurayama.tokyo.jp", +"higashiyamato.tokyo.jp", +"hino.tokyo.jp", +"hinode.tokyo.jp", +"hinohara.tokyo.jp", +"inagi.tokyo.jp", +"itabashi.tokyo.jp", +"katsushika.tokyo.jp", +"kita.tokyo.jp", +"kiyose.tokyo.jp", +"kodaira.tokyo.jp", +"koganei.tokyo.jp", +"kokubunji.tokyo.jp", +"komae.tokyo.jp", +"koto.tokyo.jp", +"kouzushima.tokyo.jp", +"kunitachi.tokyo.jp", +"machida.tokyo.jp", +"meguro.tokyo.jp", +"minato.tokyo.jp", +"mitaka.tokyo.jp", +"mizuho.tokyo.jp", +"musashimurayama.tokyo.jp", +"musashino.tokyo.jp", +"nakano.tokyo.jp", +"nerima.tokyo.jp", +"ogasawara.tokyo.jp", +"okutama.tokyo.jp", +"ome.tokyo.jp", +"oshima.tokyo.jp", +"ota.tokyo.jp", +"setagaya.tokyo.jp", +"shibuya.tokyo.jp", +"shinagawa.tokyo.jp", +"shinjuku.tokyo.jp", +"suginami.tokyo.jp", +"sumida.tokyo.jp", +"tachikawa.tokyo.jp", +"taito.tokyo.jp", +"tama.tokyo.jp", +"toshima.tokyo.jp", +"chizu.tottori.jp", +"hino.tottori.jp", +"kawahara.tottori.jp", +"koge.tottori.jp", +"kotoura.tottori.jp", +"misasa.tottori.jp", +"nanbu.tottori.jp", +"nichinan.tottori.jp", +"sakaiminato.tottori.jp", +"tottori.tottori.jp", +"wakasa.tottori.jp", +"yazu.tottori.jp", +"yonago.tottori.jp", +"asahi.toyama.jp", +"fuchu.toyama.jp", +"fukumitsu.toyama.jp", +"funahashi.toyama.jp", +"himi.toyama.jp", +"imizu.toyama.jp", +"inami.toyama.jp", +"johana.toyama.jp", +"kamiichi.toyama.jp", +"kurobe.toyama.jp", +"nakaniikawa.toyama.jp", +"namerikawa.toyama.jp", +"nanto.toyama.jp", +"nyuzen.toyama.jp", +"oyabe.toyama.jp", +"taira.toyama.jp", +"takaoka.toyama.jp", +"tateyama.toyama.jp", +"toga.toyama.jp", +"tonami.toyama.jp", +"toyama.toyama.jp", +"unazuki.toyama.jp", +"uozu.toyama.jp", +"yamada.toyama.jp", +"arida.wakayama.jp", +"aridagawa.wakayama.jp", +"gobo.wakayama.jp", +"hashimoto.wakayama.jp", +"hidaka.wakayama.jp", +"hirogawa.wakayama.jp", +"inami.wakayama.jp", +"iwade.wakayama.jp", +"kainan.wakayama.jp", +"kamitonda.wakayama.jp", +"katsuragi.wakayama.jp", +"kimino.wakayama.jp", +"kinokawa.wakayama.jp", +"kitayama.wakayama.jp", +"koya.wakayama.jp", +"koza.wakayama.jp", +"kozagawa.wakayama.jp", +"kudoyama.wakayama.jp", +"kushimoto.wakayama.jp", +"mihama.wakayama.jp", +"misato.wakayama.jp", +"nachikatsuura.wakayama.jp", +"shingu.wakayama.jp", +"shirahama.wakayama.jp", +"taiji.wakayama.jp", +"tanabe.wakayama.jp", +"wakayama.wakayama.jp", +"yuasa.wakayama.jp", +"yura.wakayama.jp", +"asahi.yamagata.jp", +"funagata.yamagata.jp", +"higashine.yamagata.jp", +"iide.yamagata.jp", +"kahoku.yamagata.jp", +"kaminoyama.yamagata.jp", +"kaneyama.yamagata.jp", +"kawanishi.yamagata.jp", +"mamurogawa.yamagata.jp", +"mikawa.yamagata.jp", +"murayama.yamagata.jp", +"nagai.yamagata.jp", +"nakayama.yamagata.jp", +"nanyo.yamagata.jp", +"nishikawa.yamagata.jp", +"obanazawa.yamagata.jp", +"oe.yamagata.jp", +"oguni.yamagata.jp", +"ohkura.yamagata.jp", +"oishida.yamagata.jp", +"sagae.yamagata.jp", +"sakata.yamagata.jp", +"sakegawa.yamagata.jp", +"shinjo.yamagata.jp", +"shirataka.yamagata.jp", +"shonai.yamagata.jp", +"takahata.yamagata.jp", +"tendo.yamagata.jp", +"tozawa.yamagata.jp", +"tsuruoka.yamagata.jp", +"yamagata.yamagata.jp", +"yamanobe.yamagata.jp", +"yonezawa.yamagata.jp", +"yuza.yamagata.jp", +"abu.yamaguchi.jp", +"hagi.yamaguchi.jp", +"hikari.yamaguchi.jp", +"hofu.yamaguchi.jp", +"iwakuni.yamaguchi.jp", +"kudamatsu.yamaguchi.jp", +"mitou.yamaguchi.jp", +"nagato.yamaguchi.jp", +"oshima.yamaguchi.jp", +"shimonoseki.yamaguchi.jp", +"shunan.yamaguchi.jp", +"tabuse.yamaguchi.jp", +"tokuyama.yamaguchi.jp", +"toyota.yamaguchi.jp", +"ube.yamaguchi.jp", +"yuu.yamaguchi.jp", +"chuo.yamanashi.jp", +"doshi.yamanashi.jp", +"fuefuki.yamanashi.jp", +"fujikawa.yamanashi.jp", +"fujikawaguchiko.yamanashi.jp", +"fujiyoshida.yamanashi.jp", +"hayakawa.yamanashi.jp", +"hokuto.yamanashi.jp", +"ichikawamisato.yamanashi.jp", +"kai.yamanashi.jp", +"kofu.yamanashi.jp", +"koshu.yamanashi.jp", +"kosuge.yamanashi.jp", +"minami-alps.yamanashi.jp", +"minobu.yamanashi.jp", +"nakamichi.yamanashi.jp", +"nanbu.yamanashi.jp", +"narusawa.yamanashi.jp", +"nirasaki.yamanashi.jp", +"nishikatsura.yamanashi.jp", +"oshino.yamanashi.jp", +"otsuki.yamanashi.jp", +"showa.yamanashi.jp", +"tabayama.yamanashi.jp", +"tsuru.yamanashi.jp", +"uenohara.yamanashi.jp", +"yamanakako.yamanashi.jp", +"yamanashi.yamanashi.jp", +"ke", +"ac.ke", +"co.ke", +"go.ke", +"info.ke", +"me.ke", +"mobi.ke", +"ne.ke", +"or.ke", +"sc.ke", +"kg", +"org.kg", +"net.kg", +"com.kg", +"edu.kg", +"gov.kg", +"mil.kg", +"*.kh", +"ki", +"edu.ki", +"biz.ki", +"net.ki", +"org.ki", +"gov.ki", +"info.ki", +"com.ki", +"km", +"org.km", +"nom.km", +"gov.km", +"prd.km", +"tm.km", +"edu.km", +"mil.km", +"ass.km", +"com.km", +"coop.km", +"asso.km", +"presse.km", +"medecin.km", +"notaires.km", +"pharmaciens.km", +"veterinaire.km", +"gouv.km", +"kn", +"net.kn", +"org.kn", +"edu.kn", +"gov.kn", +"kp", +"com.kp", +"edu.kp", +"gov.kp", +"org.kp", +"rep.kp", +"tra.kp", +"kr", +"ac.kr", +"co.kr", +"es.kr", +"go.kr", +"hs.kr", +"kg.kr", +"mil.kr", +"ms.kr", +"ne.kr", +"or.kr", +"pe.kr", +"re.kr", +"sc.kr", +"busan.kr", +"chungbuk.kr", +"chungnam.kr", +"daegu.kr", +"daejeon.kr", +"gangwon.kr", +"gwangju.kr", +"gyeongbuk.kr", +"gyeonggi.kr", +"gyeongnam.kr", +"incheon.kr", +"jeju.kr", +"jeonbuk.kr", +"jeonnam.kr", +"seoul.kr", +"ulsan.kr", +"kw", +"com.kw", +"edu.kw", +"emb.kw", +"gov.kw", +"ind.kw", +"net.kw", +"org.kw", +"ky", +"edu.ky", +"gov.ky", +"com.ky", +"org.ky", +"net.ky", +"kz", +"org.kz", +"edu.kz", +"net.kz", +"gov.kz", +"mil.kz", +"com.kz", +"la", +"int.la", +"net.la", +"info.la", +"edu.la", +"gov.la", +"per.la", +"com.la", +"org.la", +"lb", +"com.lb", +"edu.lb", +"gov.lb", +"net.lb", +"org.lb", +"lc", +"com.lc", +"net.lc", +"co.lc", +"org.lc", +"edu.lc", +"gov.lc", +"li", +"lk", +"gov.lk", +"sch.lk", +"net.lk", +"int.lk", +"com.lk", +"org.lk", +"edu.lk", +"ngo.lk", +"soc.lk", +"web.lk", +"ltd.lk", +"assn.lk", +"grp.lk", +"hotel.lk", +"ac.lk", +"lr", +"com.lr", +"edu.lr", +"gov.lr", +"org.lr", +"net.lr", +"ls", +"ac.ls", +"biz.ls", +"co.ls", +"edu.ls", +"gov.ls", +"info.ls", +"net.ls", +"org.ls", +"sc.ls", +"lt", +"gov.lt", +"lu", +"lv", +"com.lv", +"edu.lv", +"gov.lv", +"org.lv", +"mil.lv", +"id.lv", +"net.lv", +"asn.lv", +"conf.lv", +"ly", +"com.ly", +"net.ly", +"gov.ly", +"plc.ly", +"edu.ly", +"sch.ly", +"med.ly", +"org.ly", +"id.ly", +"ma", +"co.ma", +"net.ma", +"gov.ma", +"org.ma", +"ac.ma", +"press.ma", +"mc", +"tm.mc", +"asso.mc", +"md", +"me", +"co.me", +"net.me", +"org.me", +"edu.me", +"ac.me", +"gov.me", +"its.me", +"priv.me", +"mg", +"org.mg", +"nom.mg", +"gov.mg", +"prd.mg", +"tm.mg", +"edu.mg", +"mil.mg", +"com.mg", +"co.mg", +"mh", +"mil", +"mk", +"com.mk", +"org.mk", +"net.mk", +"edu.mk", +"gov.mk", +"inf.mk", +"name.mk", +"ml", +"com.ml", +"edu.ml", +"gouv.ml", +"gov.ml", +"net.ml", +"org.ml", +"presse.ml", +"*.mm", +"mn", +"gov.mn", +"edu.mn", +"org.mn", +"mo", +"com.mo", +"net.mo", +"org.mo", +"edu.mo", +"gov.mo", +"mobi", +"mp", +"mq", +"mr", +"gov.mr", +"ms", +"com.ms", +"edu.ms", +"gov.ms", +"net.ms", +"org.ms", +"mt", +"com.mt", +"edu.mt", +"net.mt", +"org.mt", +"mu", +"com.mu", +"net.mu", +"org.mu", +"gov.mu", +"ac.mu", +"co.mu", +"or.mu", +"museum", +"academy.museum", +"agriculture.museum", +"air.museum", +"airguard.museum", +"alabama.museum", +"alaska.museum", +"amber.museum", +"ambulance.museum", +"american.museum", +"americana.museum", +"americanantiques.museum", +"americanart.museum", +"amsterdam.museum", +"and.museum", +"annefrank.museum", +"anthro.museum", +"anthropology.museum", +"antiques.museum", +"aquarium.museum", +"arboretum.museum", +"archaeological.museum", +"archaeology.museum", +"architecture.museum", +"art.museum", +"artanddesign.museum", +"artcenter.museum", +"artdeco.museum", +"arteducation.museum", +"artgallery.museum", +"arts.museum", +"artsandcrafts.museum", +"asmatart.museum", +"assassination.museum", +"assisi.museum", +"association.museum", +"astronomy.museum", +"atlanta.museum", +"austin.museum", +"australia.museum", +"automotive.museum", +"aviation.museum", +"axis.museum", +"badajoz.museum", +"baghdad.museum", +"bahn.museum", +"bale.museum", +"baltimore.museum", +"barcelona.museum", +"baseball.museum", +"basel.museum", +"baths.museum", +"bauern.museum", +"beauxarts.museum", +"beeldengeluid.museum", +"bellevue.museum", +"bergbau.museum", +"berkeley.museum", +"berlin.museum", +"bern.museum", +"bible.museum", +"bilbao.museum", +"bill.museum", +"birdart.museum", +"birthplace.museum", +"bonn.museum", +"boston.museum", +"botanical.museum", +"botanicalgarden.museum", +"botanicgarden.museum", +"botany.museum", +"brandywinevalley.museum", +"brasil.museum", +"bristol.museum", +"british.museum", +"britishcolumbia.museum", +"broadcast.museum", +"brunel.museum", +"brussel.museum", +"brussels.museum", +"bruxelles.museum", +"building.museum", +"burghof.museum", +"bus.museum", +"bushey.museum", +"cadaques.museum", +"california.museum", +"cambridge.museum", +"can.museum", +"canada.museum", +"capebreton.museum", +"carrier.museum", +"cartoonart.museum", +"casadelamoneda.museum", +"castle.museum", +"castres.museum", +"celtic.museum", +"center.museum", +"chattanooga.museum", +"cheltenham.museum", +"chesapeakebay.museum", +"chicago.museum", +"children.museum", +"childrens.museum", +"childrensgarden.museum", +"chiropractic.museum", +"chocolate.museum", +"christiansburg.museum", +"cincinnati.museum", +"cinema.museum", +"circus.museum", +"civilisation.museum", +"civilization.museum", +"civilwar.museum", +"clinton.museum", +"clock.museum", +"coal.museum", +"coastaldefence.museum", +"cody.museum", +"coldwar.museum", +"collection.museum", +"colonialwilliamsburg.museum", +"coloradoplateau.museum", +"columbia.museum", +"columbus.museum", +"communication.museum", +"communications.museum", +"community.museum", +"computer.museum", +"computerhistory.museum", +"comunicações.museum", +"contemporary.museum", +"contemporaryart.museum", +"convent.museum", +"copenhagen.museum", +"corporation.museum", +"correios-e-telecomunicações.museum", +"corvette.museum", +"costume.museum", +"countryestate.museum", +"county.museum", +"crafts.museum", +"cranbrook.museum", +"creation.museum", +"cultural.museum", +"culturalcenter.museum", +"culture.museum", +"cyber.museum", +"cymru.museum", +"dali.museum", +"dallas.museum", +"database.museum", +"ddr.museum", +"decorativearts.museum", +"delaware.museum", +"delmenhorst.museum", +"denmark.museum", +"depot.museum", +"design.museum", +"detroit.museum", +"dinosaur.museum", +"discovery.museum", +"dolls.museum", +"donostia.museum", +"durham.museum", +"eastafrica.museum", +"eastcoast.museum", +"education.museum", +"educational.museum", +"egyptian.museum", +"eisenbahn.museum", +"elburg.museum", +"elvendrell.museum", +"embroidery.museum", +"encyclopedic.museum", +"england.museum", +"entomology.museum", +"environment.museum", +"environmentalconservation.museum", +"epilepsy.museum", +"essex.museum", +"estate.museum", +"ethnology.museum", +"exeter.museum", +"exhibition.museum", +"family.museum", +"farm.museum", +"farmequipment.museum", +"farmers.museum", +"farmstead.museum", +"field.museum", +"figueres.museum", +"filatelia.museum", +"film.museum", +"fineart.museum", +"finearts.museum", +"finland.museum", +"flanders.museum", +"florida.museum", +"force.museum", +"fortmissoula.museum", +"fortworth.museum", +"foundation.museum", +"francaise.museum", +"frankfurt.museum", +"franziskaner.museum", +"freemasonry.museum", +"freiburg.museum", +"fribourg.museum", +"frog.museum", +"fundacio.museum", +"furniture.museum", +"gallery.museum", +"garden.museum", +"gateway.museum", +"geelvinck.museum", +"gemological.museum", +"geology.museum", +"georgia.museum", +"giessen.museum", +"glas.museum", +"glass.museum", +"gorge.museum", +"grandrapids.museum", +"graz.museum", +"guernsey.museum", +"halloffame.museum", +"hamburg.museum", +"handson.museum", +"harvestcelebration.museum", +"hawaii.museum", +"health.museum", +"heimatunduhren.museum", +"hellas.museum", +"helsinki.museum", +"hembygdsforbund.museum", +"heritage.museum", +"histoire.museum", +"historical.museum", +"historicalsociety.museum", +"historichouses.museum", +"historisch.museum", +"historisches.museum", +"history.museum", +"historyofscience.museum", +"horology.museum", +"house.museum", +"humanities.museum", +"illustration.museum", +"imageandsound.museum", +"indian.museum", +"indiana.museum", +"indianapolis.museum", +"indianmarket.museum", +"intelligence.museum", +"interactive.museum", +"iraq.museum", +"iron.museum", +"isleofman.museum", +"jamison.museum", +"jefferson.museum", +"jerusalem.museum", +"jewelry.museum", +"jewish.museum", +"jewishart.museum", +"jfk.museum", +"journalism.museum", +"judaica.museum", +"judygarland.museum", +"juedisches.museum", +"juif.museum", +"karate.museum", +"karikatur.museum", +"kids.museum", +"koebenhavn.museum", +"koeln.museum", +"kunst.museum", +"kunstsammlung.museum", +"kunstunddesign.museum", +"labor.museum", +"labour.museum", +"lajolla.museum", +"lancashire.museum", +"landes.museum", +"lans.museum", +"läns.museum", +"larsson.museum", +"lewismiller.museum", +"lincoln.museum", +"linz.museum", +"living.museum", +"livinghistory.museum", +"localhistory.museum", +"london.museum", +"losangeles.museum", +"louvre.museum", +"loyalist.museum", +"lucerne.museum", +"luxembourg.museum", +"luzern.museum", +"mad.museum", +"madrid.museum", +"mallorca.museum", +"manchester.museum", +"mansion.museum", +"mansions.museum", +"manx.museum", +"marburg.museum", +"maritime.museum", +"maritimo.museum", +"maryland.museum", +"marylhurst.museum", +"media.museum", +"medical.museum", +"medizinhistorisches.museum", +"meeres.museum", +"memorial.museum", +"mesaverde.museum", +"michigan.museum", +"midatlantic.museum", +"military.museum", +"mill.museum", +"miners.museum", +"mining.museum", +"minnesota.museum", +"missile.museum", +"missoula.museum", +"modern.museum", +"moma.museum", +"money.museum", +"monmouth.museum", +"monticello.museum", +"montreal.museum", +"moscow.museum", +"motorcycle.museum", +"muenchen.museum", +"muenster.museum", +"mulhouse.museum", +"muncie.museum", +"museet.museum", +"museumcenter.museum", +"museumvereniging.museum", +"music.museum", +"national.museum", +"nationalfirearms.museum", +"nationalheritage.museum", +"nativeamerican.museum", +"naturalhistory.museum", +"naturalhistorymuseum.museum", +"naturalsciences.museum", +"nature.museum", +"naturhistorisches.museum", +"natuurwetenschappen.museum", +"naumburg.museum", +"naval.museum", +"nebraska.museum", +"neues.museum", +"newhampshire.museum", +"newjersey.museum", +"newmexico.museum", +"newport.museum", +"newspaper.museum", +"newyork.museum", +"niepce.museum", +"norfolk.museum", +"north.museum", +"nrw.museum", +"nyc.museum", +"nyny.museum", +"oceanographic.museum", +"oceanographique.museum", +"omaha.museum", +"online.museum", +"ontario.museum", +"openair.museum", +"oregon.museum", +"oregontrail.museum", +"otago.museum", +"oxford.museum", +"pacific.museum", +"paderborn.museum", +"palace.museum", +"paleo.museum", +"palmsprings.museum", +"panama.museum", +"paris.museum", +"pasadena.museum", +"pharmacy.museum", +"philadelphia.museum", +"philadelphiaarea.museum", +"philately.museum", +"phoenix.museum", +"photography.museum", +"pilots.museum", +"pittsburgh.museum", +"planetarium.museum", +"plantation.museum", +"plants.museum", +"plaza.museum", +"portal.museum", +"portland.museum", +"portlligat.museum", +"posts-and-telecommunications.museum", +"preservation.museum", +"presidio.museum", +"press.museum", +"project.museum", +"public.museum", +"pubol.museum", +"quebec.museum", +"railroad.museum", +"railway.museum", +"research.museum", +"resistance.museum", +"riodejaneiro.museum", +"rochester.museum", +"rockart.museum", +"roma.museum", +"russia.museum", +"saintlouis.museum", +"salem.museum", +"salvadordali.museum", +"salzburg.museum", +"sandiego.museum", +"sanfrancisco.museum", +"santabarbara.museum", +"santacruz.museum", +"santafe.museum", +"saskatchewan.museum", +"satx.museum", +"savannahga.museum", +"schlesisches.museum", +"schoenbrunn.museum", +"schokoladen.museum", +"school.museum", +"schweiz.museum", +"science.museum", +"scienceandhistory.museum", +"scienceandindustry.museum", +"sciencecenter.museum", +"sciencecenters.museum", +"science-fiction.museum", +"sciencehistory.museum", +"sciences.museum", +"sciencesnaturelles.museum", +"scotland.museum", +"seaport.museum", +"settlement.museum", +"settlers.museum", +"shell.museum", +"sherbrooke.museum", +"sibenik.museum", +"silk.museum", +"ski.museum", +"skole.museum", +"society.museum", +"sologne.museum", +"soundandvision.museum", +"southcarolina.museum", +"southwest.museum", +"space.museum", +"spy.museum", +"square.museum", +"stadt.museum", +"stalbans.museum", +"starnberg.museum", +"state.museum", +"stateofdelaware.museum", +"station.museum", +"steam.museum", +"steiermark.museum", +"stjohn.museum", +"stockholm.museum", +"stpetersburg.museum", +"stuttgart.museum", +"suisse.museum", +"surgeonshall.museum", +"surrey.museum", +"svizzera.museum", +"sweden.museum", +"sydney.museum", +"tank.museum", +"tcm.museum", +"technology.museum", +"telekommunikation.museum", +"television.museum", +"texas.museum", +"textile.museum", +"theater.museum", +"time.museum", +"timekeeping.museum", +"topology.museum", +"torino.museum", +"touch.museum", +"town.museum", +"transport.museum", +"tree.museum", +"trolley.museum", +"trust.museum", +"trustee.museum", +"uhren.museum", +"ulm.museum", +"undersea.museum", +"university.museum", +"usa.museum", +"usantiques.museum", +"usarts.museum", +"uscountryestate.museum", +"usculture.museum", +"usdecorativearts.museum", +"usgarden.museum", +"ushistory.museum", +"ushuaia.museum", +"uslivinghistory.museum", +"utah.museum", +"uvic.museum", +"valley.museum", +"vantaa.museum", +"versailles.museum", +"viking.museum", +"village.museum", +"virginia.museum", +"virtual.museum", +"virtuel.museum", +"vlaanderen.museum", +"volkenkunde.museum", +"wales.museum", +"wallonie.museum", +"war.museum", +"washingtondc.museum", +"watchandclock.museum", +"watch-and-clock.museum", +"western.museum", +"westfalen.museum", +"whaling.museum", +"wildlife.museum", +"williamsburg.museum", +"windmill.museum", +"workshop.museum", +"york.museum", +"yorkshire.museum", +"yosemite.museum", +"youth.museum", +"zoological.museum", +"zoology.museum", +"ירושלים.museum", +"иком.museum", +"mv", +"aero.mv", +"biz.mv", +"com.mv", +"coop.mv", +"edu.mv", +"gov.mv", +"info.mv", +"int.mv", +"mil.mv", +"museum.mv", +"name.mv", +"net.mv", +"org.mv", +"pro.mv", +"mw", +"ac.mw", +"biz.mw", +"co.mw", +"com.mw", +"coop.mw", +"edu.mw", +"gov.mw", +"int.mw", +"museum.mw", +"net.mw", +"org.mw", +"mx", +"com.mx", +"org.mx", +"gob.mx", +"edu.mx", +"net.mx", +"my", +"com.my", +"net.my", +"org.my", +"gov.my", +"edu.my", +"mil.my", +"name.my", +"mz", +"ac.mz", +"adv.mz", +"co.mz", +"edu.mz", +"gov.mz", +"mil.mz", +"net.mz", +"org.mz", +"na", +"info.na", +"pro.na", +"name.na", +"school.na", +"or.na", +"dr.na", +"us.na", +"mx.na", +"ca.na", +"in.na", +"cc.na", +"tv.na", +"ws.na", +"mobi.na", +"co.na", +"com.na", +"org.na", +"name", +"nc", +"asso.nc", +"nom.nc", +"ne", +"net", +"nf", +"com.nf", +"net.nf", +"per.nf", +"rec.nf", +"web.nf", +"arts.nf", +"firm.nf", +"info.nf", +"other.nf", +"store.nf", +"ng", +"com.ng", +"edu.ng", +"gov.ng", +"i.ng", +"mil.ng", +"mobi.ng", +"name.ng", +"net.ng", +"org.ng", +"sch.ng", +"ni", +"ac.ni", +"biz.ni", +"co.ni", +"com.ni", +"edu.ni", +"gob.ni", +"in.ni", +"info.ni", +"int.ni", +"mil.ni", +"net.ni", +"nom.ni", +"org.ni", +"web.ni", +"nl", +"no", +"fhs.no", +"vgs.no", +"fylkesbibl.no", +"folkebibl.no", +"museum.no", +"idrett.no", +"priv.no", +"mil.no", +"stat.no", +"dep.no", +"kommune.no", +"herad.no", +"aa.no", +"ah.no", +"bu.no", +"fm.no", +"hl.no", +"hm.no", +"jan-mayen.no", +"mr.no", +"nl.no", +"nt.no", +"of.no", +"ol.no", +"oslo.no", +"rl.no", +"sf.no", +"st.no", +"svalbard.no", +"tm.no", +"tr.no", +"va.no", +"vf.no", +"gs.aa.no", +"gs.ah.no", +"gs.bu.no", +"gs.fm.no", +"gs.hl.no", +"gs.hm.no", +"gs.jan-mayen.no", +"gs.mr.no", +"gs.nl.no", +"gs.nt.no", +"gs.of.no", +"gs.ol.no", +"gs.oslo.no", +"gs.rl.no", +"gs.sf.no", +"gs.st.no", +"gs.svalbard.no", +"gs.tm.no", +"gs.tr.no", +"gs.va.no", +"gs.vf.no", +"akrehamn.no", +"åkrehamn.no", +"algard.no", +"ålgård.no", +"arna.no", +"brumunddal.no", +"bryne.no", +"bronnoysund.no", +"brønnøysund.no", +"drobak.no", +"drøbak.no", +"egersund.no", +"fetsund.no", +"floro.no", +"florø.no", +"fredrikstad.no", +"hokksund.no", +"honefoss.no", +"hønefoss.no", +"jessheim.no", +"jorpeland.no", +"jørpeland.no", +"kirkenes.no", +"kopervik.no", +"krokstadelva.no", +"langevag.no", +"langevåg.no", +"leirvik.no", +"mjondalen.no", +"mjøndalen.no", +"mo-i-rana.no", +"mosjoen.no", +"mosjøen.no", +"nesoddtangen.no", +"orkanger.no", +"osoyro.no", +"osøyro.no", +"raholt.no", +"råholt.no", +"sandnessjoen.no", +"sandnessjøen.no", +"skedsmokorset.no", +"slattum.no", +"spjelkavik.no", +"stathelle.no", +"stavern.no", +"stjordalshalsen.no", +"stjørdalshalsen.no", +"tananger.no", +"tranby.no", +"vossevangen.no", +"afjord.no", +"åfjord.no", +"agdenes.no", +"al.no", +"ål.no", +"alesund.no", +"ålesund.no", +"alstahaug.no", +"alta.no", +"áltá.no", +"alaheadju.no", +"álaheadju.no", +"alvdal.no", +"amli.no", +"åmli.no", +"amot.no", +"åmot.no", +"andebu.no", +"andoy.no", +"andøy.no", +"andasuolo.no", +"ardal.no", +"årdal.no", +"aremark.no", +"arendal.no", +"ås.no", +"aseral.no", +"åseral.no", +"asker.no", +"askim.no", +"askvoll.no", +"askoy.no", +"askøy.no", +"asnes.no", +"åsnes.no", +"audnedaln.no", +"aukra.no", +"aure.no", +"aurland.no", +"aurskog-holand.no", +"aurskog-høland.no", +"austevoll.no", +"austrheim.no", +"averoy.no", +"averøy.no", +"balestrand.no", +"ballangen.no", +"balat.no", +"bálát.no", +"balsfjord.no", +"bahccavuotna.no", +"báhccavuotna.no", +"bamble.no", +"bardu.no", +"beardu.no", +"beiarn.no", +"bajddar.no", +"bájddar.no", +"baidar.no", +"báidár.no", +"berg.no", +"bergen.no", +"berlevag.no", +"berlevåg.no", +"bearalvahki.no", +"bearalváhki.no", +"bindal.no", +"birkenes.no", +"bjarkoy.no", +"bjarkøy.no", +"bjerkreim.no", +"bjugn.no", +"bodo.no", +"bodø.no", +"badaddja.no", +"bådåddjå.no", +"budejju.no", +"bokn.no", +"bremanger.no", +"bronnoy.no", +"brønnøy.no", +"bygland.no", +"bykle.no", +"barum.no", +"bærum.no", +"bo.telemark.no", +"bø.telemark.no", +"bo.nordland.no", +"bø.nordland.no", +"bievat.no", +"bievát.no", +"bomlo.no", +"bømlo.no", +"batsfjord.no", +"båtsfjord.no", +"bahcavuotna.no", +"báhcavuotna.no", +"dovre.no", +"drammen.no", +"drangedal.no", +"dyroy.no", +"dyrøy.no", +"donna.no", +"dønna.no", +"eid.no", +"eidfjord.no", +"eidsberg.no", +"eidskog.no", +"eidsvoll.no", +"eigersund.no", +"elverum.no", +"enebakk.no", +"engerdal.no", +"etne.no", +"etnedal.no", +"evenes.no", +"evenassi.no", +"evenášši.no", +"evje-og-hornnes.no", +"farsund.no", +"fauske.no", +"fuossko.no", +"fuoisku.no", +"fedje.no", +"fet.no", +"finnoy.no", +"finnøy.no", +"fitjar.no", +"fjaler.no", +"fjell.no", +"flakstad.no", +"flatanger.no", +"flekkefjord.no", +"flesberg.no", +"flora.no", +"fla.no", +"flå.no", +"folldal.no", +"forsand.no", +"fosnes.no", +"frei.no", +"frogn.no", +"froland.no", +"frosta.no", +"frana.no", +"fræna.no", +"froya.no", +"frøya.no", +"fusa.no", +"fyresdal.no", +"forde.no", +"førde.no", +"gamvik.no", +"gangaviika.no", +"gáŋgaviika.no", +"gaular.no", +"gausdal.no", +"gildeskal.no", +"gildeskål.no", +"giske.no", +"gjemnes.no", +"gjerdrum.no", +"gjerstad.no", +"gjesdal.no", +"gjovik.no", +"gjøvik.no", +"gloppen.no", +"gol.no", +"gran.no", +"grane.no", +"granvin.no", +"gratangen.no", +"grimstad.no", +"grong.no", +"kraanghke.no", +"kråanghke.no", +"grue.no", +"gulen.no", +"hadsel.no", +"halden.no", +"halsa.no", +"hamar.no", +"hamaroy.no", +"habmer.no", +"hábmer.no", +"hapmir.no", +"hápmir.no", +"hammerfest.no", +"hammarfeasta.no", +"hámmárfeasta.no", +"haram.no", +"hareid.no", +"harstad.no", +"hasvik.no", +"aknoluokta.no", +"ákŋoluokta.no", +"hattfjelldal.no", +"aarborte.no", +"haugesund.no", +"hemne.no", +"hemnes.no", +"hemsedal.no", +"heroy.more-og-romsdal.no", +"herøy.møre-og-romsdal.no", +"heroy.nordland.no", +"herøy.nordland.no", +"hitra.no", +"hjartdal.no", +"hjelmeland.no", +"hobol.no", +"hobøl.no", +"hof.no", +"hol.no", +"hole.no", +"holmestrand.no", +"holtalen.no", +"holtålen.no", +"hornindal.no", +"horten.no", +"hurdal.no", +"hurum.no", +"hvaler.no", +"hyllestad.no", +"hagebostad.no", +"hægebostad.no", +"hoyanger.no", +"høyanger.no", +"hoylandet.no", +"høylandet.no", +"ha.no", +"hå.no", +"ibestad.no", +"inderoy.no", +"inderøy.no", +"iveland.no", +"jevnaker.no", +"jondal.no", +"jolster.no", +"jølster.no", +"karasjok.no", +"karasjohka.no", +"kárášjohka.no", +"karlsoy.no", +"galsa.no", +"gálsá.no", +"karmoy.no", +"karmøy.no", +"kautokeino.no", +"guovdageaidnu.no", +"klepp.no", +"klabu.no", +"klæbu.no", +"kongsberg.no", +"kongsvinger.no", +"kragero.no", +"kragerø.no", +"kristiansand.no", +"kristiansund.no", +"krodsherad.no", +"krødsherad.no", +"kvalsund.no", +"rahkkeravju.no", +"ráhkkerávju.no", +"kvam.no", +"kvinesdal.no", +"kvinnherad.no", +"kviteseid.no", +"kvitsoy.no", +"kvitsøy.no", +"kvafjord.no", +"kvæfjord.no", +"giehtavuoatna.no", +"kvanangen.no", +"kvænangen.no", +"navuotna.no", +"návuotna.no", +"kafjord.no", +"kåfjord.no", +"gaivuotna.no", +"gáivuotna.no", +"larvik.no", +"lavangen.no", +"lavagis.no", +"loabat.no", +"loabát.no", +"lebesby.no", +"davvesiida.no", +"leikanger.no", +"leirfjord.no", +"leka.no", +"leksvik.no", +"lenvik.no", +"leangaviika.no", +"leaŋgaviika.no", +"lesja.no", +"levanger.no", +"lier.no", +"lierne.no", +"lillehammer.no", +"lillesand.no", +"lindesnes.no", +"lindas.no", +"lindås.no", +"lom.no", +"loppa.no", +"lahppi.no", +"láhppi.no", +"lund.no", +"lunner.no", +"luroy.no", +"lurøy.no", +"luster.no", +"lyngdal.no", +"lyngen.no", +"ivgu.no", +"lardal.no", +"lerdal.no", +"lærdal.no", +"lodingen.no", +"lødingen.no", +"lorenskog.no", +"lørenskog.no", +"loten.no", +"løten.no", +"malvik.no", +"masoy.no", +"måsøy.no", +"muosat.no", +"muosát.no", +"mandal.no", +"marker.no", +"marnardal.no", +"masfjorden.no", +"meland.no", +"meldal.no", +"melhus.no", +"meloy.no", +"meløy.no", +"meraker.no", +"meråker.no", +"moareke.no", +"moåreke.no", +"midsund.no", +"midtre-gauldal.no", +"modalen.no", +"modum.no", +"molde.no", +"moskenes.no", +"moss.no", +"mosvik.no", +"malselv.no", +"målselv.no", +"malatvuopmi.no", +"málatvuopmi.no", +"namdalseid.no", +"aejrie.no", +"namsos.no", +"namsskogan.no", +"naamesjevuemie.no", +"nååmesjevuemie.no", +"laakesvuemie.no", +"nannestad.no", +"narvik.no", +"narviika.no", +"naustdal.no", +"nedre-eiker.no", +"nes.akershus.no", +"nes.buskerud.no", +"nesna.no", +"nesodden.no", +"nesseby.no", +"unjarga.no", +"unjárga.no", +"nesset.no", +"nissedal.no", +"nittedal.no", +"nord-aurdal.no", +"nord-fron.no", +"nord-odal.no", +"norddal.no", +"nordkapp.no", +"davvenjarga.no", +"davvenjárga.no", +"nordre-land.no", +"nordreisa.no", +"raisa.no", +"ráisa.no", +"nore-og-uvdal.no", +"notodden.no", +"naroy.no", +"nærøy.no", +"notteroy.no", +"nøtterøy.no", +"odda.no", +"oksnes.no", +"øksnes.no", +"oppdal.no", +"oppegard.no", +"oppegård.no", +"orkdal.no", +"orland.no", +"ørland.no", +"orskog.no", +"ørskog.no", +"orsta.no", +"ørsta.no", +"os.hedmark.no", +"os.hordaland.no", +"osen.no", +"osteroy.no", +"osterøy.no", +"ostre-toten.no", +"østre-toten.no", +"overhalla.no", +"ovre-eiker.no", +"øvre-eiker.no", +"oyer.no", +"øyer.no", +"oygarden.no", +"øygarden.no", +"oystre-slidre.no", +"øystre-slidre.no", +"porsanger.no", +"porsangu.no", +"porsáŋgu.no", +"porsgrunn.no", +"radoy.no", +"radøy.no", +"rakkestad.no", +"rana.no", +"ruovat.no", +"randaberg.no", +"rauma.no", +"rendalen.no", +"rennebu.no", +"rennesoy.no", +"rennesøy.no", +"rindal.no", +"ringebu.no", +"ringerike.no", +"ringsaker.no", +"rissa.no", +"risor.no", +"risør.no", +"roan.no", +"rollag.no", +"rygge.no", +"ralingen.no", +"rælingen.no", +"rodoy.no", +"rødøy.no", +"romskog.no", +"rømskog.no", +"roros.no", +"røros.no", +"rost.no", +"røst.no", +"royken.no", +"røyken.no", +"royrvik.no", +"røyrvik.no", +"rade.no", +"råde.no", +"salangen.no", +"siellak.no", +"saltdal.no", +"salat.no", +"sálát.no", +"sálat.no", +"samnanger.no", +"sande.more-og-romsdal.no", +"sande.møre-og-romsdal.no", +"sande.vestfold.no", +"sandefjord.no", +"sandnes.no", +"sandoy.no", +"sandøy.no", +"sarpsborg.no", +"sauda.no", +"sauherad.no", +"sel.no", +"selbu.no", +"selje.no", +"seljord.no", +"sigdal.no", +"siljan.no", +"sirdal.no", +"skaun.no", +"skedsmo.no", +"ski.no", +"skien.no", +"skiptvet.no", +"skjervoy.no", +"skjervøy.no", +"skierva.no", +"skiervá.no", +"skjak.no", +"skjåk.no", +"skodje.no", +"skanland.no", +"skånland.no", +"skanit.no", +"skánit.no", +"smola.no", +"smøla.no", +"snillfjord.no", +"snasa.no", +"snåsa.no", +"snoasa.no", +"snaase.no", +"snåase.no", +"sogndal.no", +"sokndal.no", +"sola.no", +"solund.no", +"songdalen.no", +"sortland.no", +"spydeberg.no", +"stange.no", +"stavanger.no", +"steigen.no", +"steinkjer.no", +"stjordal.no", +"stjørdal.no", +"stokke.no", +"stor-elvdal.no", +"stord.no", +"stordal.no", +"storfjord.no", +"omasvuotna.no", +"strand.no", +"stranda.no", +"stryn.no", +"sula.no", +"suldal.no", +"sund.no", +"sunndal.no", +"surnadal.no", +"sveio.no", +"svelvik.no", +"sykkylven.no", +"sogne.no", +"søgne.no", +"somna.no", +"sømna.no", +"sondre-land.no", +"søndre-land.no", +"sor-aurdal.no", +"sør-aurdal.no", +"sor-fron.no", +"sør-fron.no", +"sor-odal.no", +"sør-odal.no", +"sor-varanger.no", +"sør-varanger.no", +"matta-varjjat.no", +"mátta-várjjat.no", +"sorfold.no", +"sørfold.no", +"sorreisa.no", +"sørreisa.no", +"sorum.no", +"sørum.no", +"tana.no", +"deatnu.no", +"time.no", +"tingvoll.no", +"tinn.no", +"tjeldsund.no", +"dielddanuorri.no", +"tjome.no", +"tjøme.no", +"tokke.no", +"tolga.no", +"torsken.no", +"tranoy.no", +"tranøy.no", +"tromso.no", +"tromsø.no", +"tromsa.no", +"romsa.no", +"trondheim.no", +"troandin.no", +"trysil.no", +"trana.no", +"træna.no", +"trogstad.no", +"trøgstad.no", +"tvedestrand.no", +"tydal.no", +"tynset.no", +"tysfjord.no", +"divtasvuodna.no", +"divttasvuotna.no", +"tysnes.no", +"tysvar.no", +"tysvær.no", +"tonsberg.no", +"tønsberg.no", +"ullensaker.no", +"ullensvang.no", +"ulvik.no", +"utsira.no", +"vadso.no", +"vadsø.no", +"cahcesuolo.no", +"čáhcesuolo.no", +"vaksdal.no", +"valle.no", +"vang.no", +"vanylven.no", +"vardo.no", +"vardø.no", +"varggat.no", +"várggát.no", +"vefsn.no", +"vaapste.no", +"vega.no", +"vegarshei.no", +"vegårshei.no", +"vennesla.no", +"verdal.no", +"verran.no", +"vestby.no", +"vestnes.no", +"vestre-slidre.no", +"vestre-toten.no", +"vestvagoy.no", +"vestvågøy.no", +"vevelstad.no", +"vik.no", +"vikna.no", +"vindafjord.no", +"volda.no", +"voss.no", +"varoy.no", +"værøy.no", +"vagan.no", +"vågan.no", +"voagat.no", +"vagsoy.no", +"vågsøy.no", +"vaga.no", +"vågå.no", +"valer.ostfold.no", +"våler.østfold.no", +"valer.hedmark.no", +"våler.hedmark.no", +"*.np", +"nr", +"biz.nr", +"info.nr", +"gov.nr", +"edu.nr", +"org.nr", +"net.nr", +"com.nr", +"nu", +"nz", +"ac.nz", +"co.nz", +"cri.nz", +"geek.nz", +"gen.nz", +"govt.nz", +"health.nz", +"iwi.nz", +"kiwi.nz", +"maori.nz", +"mil.nz", +"māori.nz", +"net.nz", +"org.nz", +"parliament.nz", +"school.nz", +"om", +"co.om", +"com.om", +"edu.om", +"gov.om", +"med.om", +"museum.om", +"net.om", +"org.om", +"pro.om", +"onion", +"org", +"pa", +"ac.pa", +"gob.pa", +"com.pa", +"org.pa", +"sld.pa", +"edu.pa", +"net.pa", +"ing.pa", +"abo.pa", +"med.pa", +"nom.pa", +"pe", +"edu.pe", +"gob.pe", +"nom.pe", +"mil.pe", +"org.pe", +"com.pe", +"net.pe", +"pf", +"com.pf", +"org.pf", +"edu.pf", +"*.pg", +"ph", +"com.ph", +"net.ph", +"org.ph", +"gov.ph", +"edu.ph", +"ngo.ph", +"mil.ph", +"i.ph", +"pk", +"com.pk", +"net.pk", +"edu.pk", +"org.pk", +"fam.pk", +"biz.pk", +"web.pk", +"gov.pk", +"gob.pk", +"gok.pk", +"gon.pk", +"gop.pk", +"gos.pk", +"info.pk", +"pl", +"com.pl", +"net.pl", +"org.pl", +"aid.pl", +"agro.pl", +"atm.pl", +"auto.pl", +"biz.pl", +"edu.pl", +"gmina.pl", +"gsm.pl", +"info.pl", +"mail.pl", +"miasta.pl", +"media.pl", +"mil.pl", +"nieruchomosci.pl", +"nom.pl", +"pc.pl", +"powiat.pl", +"priv.pl", +"realestate.pl", +"rel.pl", +"sex.pl", +"shop.pl", +"sklep.pl", +"sos.pl", +"szkola.pl", +"targi.pl", +"tm.pl", +"tourism.pl", +"travel.pl", +"turystyka.pl", +"gov.pl", +"ap.gov.pl", +"ic.gov.pl", +"is.gov.pl", +"us.gov.pl", +"kmpsp.gov.pl", +"kppsp.gov.pl", +"kwpsp.gov.pl", +"psp.gov.pl", +"wskr.gov.pl", +"kwp.gov.pl", +"mw.gov.pl", +"ug.gov.pl", +"um.gov.pl", +"umig.gov.pl", +"ugim.gov.pl", +"upow.gov.pl", +"uw.gov.pl", +"starostwo.gov.pl", +"pa.gov.pl", +"po.gov.pl", +"psse.gov.pl", +"pup.gov.pl", +"rzgw.gov.pl", +"sa.gov.pl", +"so.gov.pl", +"sr.gov.pl", +"wsa.gov.pl", +"sko.gov.pl", +"uzs.gov.pl", +"wiih.gov.pl", +"winb.gov.pl", +"pinb.gov.pl", +"wios.gov.pl", +"witd.gov.pl", +"wzmiuw.gov.pl", +"piw.gov.pl", +"wiw.gov.pl", +"griw.gov.pl", +"wif.gov.pl", +"oum.gov.pl", +"sdn.gov.pl", +"zp.gov.pl", +"uppo.gov.pl", +"mup.gov.pl", +"wuoz.gov.pl", +"konsulat.gov.pl", +"oirm.gov.pl", +"augustow.pl", +"babia-gora.pl", +"bedzin.pl", +"beskidy.pl", +"bialowieza.pl", +"bialystok.pl", +"bielawa.pl", +"bieszczady.pl", +"boleslawiec.pl", +"bydgoszcz.pl", +"bytom.pl", +"cieszyn.pl", +"czeladz.pl", +"czest.pl", +"dlugoleka.pl", +"elblag.pl", +"elk.pl", +"glogow.pl", +"gniezno.pl", +"gorlice.pl", +"grajewo.pl", +"ilawa.pl", +"jaworzno.pl", +"jelenia-gora.pl", +"jgora.pl", +"kalisz.pl", +"kazimierz-dolny.pl", +"karpacz.pl", +"kartuzy.pl", +"kaszuby.pl", +"katowice.pl", +"kepno.pl", +"ketrzyn.pl", +"klodzko.pl", +"kobierzyce.pl", +"kolobrzeg.pl", +"konin.pl", +"konskowola.pl", +"kutno.pl", +"lapy.pl", +"lebork.pl", +"legnica.pl", +"lezajsk.pl", +"limanowa.pl", +"lomza.pl", +"lowicz.pl", +"lubin.pl", +"lukow.pl", +"malbork.pl", +"malopolska.pl", +"mazowsze.pl", +"mazury.pl", +"mielec.pl", +"mielno.pl", +"mragowo.pl", +"naklo.pl", +"nowaruda.pl", +"nysa.pl", +"olawa.pl", +"olecko.pl", +"olkusz.pl", +"olsztyn.pl", +"opoczno.pl", +"opole.pl", +"ostroda.pl", +"ostroleka.pl", +"ostrowiec.pl", +"ostrowwlkp.pl", +"pila.pl", +"pisz.pl", +"podhale.pl", +"podlasie.pl", +"polkowice.pl", +"pomorze.pl", +"pomorskie.pl", +"prochowice.pl", +"pruszkow.pl", +"przeworsk.pl", +"pulawy.pl", +"radom.pl", +"rawa-maz.pl", +"rybnik.pl", +"rzeszow.pl", +"sanok.pl", +"sejny.pl", +"slask.pl", +"slupsk.pl", +"sosnowiec.pl", +"stalowa-wola.pl", +"skoczow.pl", +"starachowice.pl", +"stargard.pl", +"suwalki.pl", +"swidnica.pl", +"swiebodzin.pl", +"swinoujscie.pl", +"szczecin.pl", +"szczytno.pl", +"tarnobrzeg.pl", +"tgory.pl", +"turek.pl", +"tychy.pl", +"ustka.pl", +"walbrzych.pl", +"warmia.pl", +"warszawa.pl", +"waw.pl", +"wegrow.pl", +"wielun.pl", +"wlocl.pl", +"wloclawek.pl", +"wodzislaw.pl", +"wolomin.pl", +"wroclaw.pl", +"zachpomor.pl", +"zagan.pl", +"zarow.pl", +"zgora.pl", +"zgorzelec.pl", +"pm", +"pn", +"gov.pn", +"co.pn", +"org.pn", +"edu.pn", +"net.pn", +"post", +"pr", +"com.pr", +"net.pr", +"org.pr", +"gov.pr", +"edu.pr", +"isla.pr", +"pro.pr", +"biz.pr", +"info.pr", +"name.pr", +"est.pr", +"prof.pr", +"ac.pr", +"pro", +"aaa.pro", +"aca.pro", +"acct.pro", +"avocat.pro", +"bar.pro", +"cpa.pro", +"eng.pro", +"jur.pro", +"law.pro", +"med.pro", +"recht.pro", +"ps", +"edu.ps", +"gov.ps", +"sec.ps", +"plo.ps", +"com.ps", +"org.ps", +"net.ps", +"pt", +"net.pt", +"gov.pt", +"org.pt", +"edu.pt", +"int.pt", +"publ.pt", +"com.pt", +"nome.pt", +"pw", +"co.pw", +"ne.pw", +"or.pw", +"ed.pw", +"go.pw", +"belau.pw", +"py", +"com.py", +"coop.py", +"edu.py", +"gov.py", +"mil.py", +"net.py", +"org.py", +"qa", +"com.qa", +"edu.qa", +"gov.qa", +"mil.qa", +"name.qa", +"net.qa", +"org.qa", +"sch.qa", +"re", +"asso.re", +"com.re", +"nom.re", +"ro", +"arts.ro", +"com.ro", +"firm.ro", +"info.ro", +"nom.ro", +"nt.ro", +"org.ro", +"rec.ro", +"store.ro", +"tm.ro", +"www.ro", +"rs", +"ac.rs", +"co.rs", +"edu.rs", +"gov.rs", +"in.rs", +"org.rs", +"ru", +"rw", +"ac.rw", +"co.rw", +"coop.rw", +"gov.rw", +"mil.rw", +"net.rw", +"org.rw", +"sa", +"com.sa", +"net.sa", +"org.sa", +"gov.sa", +"med.sa", +"pub.sa", +"edu.sa", +"sch.sa", +"sb", +"com.sb", +"edu.sb", +"gov.sb", +"net.sb", +"org.sb", +"sc", +"com.sc", +"gov.sc", +"net.sc", +"org.sc", +"edu.sc", +"sd", +"com.sd", +"net.sd", +"org.sd", +"edu.sd", +"med.sd", +"tv.sd", +"gov.sd", +"info.sd", +"se", +"a.se", +"ac.se", +"b.se", +"bd.se", +"brand.se", +"c.se", +"d.se", +"e.se", +"f.se", +"fh.se", +"fhsk.se", +"fhv.se", +"g.se", +"h.se", +"i.se", +"k.se", +"komforb.se", +"kommunalforbund.se", +"komvux.se", +"l.se", +"lanbib.se", +"m.se", +"n.se", +"naturbruksgymn.se", +"o.se", +"org.se", +"p.se", +"parti.se", +"pp.se", +"press.se", +"r.se", +"s.se", +"t.se", +"tm.se", +"u.se", +"w.se", +"x.se", +"y.se", +"z.se", +"sg", +"com.sg", +"net.sg", +"org.sg", +"gov.sg", +"edu.sg", +"per.sg", +"sh", +"com.sh", +"net.sh", +"gov.sh", +"org.sh", +"mil.sh", +"si", +"sj", +"sk", +"sl", +"com.sl", +"net.sl", +"edu.sl", +"gov.sl", +"org.sl", +"sm", +"sn", +"art.sn", +"com.sn", +"edu.sn", +"gouv.sn", +"org.sn", +"perso.sn", +"univ.sn", +"so", +"com.so", +"edu.so", +"gov.so", +"me.so", +"net.so", +"org.so", +"sr", +"ss", +"biz.ss", +"com.ss", +"edu.ss", +"gov.ss", +"net.ss", +"org.ss", +"st", +"co.st", +"com.st", +"consulado.st", +"edu.st", +"embaixada.st", +"gov.st", +"mil.st", +"net.st", +"org.st", +"principe.st", +"saotome.st", +"store.st", +"su", +"sv", +"com.sv", +"edu.sv", +"gob.sv", +"org.sv", +"red.sv", +"sx", +"gov.sx", +"sy", +"edu.sy", +"gov.sy", +"net.sy", +"mil.sy", +"com.sy", +"org.sy", +"sz", +"co.sz", +"ac.sz", +"org.sz", +"tc", +"td", +"tel", +"tf", +"tg", +"th", +"ac.th", +"co.th", +"go.th", +"in.th", +"mi.th", +"net.th", +"or.th", +"tj", +"ac.tj", +"biz.tj", +"co.tj", +"com.tj", +"edu.tj", +"go.tj", +"gov.tj", +"int.tj", +"mil.tj", +"name.tj", +"net.tj", +"nic.tj", +"org.tj", +"test.tj", +"web.tj", +"tk", +"tl", +"gov.tl", +"tm", +"com.tm", +"co.tm", +"org.tm", +"net.tm", +"nom.tm", +"gov.tm", +"mil.tm", +"edu.tm", +"tn", +"com.tn", +"ens.tn", +"fin.tn", +"gov.tn", +"ind.tn", +"intl.tn", +"nat.tn", +"net.tn", +"org.tn", +"info.tn", +"perso.tn", +"tourism.tn", +"edunet.tn", +"rnrt.tn", +"rns.tn", +"rnu.tn", +"mincom.tn", +"agrinet.tn", +"defense.tn", +"turen.tn", +"to", +"com.to", +"gov.to", +"net.to", +"org.to", +"edu.to", +"mil.to", +"tr", +"av.tr", +"bbs.tr", +"bel.tr", +"biz.tr", +"com.tr", +"dr.tr", +"edu.tr", +"gen.tr", +"gov.tr", +"info.tr", +"mil.tr", +"k12.tr", +"kep.tr", +"name.tr", +"net.tr", +"org.tr", +"pol.tr", +"tel.tr", +"tsk.tr", +"tv.tr", +"web.tr", +"nc.tr", +"gov.nc.tr", +"tt", +"co.tt", +"com.tt", +"org.tt", +"net.tt", +"biz.tt", +"info.tt", +"pro.tt", +"int.tt", +"coop.tt", +"jobs.tt", +"mobi.tt", +"travel.tt", +"museum.tt", +"aero.tt", +"name.tt", +"gov.tt", +"edu.tt", +"tv", +"tw", +"edu.tw", +"gov.tw", +"mil.tw", +"com.tw", +"net.tw", +"org.tw", +"idv.tw", +"game.tw", +"ebiz.tw", +"club.tw", +"網路.tw", +"組織.tw", +"商業.tw", +"tz", +"ac.tz", +"co.tz", +"go.tz", +"hotel.tz", +"info.tz", +"me.tz", +"mil.tz", +"mobi.tz", +"ne.tz", +"or.tz", +"sc.tz", +"tv.tz", +"ua", +"com.ua", +"edu.ua", +"gov.ua", +"in.ua", +"net.ua", +"org.ua", +"cherkassy.ua", +"cherkasy.ua", +"chernigov.ua", +"chernihiv.ua", +"chernivtsi.ua", +"chernovtsy.ua", +"ck.ua", +"cn.ua", +"cr.ua", +"crimea.ua", +"cv.ua", +"dn.ua", +"dnepropetrovsk.ua", +"dnipropetrovsk.ua", +"dominic.ua", +"donetsk.ua", +"dp.ua", +"if.ua", +"ivano-frankivsk.ua", +"kh.ua", +"kharkiv.ua", +"kharkov.ua", +"kherson.ua", +"khmelnitskiy.ua", +"khmelnytskyi.ua", +"kiev.ua", +"kirovograd.ua", +"km.ua", +"kr.ua", +"krym.ua", +"ks.ua", +"kv.ua", +"kyiv.ua", +"lg.ua", +"lt.ua", +"lugansk.ua", +"lutsk.ua", +"lv.ua", +"lviv.ua", +"mk.ua", +"mykolaiv.ua", +"nikolaev.ua", +"od.ua", +"odesa.ua", +"odessa.ua", +"pl.ua", +"poltava.ua", +"rivne.ua", +"rovno.ua", +"rv.ua", +"sb.ua", +"sebastopol.ua", +"sevastopol.ua", +"sm.ua", +"sumy.ua", +"te.ua", +"ternopil.ua", +"uz.ua", +"uzhgorod.ua", +"vinnica.ua", +"vinnytsia.ua", +"vn.ua", +"volyn.ua", +"yalta.ua", +"zaporizhzhe.ua", +"zaporizhzhia.ua", +"zhitomir.ua", +"zhytomyr.ua", +"zp.ua", +"zt.ua", +"ug", +"co.ug", +"or.ug", +"ac.ug", +"sc.ug", +"go.ug", +"ne.ug", +"com.ug", +"org.ug", +"uk", +"ac.uk", +"co.uk", +"gov.uk", +"ltd.uk", +"me.uk", +"net.uk", +"nhs.uk", +"org.uk", +"plc.uk", +"police.uk", +"*.sch.uk", +"us", +"dni.us", +"fed.us", +"isa.us", +"kids.us", +"nsn.us", +"ak.us", +"al.us", +"ar.us", +"as.us", +"az.us", +"ca.us", +"co.us", +"ct.us", +"dc.us", +"de.us", +"fl.us", +"ga.us", +"gu.us", +"hi.us", +"ia.us", +"id.us", +"il.us", +"in.us", +"ks.us", +"ky.us", +"la.us", +"ma.us", +"md.us", +"me.us", +"mi.us", +"mn.us", +"mo.us", +"ms.us", +"mt.us", +"nc.us", +"nd.us", +"ne.us", +"nh.us", +"nj.us", +"nm.us", +"nv.us", +"ny.us", +"oh.us", +"ok.us", +"or.us", +"pa.us", +"pr.us", +"ri.us", +"sc.us", +"sd.us", +"tn.us", +"tx.us", +"ut.us", +"vi.us", +"vt.us", +"va.us", +"wa.us", +"wi.us", +"wv.us", +"wy.us", +"k12.ak.us", +"k12.al.us", +"k12.ar.us", +"k12.as.us", +"k12.az.us", +"k12.ca.us", +"k12.co.us", +"k12.ct.us", +"k12.dc.us", +"k12.de.us", +"k12.fl.us", +"k12.ga.us", +"k12.gu.us", +"k12.ia.us", +"k12.id.us", +"k12.il.us", +"k12.in.us", +"k12.ks.us", +"k12.ky.us", +"k12.la.us", +"k12.ma.us", +"k12.md.us", +"k12.me.us", +"k12.mi.us", +"k12.mn.us", +"k12.mo.us", +"k12.ms.us", +"k12.mt.us", +"k12.nc.us", +"k12.ne.us", +"k12.nh.us", +"k12.nj.us", +"k12.nm.us", +"k12.nv.us", +"k12.ny.us", +"k12.oh.us", +"k12.ok.us", +"k12.or.us", +"k12.pa.us", +"k12.pr.us", +"k12.ri.us", +"k12.sc.us", +"k12.tn.us", +"k12.tx.us", +"k12.ut.us", +"k12.vi.us", +"k12.vt.us", +"k12.va.us", +"k12.wa.us", +"k12.wi.us", +"k12.wy.us", +"cc.ak.us", +"cc.al.us", +"cc.ar.us", +"cc.as.us", +"cc.az.us", +"cc.ca.us", +"cc.co.us", +"cc.ct.us", +"cc.dc.us", +"cc.de.us", +"cc.fl.us", +"cc.ga.us", +"cc.gu.us", +"cc.hi.us", +"cc.ia.us", +"cc.id.us", +"cc.il.us", +"cc.in.us", +"cc.ks.us", +"cc.ky.us", +"cc.la.us", +"cc.ma.us", +"cc.md.us", +"cc.me.us", +"cc.mi.us", +"cc.mn.us", +"cc.mo.us", +"cc.ms.us", +"cc.mt.us", +"cc.nc.us", +"cc.nd.us", +"cc.ne.us", +"cc.nh.us", +"cc.nj.us", +"cc.nm.us", +"cc.nv.us", +"cc.ny.us", +"cc.oh.us", +"cc.ok.us", +"cc.or.us", +"cc.pa.us", +"cc.pr.us", +"cc.ri.us", +"cc.sc.us", +"cc.sd.us", +"cc.tn.us", +"cc.tx.us", +"cc.ut.us", +"cc.vi.us", +"cc.vt.us", +"cc.va.us", +"cc.wa.us", +"cc.wi.us", +"cc.wv.us", +"cc.wy.us", +"lib.ak.us", +"lib.al.us", +"lib.ar.us", +"lib.as.us", +"lib.az.us", +"lib.ca.us", +"lib.co.us", +"lib.ct.us", +"lib.dc.us", +"lib.fl.us", +"lib.ga.us", +"lib.gu.us", +"lib.hi.us", +"lib.ia.us", +"lib.id.us", +"lib.il.us", +"lib.in.us", +"lib.ks.us", +"lib.ky.us", +"lib.la.us", +"lib.ma.us", +"lib.md.us", +"lib.me.us", +"lib.mi.us", +"lib.mn.us", +"lib.mo.us", +"lib.ms.us", +"lib.mt.us", +"lib.nc.us", +"lib.nd.us", +"lib.ne.us", +"lib.nh.us", +"lib.nj.us", +"lib.nm.us", +"lib.nv.us", +"lib.ny.us", +"lib.oh.us", +"lib.ok.us", +"lib.or.us", +"lib.pa.us", +"lib.pr.us", +"lib.ri.us", +"lib.sc.us", +"lib.sd.us", +"lib.tn.us", +"lib.tx.us", +"lib.ut.us", +"lib.vi.us", +"lib.vt.us", +"lib.va.us", +"lib.wa.us", +"lib.wi.us", +"lib.wy.us", +"pvt.k12.ma.us", +"chtr.k12.ma.us", +"paroch.k12.ma.us", +"ann-arbor.mi.us", +"cog.mi.us", +"dst.mi.us", +"eaton.mi.us", +"gen.mi.us", +"mus.mi.us", +"tec.mi.us", +"washtenaw.mi.us", +"uy", +"com.uy", +"edu.uy", +"gub.uy", +"mil.uy", +"net.uy", +"org.uy", +"uz", +"co.uz", +"com.uz", +"net.uz", +"org.uz", +"va", +"vc", +"com.vc", +"net.vc", +"org.vc", +"gov.vc", +"mil.vc", +"edu.vc", +"ve", +"arts.ve", +"co.ve", +"com.ve", +"e12.ve", +"edu.ve", +"firm.ve", +"gob.ve", +"gov.ve", +"info.ve", +"int.ve", +"mil.ve", +"net.ve", +"org.ve", +"rec.ve", +"store.ve", +"tec.ve", +"web.ve", +"vg", +"vi", +"co.vi", +"com.vi", +"k12.vi", +"net.vi", +"org.vi", +"vn", +"com.vn", +"net.vn", +"org.vn", +"edu.vn", +"gov.vn", +"int.vn", +"ac.vn", +"biz.vn", +"info.vn", +"name.vn", +"pro.vn", +"health.vn", +"vu", +"com.vu", +"edu.vu", +"net.vu", +"org.vu", +"wf", +"ws", +"com.ws", +"net.ws", +"org.ws", +"gov.ws", +"edu.ws", +"yt", +"امارات", +"հայ", +"বাংলা", +"бг", +"бел", +"中国", +"中國", +"الجزائر", +"مصر", +"ею", +"ευ", +"موريتانيا", +"გე", +"ελ", +"香港", +"公司.香港", +"教育.香港", +"政府.香港", +"個人.香港", +"網絡.香港", +"組織.香港", +"ಭಾರತ", +"ଭାରତ", +"ভাৰত", +"भारतम्", +"भारोत", +"ڀارت", +"ഭാരതം", +"भारत", +"بارت", +"بھارت", +"భారత్", +"ભારત", +"ਭਾਰਤ", +"ভারত", +"இந்தியா", +"ایران", +"ايران", +"عراق", +"الاردن", +"한국", +"қаз", +"ලංකා", +"இலங்கை", +"المغرب", +"мкд", +"мон", +"澳門", +"澳门", +"مليسيا", +"عمان", +"پاکستان", +"پاكستان", +"فلسطين", +"срб", +"пр.срб", +"орг.срб", +"обр.срб", +"од.срб", +"упр.срб", +"ак.срб", +"рф", +"قطر", +"السعودية", +"السعودیة", +"السعودیۃ", +"السعوديه", +"سودان", +"新加坡", +"சிங்கப்பூர்", +"سورية", +"سوريا", +"ไทย", +"ศึกษา.ไทย", +"ธุรกิจ.ไทย", +"รัฐบาล.ไทย", +"ทหาร.ไทย", +"เน็ต.ไทย", +"องค์กร.ไทย", +"تونس", +"台灣", +"台湾", +"臺灣", +"укр", +"اليمن", +"xxx", +"*.ye", +"ac.za", +"agric.za", +"alt.za", +"co.za", +"edu.za", +"gov.za", +"grondar.za", +"law.za", +"mil.za", +"net.za", +"ngo.za", +"nic.za", +"nis.za", +"nom.za", +"org.za", +"school.za", +"tm.za", +"web.za", +"zm", +"ac.zm", +"biz.zm", +"co.zm", +"com.zm", +"edu.zm", +"gov.zm", +"info.zm", +"mil.zm", +"net.zm", +"org.zm", +"sch.zm", +"zw", +"ac.zw", +"co.zw", +"gov.zw", +"mil.zw", +"org.zw", +"aaa", +"aarp", +"abarth", +"abb", +"abbott", +"abbvie", +"abc", +"able", +"abogado", +"abudhabi", +"academy", +"accenture", +"accountant", +"accountants", +"aco", +"actor", +"adac", +"ads", +"adult", +"aeg", +"aetna", +"afamilycompany", +"afl", +"africa", +"agakhan", +"agency", +"aig", +"aigo", +"airbus", +"airforce", +"airtel", +"akdn", +"alfaromeo", +"alibaba", +"alipay", +"allfinanz", +"allstate", +"ally", +"alsace", +"alstom", +"amazon", +"americanexpress", +"americanfamily", +"amex", +"amfam", +"amica", +"amsterdam", +"analytics", +"android", +"anquan", +"anz", +"aol", +"apartments", +"app", +"apple", +"aquarelle", +"arab", +"aramco", +"archi", +"army", +"art", +"arte", +"asda", +"associates", +"athleta", +"attorney", +"auction", +"audi", +"audible", +"audio", +"auspost", +"author", +"auto", +"autos", +"avianca", +"aws", +"axa", +"azure", +"baby", +"baidu", +"banamex", +"bananarepublic", +"band", +"bank", +"bar", +"barcelona", +"barclaycard", +"barclays", +"barefoot", +"bargains", +"baseball", +"basketball", +"bauhaus", +"bayern", +"bbc", +"bbt", +"bbva", +"bcg", +"bcn", +"beats", +"beauty", +"beer", +"bentley", +"berlin", +"best", +"bestbuy", +"bet", +"bharti", +"bible", +"bid", +"bike", +"bing", +"bingo", +"bio", +"black", +"blackfriday", +"blockbuster", +"blog", +"bloomberg", +"blue", +"bms", +"bmw", +"bnpparibas", +"boats", +"boehringer", +"bofa", +"bom", +"bond", +"boo", +"book", +"booking", +"bosch", +"bostik", +"boston", +"bot", +"boutique", +"box", +"bradesco", +"bridgestone", +"broadway", +"broker", +"brother", +"brussels", +"budapest", +"bugatti", +"build", +"builders", +"business", +"buy", +"buzz", +"bzh", +"cab", +"cafe", +"cal", +"call", +"calvinklein", +"cam", +"camera", +"camp", +"cancerresearch", +"canon", +"capetown", +"capital", +"capitalone", +"car", +"caravan", +"cards", +"care", +"career", +"careers", +"cars", +"casa", +"case", +"caseih", +"cash", +"casino", +"catering", +"catholic", +"cba", +"cbn", +"cbre", +"cbs", +"ceb", +"center", +"ceo", +"cern", +"cfa", +"cfd", +"chanel", +"channel", +"charity", +"chase", +"chat", +"cheap", +"chintai", +"christmas", +"chrome", +"church", +"cipriani", +"circle", +"cisco", +"citadel", +"citi", +"citic", +"city", +"cityeats", +"claims", +"cleaning", +"click", +"clinic", +"clinique", +"clothing", +"cloud", +"club", +"clubmed", +"coach", +"codes", +"coffee", +"college", +"cologne", +"comcast", +"commbank", +"community", +"company", +"compare", +"computer", +"comsec", +"condos", +"construction", +"consulting", +"contact", +"contractors", +"cooking", +"cookingchannel", +"cool", +"corsica", +"country", +"coupon", +"coupons", +"courses", +"cpa", +"credit", +"creditcard", +"creditunion", +"cricket", +"crown", +"crs", +"cruise", +"cruises", +"csc", +"cuisinella", +"cymru", +"cyou", +"dabur", +"dad", +"dance", +"data", +"date", +"dating", +"datsun", +"day", +"dclk", +"dds", +"deal", +"dealer", +"deals", +"degree", +"delivery", +"dell", +"deloitte", +"delta", +"democrat", +"dental", +"dentist", +"desi", +"design", +"dev", +"dhl", +"diamonds", +"diet", +"digital", +"direct", +"directory", +"discount", +"discover", +"dish", +"diy", +"dnp", +"docs", +"doctor", +"dog", +"domains", +"dot", +"download", +"drive", +"dtv", +"dubai", +"duck", +"dunlop", +"dupont", +"durban", +"dvag", +"dvr", +"earth", +"eat", +"eco", +"edeka", +"education", +"email", +"emerck", +"energy", +"engineer", +"engineering", +"enterprises", +"epson", +"equipment", +"ericsson", +"erni", +"esq", +"estate", +"esurance", +"etisalat", +"eurovision", +"eus", +"events", +"exchange", +"expert", +"exposed", +"express", +"extraspace", +"fage", +"fail", +"fairwinds", +"faith", +"family", +"fan", +"fans", +"farm", +"farmers", +"fashion", +"fast", +"fedex", +"feedback", +"ferrari", +"ferrero", +"fiat", +"fidelity", +"fido", +"film", +"final", +"finance", +"financial", +"fire", +"firestone", +"firmdale", +"fish", +"fishing", +"fit", +"fitness", +"flickr", +"flights", +"flir", +"florist", +"flowers", +"fly", +"foo", +"food", +"foodnetwork", +"football", +"ford", +"forex", +"forsale", +"forum", +"foundation", +"fox", +"free", +"fresenius", +"frl", +"frogans", +"frontdoor", +"frontier", +"ftr", +"fujitsu", +"fujixerox", +"fun", +"fund", +"furniture", +"futbol", +"fyi", +"gal", +"gallery", +"gallo", +"gallup", +"game", +"games", +"gap", +"garden", +"gay", +"gbiz", +"gdn", +"gea", +"gent", +"genting", +"george", +"ggee", +"gift", +"gifts", +"gives", +"giving", +"glade", +"glass", +"gle", +"global", +"globo", +"gmail", +"gmbh", +"gmo", +"gmx", +"godaddy", +"gold", +"goldpoint", +"golf", +"goo", +"goodyear", +"goog", +"google", +"gop", +"got", +"grainger", +"graphics", +"gratis", +"green", +"gripe", +"grocery", +"group", +"guardian", +"gucci", +"guge", +"guide", +"guitars", +"guru", +"hair", +"hamburg", +"hangout", +"haus", +"hbo", +"hdfc", +"hdfcbank", +"health", +"healthcare", +"help", +"helsinki", +"here", +"hermes", +"hgtv", +"hiphop", +"hisamitsu", +"hitachi", +"hiv", +"hkt", +"hockey", +"holdings", +"holiday", +"homedepot", +"homegoods", +"homes", +"homesense", +"honda", +"horse", +"hospital", +"host", +"hosting", +"hot", +"hoteles", +"hotels", +"hotmail", +"house", +"how", +"hsbc", +"hughes", +"hyatt", +"hyundai", +"ibm", +"icbc", +"ice", +"icu", +"ieee", +"ifm", +"ikano", +"imamat", +"imdb", +"immo", +"immobilien", +"inc", +"industries", +"infiniti", +"ing", +"ink", +"institute", +"insurance", +"insure", +"intel", +"international", +"intuit", +"investments", +"ipiranga", +"irish", +"ismaili", +"ist", +"istanbul", +"itau", +"itv", +"iveco", +"jaguar", +"java", +"jcb", +"jcp", +"jeep", +"jetzt", +"jewelry", +"jio", +"jll", +"jmp", +"jnj", +"joburg", +"jot", +"joy", +"jpmorgan", +"jprs", +"juegos", +"juniper", +"kaufen", +"kddi", +"kerryhotels", +"kerrylogistics", +"kerryproperties", +"kfh", +"kia", +"kim", +"kinder", +"kindle", +"kitchen", +"kiwi", +"koeln", +"komatsu", +"kosher", +"kpmg", +"kpn", +"krd", +"kred", +"kuokgroup", +"kyoto", +"lacaixa", +"lamborghini", +"lamer", +"lancaster", +"lancia", +"land", +"landrover", +"lanxess", +"lasalle", +"lat", +"latino", +"latrobe", +"law", +"lawyer", +"lds", +"lease", +"leclerc", +"lefrak", +"legal", +"lego", +"lexus", +"lgbt", +"lidl", +"life", +"lifeinsurance", +"lifestyle", +"lighting", +"like", +"lilly", +"limited", +"limo", +"lincoln", +"linde", +"link", +"lipsy", +"live", +"living", +"lixil", +"llc", +"llp", +"loan", +"loans", +"locker", +"locus", +"loft", +"lol", +"london", +"lotte", +"lotto", +"love", +"lpl", +"lplfinancial", +"ltd", +"ltda", +"lundbeck", +"lupin", +"luxe", +"luxury", +"macys", +"madrid", +"maif", +"maison", +"makeup", +"man", +"management", +"mango", +"map", +"market", +"marketing", +"markets", +"marriott", +"marshalls", +"maserati", +"mattel", +"mba", +"mckinsey", +"med", +"media", +"meet", +"melbourne", +"meme", +"memorial", +"men", +"menu", +"merckmsd", +"metlife", +"miami", +"microsoft", +"mini", +"mint", +"mit", +"mitsubishi", +"mlb", +"mls", +"mma", +"mobile", +"moda", +"moe", +"moi", +"mom", +"monash", +"money", +"monster", +"mormon", +"mortgage", +"moscow", +"moto", +"motorcycles", +"mov", +"movie", +"msd", +"mtn", +"mtr", +"mutual", +"nab", +"nadex", +"nagoya", +"nationwide", +"natura", +"navy", +"nba", +"nec", +"netbank", +"netflix", +"network", +"neustar", +"new", +"newholland", +"news", +"next", +"nextdirect", +"nexus", +"nfl", +"ngo", +"nhk", +"nico", +"nike", +"nikon", +"ninja", +"nissan", +"nissay", +"nokia", +"northwesternmutual", +"norton", +"now", +"nowruz", +"nowtv", +"nra", +"nrw", +"ntt", +"nyc", +"obi", +"observer", +"off", +"office", +"okinawa", +"olayan", +"olayangroup", +"oldnavy", +"ollo", +"omega", +"one", +"ong", +"onl", +"online", +"onyourside", +"ooo", +"open", +"oracle", +"orange", +"organic", +"origins", +"osaka", +"otsuka", +"ott", +"ovh", +"page", +"panasonic", +"paris", +"pars", +"partners", +"parts", +"party", +"passagens", +"pay", +"pccw", +"pet", +"pfizer", +"pharmacy", +"phd", +"philips", +"phone", +"photo", +"photography", +"photos", +"physio", +"pics", +"pictet", +"pictures", +"pid", +"pin", +"ping", +"pink", +"pioneer", +"pizza", +"place", +"play", +"playstation", +"plumbing", +"plus", +"pnc", +"pohl", +"poker", +"politie", +"porn", +"pramerica", +"praxi", +"press", +"prime", +"prod", +"productions", +"prof", +"progressive", +"promo", +"properties", +"property", +"protection", +"pru", +"prudential", +"pub", +"pwc", +"qpon", +"quebec", +"quest", +"qvc", +"racing", +"radio", +"raid", +"read", +"realestate", +"realtor", +"realty", +"recipes", +"red", +"redstone", +"redumbrella", +"rehab", +"reise", +"reisen", +"reit", +"reliance", +"ren", +"rent", +"rentals", +"repair", +"report", +"republican", +"rest", +"restaurant", +"review", +"reviews", +"rexroth", +"rich", +"richardli", +"ricoh", +"rightathome", +"ril", +"rio", +"rip", +"rmit", +"rocher", +"rocks", +"rodeo", +"rogers", +"room", +"rsvp", +"rugby", +"ruhr", +"run", +"rwe", +"ryukyu", +"saarland", +"safe", +"safety", +"sakura", +"sale", +"salon", +"samsclub", +"samsung", +"sandvik", +"sandvikcoromant", +"sanofi", +"sap", +"sarl", +"sas", +"save", +"saxo", +"sbi", +"sbs", +"sca", +"scb", +"schaeffler", +"schmidt", +"scholarships", +"school", +"schule", +"schwarz", +"science", +"scjohnson", +"scor", +"scot", +"search", +"seat", +"secure", +"security", +"seek", +"select", +"sener", +"services", +"ses", +"seven", +"sew", +"sex", +"sexy", +"sfr", +"shangrila", +"sharp", +"shaw", +"shell", +"shia", +"shiksha", +"shoes", +"shop", +"shopping", +"shouji", +"show", +"showtime", +"shriram", +"silk", +"sina", +"singles", +"site", +"ski", +"skin", +"sky", +"skype", +"sling", +"smart", +"smile", +"sncf", +"soccer", +"social", +"softbank", +"software", +"sohu", +"solar", +"solutions", +"song", +"sony", +"soy", +"spa", +"space", +"sport", +"spot", +"spreadbetting", +"srl", +"stada", +"staples", +"star", +"statebank", +"statefarm", +"stc", +"stcgroup", +"stockholm", +"storage", +"store", +"stream", +"studio", +"study", +"style", +"sucks", +"supplies", +"supply", +"support", +"surf", +"surgery", +"suzuki", +"swatch", +"swiftcover", +"swiss", +"sydney", +"symantec", +"systems", +"tab", +"taipei", +"talk", +"taobao", +"target", +"tatamotors", +"tatar", +"tattoo", +"tax", +"taxi", +"tci", +"tdk", +"team", +"tech", +"technology", +"temasek", +"tennis", +"teva", +"thd", +"theater", +"theatre", +"tiaa", +"tickets", +"tienda", +"tiffany", +"tips", +"tires", +"tirol", +"tjmaxx", +"tjx", +"tkmaxx", +"tmall", +"today", +"tokyo", +"tools", +"top", +"toray", +"toshiba", +"total", +"tours", +"town", +"toyota", +"toys", +"trade", +"trading", +"training", +"travel", +"travelchannel", +"travelers", +"travelersinsurance", +"trust", +"trv", +"tube", +"tui", +"tunes", +"tushu", +"tvs", +"ubank", +"ubs", +"unicom", +"university", +"uno", +"uol", +"ups", +"vacations", +"vana", +"vanguard", +"vegas", +"ventures", +"verisign", +"versicherung", +"vet", +"viajes", +"video", +"vig", +"viking", +"villas", +"vin", +"vip", +"virgin", +"visa", +"vision", +"viva", +"vivo", +"vlaanderen", +"vodka", +"volkswagen", +"volvo", +"vote", +"voting", +"voto", +"voyage", +"vuelos", +"wales", +"walmart", +"walter", +"wang", +"wanggou", +"watch", +"watches", +"weather", +"weatherchannel", +"webcam", +"weber", +"website", +"wed", +"wedding", +"weibo", +"weir", +"whoswho", +"wien", +"wiki", +"williamhill", +"win", +"windows", +"wine", +"winners", +"wme", +"wolterskluwer", +"woodside", +"work", +"works", +"world", +"wow", +"wtc", +"wtf", +"xbox", +"xerox", +"xfinity", +"xihuan", +"xin", +"कॉम", +"セール", +"佛山", +"慈善", +"集团", +"在线", +"大众汽车", +"点看", +"คอม", +"八卦", +"موقع", +"公益", +"公司", +"香格里拉", +"网站", +"移动", +"我爱你", +"москва", +"католик", +"онлайн", +"сайт", +"联通", +"קום", +"时尚", +"微博", +"淡马锡", +"ファッション", +"орг", +"नेट", +"ストア", +"アマゾン", +"삼성", +"商标", +"商店", +"商城", +"дети", +"ポイント", +"新闻", +"工行", +"家電", +"كوم", +"中文网", +"中信", +"娱乐", +"谷歌", +"電訊盈科", +"购物", +"クラウド", +"通販", +"网店", +"संगठन", +"餐厅", +"网络", +"ком", +"亚马逊", +"诺基亚", +"食品", +"飞利浦", +"手表", +"手机", +"ارامكو", +"العليان", +"اتصالات", +"بازار", +"ابوظبي", +"كاثوليك", +"همراه", +"닷컴", +"政府", +"شبكة", +"بيتك", +"عرب", +"机构", +"组织机构", +"健康", +"招聘", +"рус", +"珠宝", +"大拿", +"みんな", +"グーグル", +"世界", +"書籍", +"网址", +"닷넷", +"コム", +"天主教", +"游戏", +"vermögensberater", +"vermögensberatung", +"企业", +"信息", +"嘉里大酒店", +"嘉里", +"广东", +"政务", +"xyz", +"yachts", +"yahoo", +"yamaxun", +"yandex", +"yodobashi", +"yoga", +"yokohama", +"you", +"youtube", +"yun", +"zappos", +"zara", +"zero", +"zip", +"zone", +"zuerich", +"cc.ua", +"inf.ua", +"ltd.ua", +"adobeaemcloud.com", +"adobeaemcloud.net", +"*.dev.adobeaemcloud.com", +"beep.pl", +"barsy.ca", +"*.compute.estate", +"*.alces.network", +"altervista.org", +"alwaysdata.net", +"cloudfront.net", +"*.compute.amazonaws.com", +"*.compute-1.amazonaws.com", +"*.compute.amazonaws.com.cn", +"us-east-1.amazonaws.com", +"cn-north-1.eb.amazonaws.com.cn", +"cn-northwest-1.eb.amazonaws.com.cn", +"elasticbeanstalk.com", +"ap-northeast-1.elasticbeanstalk.com", +"ap-northeast-2.elasticbeanstalk.com", +"ap-northeast-3.elasticbeanstalk.com", +"ap-south-1.elasticbeanstalk.com", +"ap-southeast-1.elasticbeanstalk.com", +"ap-southeast-2.elasticbeanstalk.com", +"ca-central-1.elasticbeanstalk.com", +"eu-central-1.elasticbeanstalk.com", +"eu-west-1.elasticbeanstalk.com", +"eu-west-2.elasticbeanstalk.com", +"eu-west-3.elasticbeanstalk.com", +"sa-east-1.elasticbeanstalk.com", +"us-east-1.elasticbeanstalk.com", +"us-east-2.elasticbeanstalk.com", +"us-gov-west-1.elasticbeanstalk.com", +"us-west-1.elasticbeanstalk.com", +"us-west-2.elasticbeanstalk.com", +"*.elb.amazonaws.com", +"*.elb.amazonaws.com.cn", +"s3.amazonaws.com", +"s3-ap-northeast-1.amazonaws.com", +"s3-ap-northeast-2.amazonaws.com", +"s3-ap-south-1.amazonaws.com", +"s3-ap-southeast-1.amazonaws.com", +"s3-ap-southeast-2.amazonaws.com", +"s3-ca-central-1.amazonaws.com", +"s3-eu-central-1.amazonaws.com", +"s3-eu-west-1.amazonaws.com", +"s3-eu-west-2.amazonaws.com", +"s3-eu-west-3.amazonaws.com", +"s3-external-1.amazonaws.com", +"s3-fips-us-gov-west-1.amazonaws.com", +"s3-sa-east-1.amazonaws.com", +"s3-us-gov-west-1.amazonaws.com", +"s3-us-east-2.amazonaws.com", +"s3-us-west-1.amazonaws.com", +"s3-us-west-2.amazonaws.com", +"s3.ap-northeast-2.amazonaws.com", +"s3.ap-south-1.amazonaws.com", +"s3.cn-north-1.amazonaws.com.cn", +"s3.ca-central-1.amazonaws.com", +"s3.eu-central-1.amazonaws.com", +"s3.eu-west-2.amazonaws.com", +"s3.eu-west-3.amazonaws.com", +"s3.us-east-2.amazonaws.com", +"s3.dualstack.ap-northeast-1.amazonaws.com", +"s3.dualstack.ap-northeast-2.amazonaws.com", +"s3.dualstack.ap-south-1.amazonaws.com", +"s3.dualstack.ap-southeast-1.amazonaws.com", +"s3.dualstack.ap-southeast-2.amazonaws.com", +"s3.dualstack.ca-central-1.amazonaws.com", +"s3.dualstack.eu-central-1.amazonaws.com", +"s3.dualstack.eu-west-1.amazonaws.com", +"s3.dualstack.eu-west-2.amazonaws.com", +"s3.dualstack.eu-west-3.amazonaws.com", +"s3.dualstack.sa-east-1.amazonaws.com", +"s3.dualstack.us-east-1.amazonaws.com", +"s3.dualstack.us-east-2.amazonaws.com", +"s3-website-us-east-1.amazonaws.com", +"s3-website-us-west-1.amazonaws.com", +"s3-website-us-west-2.amazonaws.com", +"s3-website-ap-northeast-1.amazonaws.com", +"s3-website-ap-southeast-1.amazonaws.com", +"s3-website-ap-southeast-2.amazonaws.com", +"s3-website-eu-west-1.amazonaws.com", +"s3-website-sa-east-1.amazonaws.com", +"s3-website.ap-northeast-2.amazonaws.com", +"s3-website.ap-south-1.amazonaws.com", +"s3-website.ca-central-1.amazonaws.com", +"s3-website.eu-central-1.amazonaws.com", +"s3-website.eu-west-2.amazonaws.com", +"s3-website.eu-west-3.amazonaws.com", +"s3-website.us-east-2.amazonaws.com", +"amsw.nl", +"t3l3p0rt.net", +"tele.amune.org", +"apigee.io", +"on-aptible.com", +"user.aseinet.ne.jp", +"gv.vc", +"d.gv.vc", +"user.party.eus", +"pimienta.org", +"poivron.org", +"potager.org", +"sweetpepper.org", +"myasustor.com", +"myfritz.net", +"*.awdev.ca", +"*.advisor.ws", +"b-data.io", +"backplaneapp.io", +"balena-devices.com", +"app.banzaicloud.io", +"betainabox.com", +"bnr.la", +"blackbaudcdn.net", +"boomla.net", +"boxfuse.io", +"square7.ch", +"bplaced.com", +"bplaced.de", +"square7.de", +"bplaced.net", +"square7.net", +"browsersafetymark.io", +"uk0.bigv.io", +"dh.bytemark.co.uk", +"vm.bytemark.co.uk", +"mycd.eu", +"carrd.co", +"crd.co", +"uwu.ai", +"ae.org", +"ar.com", +"br.com", +"cn.com", +"com.de", +"com.se", +"de.com", +"eu.com", +"gb.com", +"gb.net", +"hu.com", +"hu.net", +"jp.net", +"jpn.com", +"kr.com", +"mex.com", +"no.com", +"qc.com", +"ru.com", +"sa.com", +"se.net", +"uk.com", +"uk.net", +"us.com", +"uy.com", +"za.bz", +"za.com", +"africa.com", +"gr.com", +"in.net", +"us.org", +"co.com", +"c.la", +"certmgr.org", +"xenapponazure.com", +"discourse.group", +"discourse.team", +"virtueeldomein.nl", +"cleverapps.io", +"*.lcl.dev", +"*.stg.dev", +"c66.me", +"cloud66.ws", +"cloud66.zone", +"jdevcloud.com", +"wpdevcloud.com", +"cloudaccess.host", +"freesite.host", +"cloudaccess.net", +"cloudcontrolled.com", +"cloudcontrolapp.com", +"cloudera.site", +"trycloudflare.com", +"workers.dev", +"wnext.app", +"co.ca", +"*.otap.co", +"co.cz", +"c.cdn77.org", +"cdn77-ssl.net", +"r.cdn77.net", +"rsc.cdn77.org", +"ssl.origin.cdn77-secure.org", +"cloudns.asia", +"cloudns.biz", +"cloudns.club", +"cloudns.cc", +"cloudns.eu", +"cloudns.in", +"cloudns.info", +"cloudns.org", +"cloudns.pro", +"cloudns.pw", +"cloudns.us", +"cloudeity.net", +"cnpy.gdn", +"co.nl", +"co.no", +"webhosting.be", +"hosting-cluster.nl", +"ac.ru", +"edu.ru", +"gov.ru", +"int.ru", +"mil.ru", +"test.ru", +"dyn.cosidns.de", +"dynamisches-dns.de", +"dnsupdater.de", +"internet-dns.de", +"l-o-g-i-n.de", +"dynamic-dns.info", +"feste-ip.net", +"knx-server.net", +"static-access.net", +"realm.cz", +"*.cryptonomic.net", +"cupcake.is", +"*.customer-oci.com", +"*.oci.customer-oci.com", +"*.ocp.customer-oci.com", +"*.ocs.customer-oci.com", +"cyon.link", +"cyon.site", +"daplie.me", +"localhost.daplie.me", +"dattolocal.com", +"dattorelay.com", +"dattoweb.com", +"mydatto.com", +"dattolocal.net", +"mydatto.net", +"biz.dk", +"co.dk", +"firm.dk", +"reg.dk", +"store.dk", +"*.dapps.earth", +"*.bzz.dapps.earth", +"builtwithdark.com", +"edgestack.me", +"debian.net", +"dedyn.io", +"dnshome.de", +"online.th", +"shop.th", +"drayddns.com", +"dreamhosters.com", +"mydrobo.com", +"drud.io", +"drud.us", +"duckdns.org", +"dy.fi", +"tunk.org", +"dyndns-at-home.com", +"dyndns-at-work.com", +"dyndns-blog.com", +"dyndns-free.com", +"dyndns-home.com", +"dyndns-ip.com", +"dyndns-mail.com", +"dyndns-office.com", +"dyndns-pics.com", +"dyndns-remote.com", +"dyndns-server.com", +"dyndns-web.com", +"dyndns-wiki.com", +"dyndns-work.com", +"dyndns.biz", +"dyndns.info", +"dyndns.org", +"dyndns.tv", +"at-band-camp.net", +"ath.cx", +"barrel-of-knowledge.info", +"barrell-of-knowledge.info", +"better-than.tv", +"blogdns.com", +"blogdns.net", +"blogdns.org", +"blogsite.org", +"boldlygoingnowhere.org", +"broke-it.net", +"buyshouses.net", +"cechire.com", +"dnsalias.com", +"dnsalias.net", +"dnsalias.org", +"dnsdojo.com", +"dnsdojo.net", +"dnsdojo.org", +"does-it.net", +"doesntexist.com", +"doesntexist.org", +"dontexist.com", +"dontexist.net", +"dontexist.org", +"doomdns.com", +"doomdns.org", +"dvrdns.org", +"dyn-o-saur.com", +"dynalias.com", +"dynalias.net", +"dynalias.org", +"dynathome.net", +"dyndns.ws", +"endofinternet.net", +"endofinternet.org", +"endoftheinternet.org", +"est-a-la-maison.com", +"est-a-la-masion.com", +"est-le-patron.com", +"est-mon-blogueur.com", +"for-better.biz", +"for-more.biz", +"for-our.info", +"for-some.biz", +"for-the.biz", +"forgot.her.name", +"forgot.his.name", +"from-ak.com", +"from-al.com", +"from-ar.com", +"from-az.net", +"from-ca.com", +"from-co.net", +"from-ct.com", +"from-dc.com", +"from-de.com", +"from-fl.com", +"from-ga.com", +"from-hi.com", +"from-ia.com", +"from-id.com", +"from-il.com", +"from-in.com", +"from-ks.com", +"from-ky.com", +"from-la.net", +"from-ma.com", +"from-md.com", +"from-me.org", +"from-mi.com", +"from-mn.com", +"from-mo.com", +"from-ms.com", +"from-mt.com", +"from-nc.com", +"from-nd.com", +"from-ne.com", +"from-nh.com", +"from-nj.com", +"from-nm.com", +"from-nv.com", +"from-ny.net", +"from-oh.com", +"from-ok.com", +"from-or.com", +"from-pa.com", +"from-pr.com", +"from-ri.com", +"from-sc.com", +"from-sd.com", +"from-tn.com", +"from-tx.com", +"from-ut.com", +"from-va.com", +"from-vt.com", +"from-wa.com", +"from-wi.com", +"from-wv.com", +"from-wy.com", +"ftpaccess.cc", +"fuettertdasnetz.de", +"game-host.org", +"game-server.cc", +"getmyip.com", +"gets-it.net", +"go.dyndns.org", +"gotdns.com", +"gotdns.org", +"groks-the.info", +"groks-this.info", +"ham-radio-op.net", +"here-for-more.info", +"hobby-site.com", +"hobby-site.org", +"home.dyndns.org", +"homedns.org", +"homeftp.net", +"homeftp.org", +"homeip.net", +"homelinux.com", +"homelinux.net", +"homelinux.org", +"homeunix.com", +"homeunix.net", +"homeunix.org", +"iamallama.com", +"in-the-band.net", +"is-a-anarchist.com", +"is-a-blogger.com", +"is-a-bookkeeper.com", +"is-a-bruinsfan.org", +"is-a-bulls-fan.com", +"is-a-candidate.org", +"is-a-caterer.com", +"is-a-celticsfan.org", +"is-a-chef.com", +"is-a-chef.net", +"is-a-chef.org", +"is-a-conservative.com", +"is-a-cpa.com", +"is-a-cubicle-slave.com", +"is-a-democrat.com", +"is-a-designer.com", +"is-a-doctor.com", +"is-a-financialadvisor.com", +"is-a-geek.com", +"is-a-geek.net", +"is-a-geek.org", +"is-a-green.com", +"is-a-guru.com", +"is-a-hard-worker.com", +"is-a-hunter.com", +"is-a-knight.org", +"is-a-landscaper.com", +"is-a-lawyer.com", +"is-a-liberal.com", +"is-a-libertarian.com", +"is-a-linux-user.org", +"is-a-llama.com", +"is-a-musician.com", +"is-a-nascarfan.com", +"is-a-nurse.com", +"is-a-painter.com", +"is-a-patsfan.org", +"is-a-personaltrainer.com", +"is-a-photographer.com", +"is-a-player.com", +"is-a-republican.com", +"is-a-rockstar.com", +"is-a-socialist.com", +"is-a-soxfan.org", +"is-a-student.com", +"is-a-teacher.com", +"is-a-techie.com", +"is-a-therapist.com", +"is-an-accountant.com", +"is-an-actor.com", +"is-an-actress.com", +"is-an-anarchist.com", +"is-an-artist.com", +"is-an-engineer.com", +"is-an-entertainer.com", +"is-by.us", +"is-certified.com", +"is-found.org", +"is-gone.com", +"is-into-anime.com", +"is-into-cars.com", +"is-into-cartoons.com", +"is-into-games.com", +"is-leet.com", +"is-lost.org", +"is-not-certified.com", +"is-saved.org", +"is-slick.com", +"is-uberleet.com", +"is-very-bad.org", +"is-very-evil.org", +"is-very-good.org", +"is-very-nice.org", +"is-very-sweet.org", +"is-with-theband.com", +"isa-geek.com", +"isa-geek.net", +"isa-geek.org", +"isa-hockeynut.com", +"issmarterthanyou.com", +"isteingeek.de", +"istmein.de", +"kicks-ass.net", +"kicks-ass.org", +"knowsitall.info", +"land-4-sale.us", +"lebtimnetz.de", +"leitungsen.de", +"likes-pie.com", +"likescandy.com", +"merseine.nu", +"mine.nu", +"misconfused.org", +"mypets.ws", +"myphotos.cc", +"neat-url.com", +"office-on-the.net", +"on-the-web.tv", +"podzone.net", +"podzone.org", +"readmyblog.org", +"saves-the-whales.com", +"scrapper-site.net", +"scrapping.cc", +"selfip.biz", +"selfip.com", +"selfip.info", +"selfip.net", +"selfip.org", +"sells-for-less.com", +"sells-for-u.com", +"sells-it.net", +"sellsyourhome.org", +"servebbs.com", +"servebbs.net", +"servebbs.org", +"serveftp.net", +"serveftp.org", +"servegame.org", +"shacknet.nu", +"simple-url.com", +"space-to-rent.com", +"stuff-4-sale.org", +"stuff-4-sale.us", +"teaches-yoga.com", +"thruhere.net", +"traeumtgerade.de", +"webhop.biz", +"webhop.info", +"webhop.net", +"webhop.org", +"worse-than.tv", +"writesthisblog.com", +"ddnss.de", +"dyn.ddnss.de", +"dyndns.ddnss.de", +"dyndns1.de", +"dyn-ip24.de", +"home-webserver.de", +"dyn.home-webserver.de", +"myhome-server.de", +"ddnss.org", +"definima.net", +"definima.io", +"bci.dnstrace.pro", +"ddnsfree.com", +"ddnsgeek.com", +"giize.com", +"gleeze.com", +"kozow.com", +"loseyourip.com", +"ooguy.com", +"theworkpc.com", +"casacam.net", +"dynu.net", +"accesscam.org", +"camdvr.org", +"freeddns.org", +"mywire.org", +"webredirect.org", +"myddns.rocks", +"blogsite.xyz", +"dynv6.net", +"e4.cz", +"en-root.fr", +"mytuleap.com", +"onred.one", +"staging.onred.one", +"enonic.io", +"customer.enonic.io", +"eu.org", +"al.eu.org", +"asso.eu.org", +"at.eu.org", +"au.eu.org", +"be.eu.org", +"bg.eu.org", +"ca.eu.org", +"cd.eu.org", +"ch.eu.org", +"cn.eu.org", +"cy.eu.org", +"cz.eu.org", +"de.eu.org", +"dk.eu.org", +"edu.eu.org", +"ee.eu.org", +"es.eu.org", +"fi.eu.org", +"fr.eu.org", +"gr.eu.org", +"hr.eu.org", +"hu.eu.org", +"ie.eu.org", +"il.eu.org", +"in.eu.org", +"int.eu.org", +"is.eu.org", +"it.eu.org", +"jp.eu.org", +"kr.eu.org", +"lt.eu.org", +"lu.eu.org", +"lv.eu.org", +"mc.eu.org", +"me.eu.org", +"mk.eu.org", +"mt.eu.org", +"my.eu.org", +"net.eu.org", +"ng.eu.org", +"nl.eu.org", +"no.eu.org", +"nz.eu.org", +"paris.eu.org", +"pl.eu.org", +"pt.eu.org", +"q-a.eu.org", +"ro.eu.org", +"ru.eu.org", +"se.eu.org", +"si.eu.org", +"sk.eu.org", +"tr.eu.org", +"uk.eu.org", +"us.eu.org", +"eu-1.evennode.com", +"eu-2.evennode.com", +"eu-3.evennode.com", +"eu-4.evennode.com", +"us-1.evennode.com", +"us-2.evennode.com", +"us-3.evennode.com", +"us-4.evennode.com", +"twmail.cc", +"twmail.net", +"twmail.org", +"mymailer.com.tw", +"url.tw", +"apps.fbsbx.com", +"ru.net", +"adygeya.ru", +"bashkiria.ru", +"bir.ru", +"cbg.ru", +"com.ru", +"dagestan.ru", +"grozny.ru", +"kalmykia.ru", +"kustanai.ru", +"marine.ru", +"mordovia.ru", +"msk.ru", +"mytis.ru", +"nalchik.ru", +"nov.ru", +"pyatigorsk.ru", +"spb.ru", +"vladikavkaz.ru", +"vladimir.ru", +"abkhazia.su", +"adygeya.su", +"aktyubinsk.su", +"arkhangelsk.su", +"armenia.su", +"ashgabad.su", +"azerbaijan.su", +"balashov.su", +"bashkiria.su", +"bryansk.su", +"bukhara.su", +"chimkent.su", +"dagestan.su", +"east-kazakhstan.su", +"exnet.su", +"georgia.su", +"grozny.su", +"ivanovo.su", +"jambyl.su", +"kalmykia.su", +"kaluga.su", +"karacol.su", +"karaganda.su", +"karelia.su", +"khakassia.su", +"krasnodar.su", +"kurgan.su", +"kustanai.su", +"lenug.su", +"mangyshlak.su", +"mordovia.su", +"msk.su", +"murmansk.su", +"nalchik.su", +"navoi.su", +"north-kazakhstan.su", +"nov.su", +"obninsk.su", +"penza.su", +"pokrovsk.su", +"sochi.su", +"spb.su", +"tashkent.su", +"termez.su", +"togliatti.su", +"troitsk.su", +"tselinograd.su", +"tula.su", +"tuva.su", +"vladikavkaz.su", +"vladimir.su", +"vologda.su", +"channelsdvr.net", +"u.channelsdvr.net", +"fastly-terrarium.com", +"fastlylb.net", +"map.fastlylb.net", +"freetls.fastly.net", +"map.fastly.net", +"a.prod.fastly.net", +"global.prod.fastly.net", +"a.ssl.fastly.net", +"b.ssl.fastly.net", +"global.ssl.fastly.net", +"fastpanel.direct", +"fastvps-server.com", +"fhapp.xyz", +"fedorainfracloud.org", +"fedorapeople.org", +"cloud.fedoraproject.org", +"app.os.fedoraproject.org", +"app.os.stg.fedoraproject.org", +"mydobiss.com", +"filegear.me", +"filegear-au.me", +"filegear-de.me", +"filegear-gb.me", +"filegear-ie.me", +"filegear-jp.me", +"filegear-sg.me", +"firebaseapp.com", +"flynnhub.com", +"flynnhosting.net", +"0e.vc", +"freebox-os.com", +"freeboxos.com", +"fbx-os.fr", +"fbxos.fr", +"freebox-os.fr", +"freeboxos.fr", +"freedesktop.org", +"*.futurecms.at", +"*.ex.futurecms.at", +"*.in.futurecms.at", +"futurehosting.at", +"futuremailing.at", +"*.ex.ortsinfo.at", +"*.kunden.ortsinfo.at", +"*.statics.cloud", +"service.gov.uk", +"gehirn.ne.jp", +"usercontent.jp", +"gentapps.com", +"lab.ms", +"github.io", +"githubusercontent.com", +"gitlab.io", +"glitch.me", +"lolipop.io", +"cloudapps.digital", +"london.cloudapps.digital", +"homeoffice.gov.uk", +"ro.im", +"shop.ro", +"goip.de", +"run.app", +"a.run.app", +"web.app", +"*.0emm.com", +"appspot.com", +"*.r.appspot.com", +"blogspot.ae", +"blogspot.al", +"blogspot.am", +"blogspot.ba", +"blogspot.be", +"blogspot.bg", +"blogspot.bj", +"blogspot.ca", +"blogspot.cf", +"blogspot.ch", +"blogspot.cl", +"blogspot.co.at", +"blogspot.co.id", +"blogspot.co.il", +"blogspot.co.ke", +"blogspot.co.nz", +"blogspot.co.uk", +"blogspot.co.za", +"blogspot.com", +"blogspot.com.ar", +"blogspot.com.au", +"blogspot.com.br", +"blogspot.com.by", +"blogspot.com.co", +"blogspot.com.cy", +"blogspot.com.ee", +"blogspot.com.eg", +"blogspot.com.es", +"blogspot.com.mt", +"blogspot.com.ng", +"blogspot.com.tr", +"blogspot.com.uy", +"blogspot.cv", +"blogspot.cz", +"blogspot.de", +"blogspot.dk", +"blogspot.fi", +"blogspot.fr", +"blogspot.gr", +"blogspot.hk", +"blogspot.hr", +"blogspot.hu", +"blogspot.ie", +"blogspot.in", +"blogspot.is", +"blogspot.it", +"blogspot.jp", +"blogspot.kr", +"blogspot.li", +"blogspot.lt", +"blogspot.lu", +"blogspot.md", +"blogspot.mk", +"blogspot.mr", +"blogspot.mx", +"blogspot.my", +"blogspot.nl", +"blogspot.no", +"blogspot.pe", +"blogspot.pt", +"blogspot.qa", +"blogspot.re", +"blogspot.ro", +"blogspot.rs", +"blogspot.ru", +"blogspot.se", +"blogspot.sg", +"blogspot.si", +"blogspot.sk", +"blogspot.sn", +"blogspot.td", +"blogspot.tw", +"blogspot.ug", +"blogspot.vn", +"cloudfunctions.net", +"cloud.goog", +"codespot.com", +"googleapis.com", +"googlecode.com", +"pagespeedmobilizer.com", +"publishproxy.com", +"withgoogle.com", +"withyoutube.com", +"awsmppl.com", +"fin.ci", +"free.hr", +"caa.li", +"ua.rs", +"conf.se", +"hs.zone", +"hs.run", +"hashbang.sh", +"hasura.app", +"hasura-app.io", +"hepforge.org", +"herokuapp.com", +"herokussl.com", +"myravendb.com", +"ravendb.community", +"ravendb.me", +"development.run", +"ravendb.run", +"bpl.biz", +"orx.biz", +"ng.city", +"biz.gl", +"ng.ink", +"col.ng", +"firm.ng", +"gen.ng", +"ltd.ng", +"ngo.ng", +"ng.school", +"sch.so", +"häkkinen.fi", +"*.moonscale.io", +"moonscale.net", +"iki.fi", +"dyn-berlin.de", +"in-berlin.de", +"in-brb.de", +"in-butter.de", +"in-dsl.de", +"in-dsl.net", +"in-dsl.org", +"in-vpn.de", +"in-vpn.net", +"in-vpn.org", +"biz.at", +"info.at", +"info.cx", +"ac.leg.br", +"al.leg.br", +"am.leg.br", +"ap.leg.br", +"ba.leg.br", +"ce.leg.br", +"df.leg.br", +"es.leg.br", +"go.leg.br", +"ma.leg.br", +"mg.leg.br", +"ms.leg.br", +"mt.leg.br", +"pa.leg.br", +"pb.leg.br", +"pe.leg.br", +"pi.leg.br", +"pr.leg.br", +"rj.leg.br", +"rn.leg.br", +"ro.leg.br", +"rr.leg.br", +"rs.leg.br", +"sc.leg.br", +"se.leg.br", +"sp.leg.br", +"to.leg.br", +"pixolino.com", +"ipifony.net", +"mein-iserv.de", +"test-iserv.de", +"iserv.dev", +"iobb.net", +"myjino.ru", +"*.hosting.myjino.ru", +"*.landing.myjino.ru", +"*.spectrum.myjino.ru", +"*.vps.myjino.ru", +"*.triton.zone", +"*.cns.joyent.com", +"js.org", +"kaas.gg", +"khplay.nl", +"keymachine.de", +"kinghost.net", +"uni5.net", +"knightpoint.systems", +"oya.to", +"co.krd", +"edu.krd", +"git-repos.de", +"lcube-server.de", +"svn-repos.de", +"leadpages.co", +"lpages.co", +"lpusercontent.com", +"lelux.site", +"co.business", +"co.education", +"co.events", +"co.financial", +"co.network", +"co.place", +"co.technology", +"app.lmpm.com", +"linkitools.space", +"linkyard.cloud", +"linkyard-cloud.ch", +"members.linode.com", +"nodebalancer.linode.com", +"we.bs", +"loginline.app", +"loginline.dev", +"loginline.io", +"loginline.services", +"loginline.site", +"krasnik.pl", +"leczna.pl", +"lubartow.pl", +"lublin.pl", +"poniatowa.pl", +"swidnik.pl", +"uklugs.org", +"glug.org.uk", +"lug.org.uk", +"lugs.org.uk", +"barsy.bg", +"barsy.co.uk", +"barsyonline.co.uk", +"barsycenter.com", +"barsyonline.com", +"barsy.club", +"barsy.de", +"barsy.eu", +"barsy.in", +"barsy.info", +"barsy.io", +"barsy.me", +"barsy.menu", +"barsy.mobi", +"barsy.net", +"barsy.online", +"barsy.org", +"barsy.pro", +"barsy.pub", +"barsy.shop", +"barsy.site", +"barsy.support", +"barsy.uk", +"*.magentosite.cloud", +"mayfirst.info", +"mayfirst.org", +"hb.cldmail.ru", +"miniserver.com", +"memset.net", +"cloud.metacentrum.cz", +"custom.metacentrum.cz", +"flt.cloud.muni.cz", +"usr.cloud.muni.cz", +"meteorapp.com", +"eu.meteorapp.com", +"co.pl", +"azurecontainer.io", +"azurewebsites.net", +"azure-mobile.net", +"cloudapp.net", +"mozilla-iot.org", +"bmoattachments.org", +"net.ru", +"org.ru", +"pp.ru", +"ui.nabu.casa", +"pony.club", +"of.fashion", +"on.fashion", +"of.football", +"in.london", +"of.london", +"for.men", +"and.mom", +"for.mom", +"for.one", +"for.sale", +"of.work", +"to.work", +"nctu.me", +"bitballoon.com", +"netlify.com", +"4u.com", +"ngrok.io", +"nh-serv.co.uk", +"nfshost.com", +"dnsking.ch", +"mypi.co", +"n4t.co", +"001www.com", +"ddnslive.com", +"myiphost.com", +"forumz.info", +"16-b.it", +"32-b.it", +"64-b.it", +"soundcast.me", +"tcp4.me", +"dnsup.net", +"hicam.net", +"now-dns.net", +"ownip.net", +"vpndns.net", +"dynserv.org", +"now-dns.org", +"x443.pw", +"now-dns.top", +"ntdll.top", +"freeddns.us", +"crafting.xyz", +"zapto.xyz", +"nsupdate.info", +"nerdpol.ovh", +"blogsyte.com", +"brasilia.me", +"cable-modem.org", +"ciscofreak.com", +"collegefan.org", +"couchpotatofries.org", +"damnserver.com", +"ddns.me", +"ditchyourip.com", +"dnsfor.me", +"dnsiskinky.com", +"dvrcam.info", +"dynns.com", +"eating-organic.net", +"fantasyleague.cc", +"geekgalaxy.com", +"golffan.us", +"health-carereform.com", +"homesecuritymac.com", +"homesecuritypc.com", +"hopto.me", +"ilovecollege.info", +"loginto.me", +"mlbfan.org", +"mmafan.biz", +"myactivedirectory.com", +"mydissent.net", +"myeffect.net", +"mymediapc.net", +"mypsx.net", +"mysecuritycamera.com", +"mysecuritycamera.net", +"mysecuritycamera.org", +"net-freaks.com", +"nflfan.org", +"nhlfan.net", +"no-ip.ca", +"no-ip.co.uk", +"no-ip.net", +"noip.us", +"onthewifi.com", +"pgafan.net", +"point2this.com", +"pointto.us", +"privatizehealthinsurance.net", +"quicksytes.com", +"read-books.org", +"securitytactics.com", +"serveexchange.com", +"servehumour.com", +"servep2p.com", +"servesarcasm.com", +"stufftoread.com", +"ufcfan.org", +"unusualperson.com", +"workisboring.com", +"3utilities.com", +"bounceme.net", +"ddns.net", +"ddnsking.com", +"gotdns.ch", +"hopto.org", +"myftp.biz", +"myftp.org", +"myvnc.com", +"no-ip.biz", +"no-ip.info", +"no-ip.org", +"noip.me", +"redirectme.net", +"servebeer.com", +"serveblog.net", +"servecounterstrike.com", +"serveftp.com", +"servegame.com", +"servehalflife.com", +"servehttp.com", +"serveirc.com", +"serveminecraft.net", +"servemp3.com", +"servepics.com", +"servequake.com", +"sytes.net", +"webhop.me", +"zapto.org", +"stage.nodeart.io", +"nodum.co", +"nodum.io", +"pcloud.host", +"nyc.mn", +"nom.ae", +"nom.af", +"nom.ai", +"nom.al", +"nym.by", +"nom.bz", +"nym.bz", +"nom.cl", +"nym.ec", +"nom.gd", +"nom.ge", +"nom.gl", +"nym.gr", +"nom.gt", +"nym.gy", +"nym.hk", +"nom.hn", +"nym.ie", +"nom.im", +"nom.ke", +"nym.kz", +"nym.la", +"nym.lc", +"nom.li", +"nym.li", +"nym.lt", +"nym.lu", +"nom.lv", +"nym.me", +"nom.mk", +"nym.mn", +"nym.mx", +"nom.nu", +"nym.nz", +"nym.pe", +"nym.pt", +"nom.pw", +"nom.qa", +"nym.ro", +"nom.rs", +"nom.si", +"nym.sk", +"nom.st", +"nym.su", +"nym.sx", +"nom.tj", +"nym.tw", +"nom.ug", +"nom.uy", +"nom.vc", +"nom.vg", +"static.observableusercontent.com", +"cya.gg", +"cloudycluster.net", +"nid.io", +"opencraft.hosting", +"operaunite.com", +"skygearapp.com", +"outsystemscloud.com", +"ownprovider.com", +"own.pm", +"ox.rs", +"oy.lc", +"pgfog.com", +"pagefrontapp.com", +"art.pl", +"gliwice.pl", +"krakow.pl", +"poznan.pl", +"wroc.pl", +"zakopane.pl", +"pantheonsite.io", +"gotpantheon.com", +"mypep.link", +"perspecta.cloud", +"on-web.fr", +"*.platform.sh", +"*.platformsh.site", +"dyn53.io", +"co.bn", +"xen.prgmr.com", +"priv.at", +"prvcy.page", +"*.dweb.link", +"protonet.io", +"chirurgiens-dentistes-en-france.fr", +"byen.site", +"pubtls.org", +"qualifioapp.com", +"qbuser.com", +"instantcloud.cn", +"ras.ru", +"qa2.com", +"qcx.io", +"*.sys.qcx.io", +"dev-myqnapcloud.com", +"alpha-myqnapcloud.com", +"myqnapcloud.com", +"*.quipelements.com", +"vapor.cloud", +"vaporcloud.io", +"rackmaze.com", +"rackmaze.net", +"*.on-k3s.io", +"*.on-rancher.cloud", +"*.on-rio.io", +"readthedocs.io", +"rhcloud.com", +"app.render.com", +"onrender.com", +"repl.co", +"repl.run", +"resindevice.io", +"devices.resinstaging.io", +"hzc.io", +"wellbeingzone.eu", +"ptplus.fit", +"wellbeingzone.co.uk", +"git-pages.rit.edu", +"sandcats.io", +"logoip.de", +"logoip.com", +"schokokeks.net", +"gov.scot", +"scrysec.com", +"firewall-gateway.com", +"firewall-gateway.de", +"my-gateway.de", +"my-router.de", +"spdns.de", +"spdns.eu", +"firewall-gateway.net", +"my-firewall.org", +"myfirewall.org", +"spdns.org", +"senseering.net", +"biz.ua", +"co.ua", +"pp.ua", +"shiftedit.io", +"myshopblocks.com", +"shopitsite.com", +"mo-siemens.io", +"1kapp.com", +"appchizi.com", +"applinzi.com", +"sinaapp.com", +"vipsinaapp.com", +"siteleaf.net", +"bounty-full.com", +"alpha.bounty-full.com", +"beta.bounty-full.com", +"stackhero-network.com", +"static.land", +"dev.static.land", +"sites.static.land", +"apps.lair.io", +"*.stolos.io", +"spacekit.io", +"customer.speedpartner.de", +"api.stdlib.com", +"storj.farm", +"utwente.io", +"soc.srcf.net", +"user.srcf.net", +"temp-dns.com", +"applicationcloud.io", +"scapp.io", +"*.s5y.io", +"*.sensiosite.cloud", +"syncloud.it", +"diskstation.me", +"dscloud.biz", +"dscloud.me", +"dscloud.mobi", +"dsmynas.com", +"dsmynas.net", +"dsmynas.org", +"familyds.com", +"familyds.net", +"familyds.org", +"i234.me", +"myds.me", +"synology.me", +"vpnplus.to", +"direct.quickconnect.to", +"taifun-dns.de", +"gda.pl", +"gdansk.pl", +"gdynia.pl", +"med.pl", +"sopot.pl", +"edugit.org", +"telebit.app", +"telebit.io", +"*.telebit.xyz", +"gwiddle.co.uk", +"thingdustdata.com", +"cust.dev.thingdust.io", +"cust.disrec.thingdust.io", +"cust.prod.thingdust.io", +"cust.testing.thingdust.io", +"arvo.network", +"azimuth.network", +"bloxcms.com", +"townnews-staging.com", +"12hp.at", +"2ix.at", +"4lima.at", +"lima-city.at", +"12hp.ch", +"2ix.ch", +"4lima.ch", +"lima-city.ch", +"trafficplex.cloud", +"de.cool", +"12hp.de", +"2ix.de", +"4lima.de", +"lima-city.de", +"1337.pictures", +"clan.rip", +"lima-city.rocks", +"webspace.rocks", +"lima.zone", +"*.transurl.be", +"*.transurl.eu", +"*.transurl.nl", +"tuxfamily.org", +"dd-dns.de", +"diskstation.eu", +"diskstation.org", +"dray-dns.de", +"draydns.de", +"dyn-vpn.de", +"dynvpn.de", +"mein-vigor.de", +"my-vigor.de", +"my-wan.de", +"syno-ds.de", +"synology-diskstation.de", +"synology-ds.de", +"uber.space", +"*.uberspace.de", +"hk.com", +"hk.org", +"ltd.hk", +"inc.hk", +"virtualuser.de", +"virtual-user.de", +"urown.cloud", +"dnsupdate.info", +"lib.de.us", +"2038.io", +"router.management", +"v-info.info", +"voorloper.cloud", +"v.ua", +"wafflecell.com", +"*.webhare.dev", +"wedeploy.io", +"wedeploy.me", +"wedeploy.sh", +"remotewd.com", +"wmflabs.org", +"myforum.community", +"community-pro.de", +"diskussionsbereich.de", +"community-pro.net", +"meinforum.net", +"half.host", +"xnbay.com", +"u2.xnbay.com", +"u2-local.xnbay.com", +"cistron.nl", +"demon.nl", +"xs4all.space", +"yandexcloud.net", +"storage.yandexcloud.net", +"website.yandexcloud.net", +"official.academy", +"yolasite.com", +"ybo.faith", +"yombo.me", +"homelink.one", +"ybo.party", +"ybo.review", +"ybo.science", +"ybo.trade", +"nohost.me", +"noho.st", +"za.net", +"za.org", +"now.sh", +"bss.design", +"basicserver.io", +"virtualserver.io", +"enterprisecloud.nu" +] \ No newline at end of file diff --git a/node_modules/psl/dist/psl.js b/node_modules/psl/dist/psl.js new file mode 100644 index 0000000..f4b9b89 --- /dev/null +++ b/node_modules/psl/dist/psl.js @@ -0,0 +1,9645 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.psl = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i= punySuffix.length) { + // return memo; + // } + //} + return rule; + }, null); +}; + + +// +// Error codes and messages. +// +exports.errorCodes = { + DOMAIN_TOO_SHORT: 'Domain name too short.', + DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', + LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', + LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', + LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', + LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', + LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' +}; + + +// +// Validate domain name and throw if not valid. +// +// From wikipedia: +// +// Hostnames are composed of series of labels concatenated with dots, as are all +// domain names. Each label must be between 1 and 63 characters long, and the +// entire hostname (including the delimiting dots) has a maximum of 255 chars. +// +// Allowed chars: +// +// * `a-z` +// * `0-9` +// * `-` but not as a starting or ending character +// * `.` as a separator for the textual portions of a domain name +// +// * http://en.wikipedia.org/wiki/Domain_name +// * http://en.wikipedia.org/wiki/Hostname +// +internals.validate = function (input) { + + // Before we can validate we need to take care of IDNs with unicode chars. + var ascii = Punycode.toASCII(input); + + if (ascii.length < 1) { + return 'DOMAIN_TOO_SHORT'; + } + if (ascii.length > 255) { + return 'DOMAIN_TOO_LONG'; + } + + // Check each part's length and allowed chars. + var labels = ascii.split('.'); + var label; + + for (var i = 0; i < labels.length; ++i) { + label = labels[i]; + if (!label.length) { + return 'LABEL_TOO_SHORT'; + } + if (label.length > 63) { + return 'LABEL_TOO_LONG'; + } + if (label.charAt(0) === '-') { + return 'LABEL_STARTS_WITH_DASH'; + } + if (label.charAt(label.length - 1) === '-') { + return 'LABEL_ENDS_WITH_DASH'; + } + if (!/^[a-z0-9\-]+$/.test(label)) { + return 'LABEL_INVALID_CHARS'; + } + } +}; + + +// +// Public API +// + + +// +// Parse domain. +// +exports.parse = function (input) { + + if (typeof input !== 'string') { + throw new TypeError('Domain name must be a string.'); + } + + // Force domain to lowercase. + var domain = input.slice(0).toLowerCase(); + + // Handle FQDN. + // TODO: Simply remove trailing dot? + if (domain.charAt(domain.length - 1) === '.') { + domain = domain.slice(0, domain.length - 1); + } + + // Validate and sanitise input. + var error = internals.validate(domain); + if (error) { + return { + input: input, + error: { + message: exports.errorCodes[error], + code: error + } + }; + } + + var parsed = { + input: input, + tld: null, + sld: null, + domain: null, + subdomain: null, + listed: false + }; + + var domainParts = domain.split('.'); + + // Non-Internet TLD + if (domainParts[domainParts.length - 1] === 'local') { + return parsed; + } + + var handlePunycode = function () { + + if (!/xn--/.test(domain)) { + return parsed; + } + if (parsed.domain) { + parsed.domain = Punycode.toASCII(parsed.domain); + } + if (parsed.subdomain) { + parsed.subdomain = Punycode.toASCII(parsed.subdomain); + } + return parsed; + }; + + var rule = internals.findRule(domain); + + // Unlisted tld. + if (!rule) { + if (domainParts.length < 2) { + return parsed; + } + parsed.tld = domainParts.pop(); + parsed.sld = domainParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + if (domainParts.length) { + parsed.subdomain = domainParts.pop(); + } + return handlePunycode(); + } + + // At this point we know the public suffix is listed. + parsed.listed = true; + + var tldParts = rule.suffix.split('.'); + var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); + + if (rule.exception) { + privateParts.push(tldParts.shift()); + } + + parsed.tld = tldParts.join('.'); + + if (!privateParts.length) { + return handlePunycode(); + } + + if (rule.wildcard) { + tldParts.unshift(privateParts.pop()); + parsed.tld = tldParts.join('.'); + } + + if (!privateParts.length) { + return handlePunycode(); + } + + parsed.sld = privateParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + + if (privateParts.length) { + parsed.subdomain = privateParts.join('.'); + } + + return handlePunycode(); +}; + + +// +// Get domain. +// +exports.get = function (domain) { + + if (!domain) { + return null; + } + return exports.parse(domain).domain || null; +}; + + +// +// Check whether domain belongs to a known public suffix. +// +exports.isValid = function (domain) { + + var parsed = exports.parse(domain); + return Boolean(parsed.domain && parsed.listed); +}; + +},{"./data/rules.json":1,"punycode":3}],3:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}]},{},[2])(2) +}); diff --git a/node_modules/psl/dist/psl.min.js b/node_modules/psl/dist/psl.min.js new file mode 100644 index 0000000..d5c787e --- /dev/null +++ b/node_modules/psl/dist/psl.min.js @@ -0,0 +1 @@ +!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).psl=a()}}(function(){return function s(m,t,u){function r(o,a){if(!t[o]){if(!m[o]){var i="function"==typeof require&&require;if(!a&&i)return i(o,!0);if(p)return p(o,!0);var e=new Error("Cannot find module '"+o+"'");throw e.code="MODULE_NOT_FOUND",e}var n=t[o]={exports:{}};m[o][0].call(n.exports,function(a){return r(m[o][1][a]||a)},n,n.exports,s,m,t,u)}return t[o].exports}for(var p="function"==typeof require&&require,a=0;a= 0x80 (not a basic code point)","invalid-input":"Invalid input"},c=b-y,x=Math.floor,q=String.fromCharCode;function A(a){throw new RangeError(k[a])}function l(a,o){for(var i=a.length,e=[];i--;)e[i]=o(a[i]);return e}function g(a,o){var i=a.split("@"),e="";return 1>>10&1023|55296),a=56320|1023&a),o+=q(a)}).join("")}function L(a,o){return a+22+75*(a<26)-((0!=o)<<5)}function I(a,o,i){var e=0;for(a=i?x(a/t):a>>1,a+=x(a/o);c*f>>1x((d-g)/m))&&A("overflow"),g+=u*m,!(u<(r=t<=j?y:j+f<=t?f:t-j));t+=b)m>x(d/(p=b-r))&&A("overflow"),m*=p;j=I(g-s,o=c.length+1,0==s),x(g/o)>d-h&&A("overflow"),h+=x(g/o),g%=o,c.splice(g++,0,h)}return _(c)}function j(a){var o,i,e,n,s,m,t,u,r,p,k,c,l,g,h,j=[];for(c=(a=O(a)).length,o=w,s=v,m=i=0;mx((d-i)/(l=e+1))&&A("overflow"),i+=(t-o)*l,o=t,m=0;md&&A("overflow"),k==o){for(u=i,r=b;!(u<(p=r<=s?y:s+f<=r?f:r-s));r+=b)h=u-p,g=b-p,j.push(q(L(p+h%g,0))),u=x(h/g);j.push(q(L(u,0))),s=I(i,l,e==n),i=0,++e}++i,++o}return j.join("")}if(n={version:"1.4.1",ucs2:{decode:O,encode:_},decode:h,encode:j,toASCII:function(a){return g(a,function(a){return r.test(a)?"xn--"+j(a):a})},toUnicode:function(a){return g(a,function(a){return u.test(a)?h(a.slice(4).toLowerCase()):a})}},0,o&&i)if(T.exports==o)i.exports=n;else for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);else a.punycode=n}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[2])(2)}); diff --git a/node_modules/psl/index.js b/node_modules/psl/index.js new file mode 100644 index 0000000..da7bc12 --- /dev/null +++ b/node_modules/psl/index.js @@ -0,0 +1,269 @@ +/*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */ +'use strict'; + + +var Punycode = require('punycode'); + + +var internals = {}; + + +// +// Read rules from file. +// +internals.rules = require('./data/rules.json').map(function (rule) { + + return { + rule: rule, + suffix: rule.replace(/^(\*\.|\!)/, ''), + punySuffix: -1, + wildcard: rule.charAt(0) === '*', + exception: rule.charAt(0) === '!' + }; +}); + + +// +// Check is given string ends with `suffix`. +// +internals.endsWith = function (str, suffix) { + + return str.indexOf(suffix, str.length - suffix.length) !== -1; +}; + + +// +// Find rule for a given domain. +// +internals.findRule = function (domain) { + + var punyDomain = Punycode.toASCII(domain); + return internals.rules.reduce(function (memo, rule) { + + if (rule.punySuffix === -1){ + rule.punySuffix = Punycode.toASCII(rule.suffix); + } + if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) { + return memo; + } + // This has been commented out as it never seems to run. This is because + // sub tlds always appear after their parents and we never find a shorter + // match. + //if (memo) { + // var memoSuffix = Punycode.toASCII(memo.suffix); + // if (memoSuffix.length >= punySuffix.length) { + // return memo; + // } + //} + return rule; + }, null); +}; + + +// +// Error codes and messages. +// +exports.errorCodes = { + DOMAIN_TOO_SHORT: 'Domain name too short.', + DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', + LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', + LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', + LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', + LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', + LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' +}; + + +// +// Validate domain name and throw if not valid. +// +// From wikipedia: +// +// Hostnames are composed of series of labels concatenated with dots, as are all +// domain names. Each label must be between 1 and 63 characters long, and the +// entire hostname (including the delimiting dots) has a maximum of 255 chars. +// +// Allowed chars: +// +// * `a-z` +// * `0-9` +// * `-` but not as a starting or ending character +// * `.` as a separator for the textual portions of a domain name +// +// * http://en.wikipedia.org/wiki/Domain_name +// * http://en.wikipedia.org/wiki/Hostname +// +internals.validate = function (input) { + + // Before we can validate we need to take care of IDNs with unicode chars. + var ascii = Punycode.toASCII(input); + + if (ascii.length < 1) { + return 'DOMAIN_TOO_SHORT'; + } + if (ascii.length > 255) { + return 'DOMAIN_TOO_LONG'; + } + + // Check each part's length and allowed chars. + var labels = ascii.split('.'); + var label; + + for (var i = 0; i < labels.length; ++i) { + label = labels[i]; + if (!label.length) { + return 'LABEL_TOO_SHORT'; + } + if (label.length > 63) { + return 'LABEL_TOO_LONG'; + } + if (label.charAt(0) === '-') { + return 'LABEL_STARTS_WITH_DASH'; + } + if (label.charAt(label.length - 1) === '-') { + return 'LABEL_ENDS_WITH_DASH'; + } + if (!/^[a-z0-9\-]+$/.test(label)) { + return 'LABEL_INVALID_CHARS'; + } + } +}; + + +// +// Public API +// + + +// +// Parse domain. +// +exports.parse = function (input) { + + if (typeof input !== 'string') { + throw new TypeError('Domain name must be a string.'); + } + + // Force domain to lowercase. + var domain = input.slice(0).toLowerCase(); + + // Handle FQDN. + // TODO: Simply remove trailing dot? + if (domain.charAt(domain.length - 1) === '.') { + domain = domain.slice(0, domain.length - 1); + } + + // Validate and sanitise input. + var error = internals.validate(domain); + if (error) { + return { + input: input, + error: { + message: exports.errorCodes[error], + code: error + } + }; + } + + var parsed = { + input: input, + tld: null, + sld: null, + domain: null, + subdomain: null, + listed: false + }; + + var domainParts = domain.split('.'); + + // Non-Internet TLD + if (domainParts[domainParts.length - 1] === 'local') { + return parsed; + } + + var handlePunycode = function () { + + if (!/xn--/.test(domain)) { + return parsed; + } + if (parsed.domain) { + parsed.domain = Punycode.toASCII(parsed.domain); + } + if (parsed.subdomain) { + parsed.subdomain = Punycode.toASCII(parsed.subdomain); + } + return parsed; + }; + + var rule = internals.findRule(domain); + + // Unlisted tld. + if (!rule) { + if (domainParts.length < 2) { + return parsed; + } + parsed.tld = domainParts.pop(); + parsed.sld = domainParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + if (domainParts.length) { + parsed.subdomain = domainParts.pop(); + } + return handlePunycode(); + } + + // At this point we know the public suffix is listed. + parsed.listed = true; + + var tldParts = rule.suffix.split('.'); + var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); + + if (rule.exception) { + privateParts.push(tldParts.shift()); + } + + parsed.tld = tldParts.join('.'); + + if (!privateParts.length) { + return handlePunycode(); + } + + if (rule.wildcard) { + tldParts.unshift(privateParts.pop()); + parsed.tld = tldParts.join('.'); + } + + if (!privateParts.length) { + return handlePunycode(); + } + + parsed.sld = privateParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + + if (privateParts.length) { + parsed.subdomain = privateParts.join('.'); + } + + return handlePunycode(); +}; + + +// +// Get domain. +// +exports.get = function (domain) { + + if (!domain) { + return null; + } + return exports.parse(domain).domain || null; +}; + + +// +// Check whether domain belongs to a known public suffix. +// +exports.isValid = function (domain) { + + var parsed = exports.parse(domain); + return Boolean(parsed.domain && parsed.listed); +}; diff --git a/node_modules/psl/package.json b/node_modules/psl/package.json new file mode 100644 index 0000000..9652c2c --- /dev/null +++ b/node_modules/psl/package.json @@ -0,0 +1,80 @@ +{ + "_args": [ + [ + "psl@1.8.0", + "/home/other/discord_bot" + ] + ], + "_from": "psl@1.8.0", + "_id": "psl@1.8.0", + "_inBundle": false, + "_integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==", + "_location": "/psl", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "psl@1.8.0", + "name": "psl", + "escapedName": "psl", + "rawSpec": "1.8.0", + "saveSpec": null, + "fetchSpec": "1.8.0" + }, + "_requiredBy": [ + "/tough-cookie" + ], + "_resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", + "_spec": "1.8.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Lupo Montero", + "email": "lupomontero@gmail.com", + "url": "https://lupomontero.com/" + }, + "bugs": { + "url": "https://github.com/lupomontero/psl/issues" + }, + "description": "Domain name parser based on the Public Suffix List", + "devDependencies": { + "JSONStream": "^1.3.5", + "browserify": "^16.5.0", + "commit-and-pr": "^1.0.4", + "eslint": "^6.8.0", + "eslint-config-hapi": "^12.0.0", + "eslint-plugin-hapi": "^4.1.0", + "karma": "^4.4.1", + "karma-browserify": "^7.0.0", + "karma-mocha": "^1.3.0", + "karma-mocha-reporter": "^2.2.5", + "karma-phantomjs-launcher": "^1.0.4", + "mocha": "^7.1.1", + "phantomjs-prebuilt": "^2.1.16", + "request": "^2.88.2", + "uglify-js": "^3.8.0", + "watchify": "^3.11.1" + }, + "homepage": "https://github.com/lupomontero/psl#readme", + "keywords": [ + "publicsuffix", + "publicsuffixlist" + ], + "license": "MIT", + "main": "index.js", + "name": "psl", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/lupomontero/psl.git" + }, + "scripts": { + "build": "browserify ./index.js --standalone=psl > ./dist/psl.js", + "changelog": "git log $(git describe --tags --abbrev=0)..HEAD --oneline --format=\"%h %s (%an <%ae>)\"", + "commit-and-pr": "commit-and-pr", + "postbuild": "cat ./dist/psl.js | uglifyjs -c -m > ./dist/psl.min.js", + "prebuild": "./scripts/update-rules.js", + "pretest": "eslint .", + "test": "mocha test && karma start ./karma.conf.js --single-run", + "watch": "mocha test --watch" + }, + "version": "1.8.0" +} diff --git a/node_modules/pstree.remy/.travis.yml b/node_modules/pstree.remy/.travis.yml new file mode 100644 index 0000000..5bf093e --- /dev/null +++ b/node_modules/pstree.remy/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +cache: + directories: + - ~/.npm +notifications: + email: false +node_js: + - '8' diff --git a/node_modules/pstree.remy/LICENSE b/node_modules/pstree.remy/LICENSE new file mode 100644 index 0000000..e83bea6 --- /dev/null +++ b/node_modules/pstree.remy/LICENSE @@ -0,0 +1,7 @@ +The MIT License (MIT) +Copyright © 2019 Remy Sharp, https://remysharp.com +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/pstree.remy/README.md b/node_modules/pstree.remy/README.md new file mode 100644 index 0000000..5f44c62 --- /dev/null +++ b/node_modules/pstree.remy/README.md @@ -0,0 +1,26 @@ +# pstree.remy + +> Cross platform ps-tree (including unix flavours without ps) + +## Installation + +```shel +npm install pstree.remy +``` + +## Usage + +```js +const psTree = psTree require('pstree.remy'); + +psTree(PID, (err, pids) => { + if (err) { + console.error(err); + } + console.log(pids) +}); + +console.log(psTree.hasPS + ? "This platform has the ps shell command" + : "This platform does not have the ps shell command"); +``` diff --git a/node_modules/pstree.remy/lib/index.js b/node_modules/pstree.remy/lib/index.js new file mode 100644 index 0000000..743e997 --- /dev/null +++ b/node_modules/pstree.remy/lib/index.js @@ -0,0 +1,37 @@ +const exec = require('child_process').exec; +const tree = require('./tree'); +const utils = require('./utils'); +var hasPS = true; + +// discover if the OS has `ps`, and therefore can use psTree +exec('ps', (error) => { + module.exports.hasPS = hasPS = !error; +}); + +module.exports = function main(pid, callback) { + if (typeof pid === 'number') { + pid = pid.toString(); + } + + if (hasPS && !process.env.NO_PS) { + return tree(pid, callback); + } + + utils + .getStat() + .then(utils.tree) + .then((tree) => utils.pidsForTree(tree, pid)) + .then((res) => + callback( + null, + res.map((p) => p.PID) + ) + ) + .catch((error) => callback(error)); +}; + +if (!module.parent) { + module.exports(process.argv[2], (e, pids) => console.log(pids)); +} + +module.exports.hasPS = hasPS; diff --git a/node_modules/pstree.remy/lib/tree.js b/node_modules/pstree.remy/lib/tree.js new file mode 100644 index 0000000..bac7cce --- /dev/null +++ b/node_modules/pstree.remy/lib/tree.js @@ -0,0 +1,37 @@ +const spawn = require('child_process').spawn; + +module.exports = function (rootPid, callback) { + const pidsOfInterest = new Set([parseInt(rootPid, 10)]); + var output = ''; + + // *nix + const ps = spawn('ps', ['-A', '-o', 'ppid,pid']); + ps.stdout.on('data', (data) => { + output += data.toString('ascii'); + }); + + ps.on('close', () => { + try { + const res = output + .split('\n') + .slice(1) + .map((_) => _.trim()) + .reduce((acc, line) => { + const pids = line.split(/\s+/); + const ppid = parseInt(pids[0], 10); + + if (pidsOfInterest.has(ppid)) { + const pid = parseInt(pids[1], 10); + acc.push(pid); + pidsOfInterest.add(pid); + } + + return acc; + }, []); + + callback(null, res); + } catch (e) { + callback(e, null); + } + }); +}; diff --git a/node_modules/pstree.remy/lib/utils.js b/node_modules/pstree.remy/lib/utils.js new file mode 100644 index 0000000..8fa5719 --- /dev/null +++ b/node_modules/pstree.remy/lib/utils.js @@ -0,0 +1,53 @@ +const spawn = require('child_process').spawn; + +module.exports = { tree, pidsForTree, getStat }; + +function getStat() { + return new Promise((resolve) => { + const command = `ls /proc | grep -E '^[0-9]+$' | xargs -I{} cat /proc/{}/stat`; + const spawned = spawn('sh', ['-c', command], { + stdio: ['pipe', 'pipe', 'pipe'], + }); + + var res = ''; + spawned.stdout.on('data', (data) => (res += data)); + spawned.on('close', () => resolve(res)); + }); +} + +function template(s) { + var stat = null; + // 'pid', 'comm', 'state', 'ppid', 'pgrp' + // %d (%s) %c %d %d + s.replace( + /(\d+) \((.*?)\)\s(.+?)\s(\d+)\s/g, + (all, PID, COMMAND, STAT, PPID) => { + stat = { PID, COMMAND, PPID, STAT }; + } + ); + + return stat; +} + +function tree(stats) { + const processes = stats.split('\n').map(template).filter(Boolean); + + return processes; +} + +function pidsForTree(tree, pid) { + if (typeof pid === 'number') { + pid = pid.toString(); + } + const parents = [pid]; + const pids = []; + + tree.forEach((proc) => { + if (parents.indexOf(proc.PPID) !== -1) { + parents.push(proc.PID); + pids.push(proc); + } + }); + + return pids; +} diff --git a/node_modules/pstree.remy/package.json b/node_modules/pstree.remy/package.json new file mode 100644 index 0000000..95e7829 --- /dev/null +++ b/node_modules/pstree.remy/package.json @@ -0,0 +1,67 @@ +{ + "_args": [ + [ + "pstree.remy@1.1.8", + "/home/other/discord_bot" + ] + ], + "_from": "pstree.remy@1.1.8", + "_id": "pstree.remy@1.1.8", + "_inBundle": false, + "_integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", + "_location": "/pstree.remy", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "pstree.remy@1.1.8", + "name": "pstree.remy", + "escapedName": "pstree.remy", + "rawSpec": "1.1.8", + "saveSpec": null, + "fetchSpec": "1.1.8" + }, + "_requiredBy": [ + "/nodemon" + ], + "_resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "_spec": "1.1.8", + "_where": "/home/other/discord_bot", + "author": { + "name": "Remy Sharp" + }, + "bugs": { + "url": "https://github.com/remy/pstree/issues" + }, + "dependencies": {}, + "description": "Collects the full tree of processes from /proc", + "devDependencies": { + "tap": "^11.0.0" + }, + "directories": { + "test": "tests" + }, + "homepage": "https://github.com/remy/pstree#readme", + "keywords": [ + "ps", + "pstree", + "ps tree" + ], + "license": "MIT", + "main": "lib/index.js", + "name": "pstree.remy", + "prettier": { + "trailingComma": "es5", + "semi": true, + "singleQuote": true + }, + "repository": { + "type": "git", + "url": "git+https://github.com/remy/pstree.git" + }, + "scripts": { + "_prepublish": "npm test", + "test": "tap tests/*.test.js" + }, + "version": "1.1.8" +} diff --git a/node_modules/pstree.remy/tests/fixtures/index.js b/node_modules/pstree.remy/tests/fixtures/index.js new file mode 100644 index 0000000..4cdbcb1 --- /dev/null +++ b/node_modules/pstree.remy/tests/fixtures/index.js @@ -0,0 +1,13 @@ +const spawn = require('child_process').spawn; +function run() { + spawn( + 'sh', + ['-c', 'node -e "setInterval(() => console.log(`running`), 200)"'], + { + stdio: 'pipe', + } + ); +} + +var runCallCount = process.argv[2] || 1; +for (var i = 0; i < runCallCount; i++) run(); diff --git a/node_modules/pstree.remy/tests/fixtures/out1 b/node_modules/pstree.remy/tests/fixtures/out1 new file mode 100644 index 0000000..abfe581 --- /dev/null +++ b/node_modules/pstree.remy/tests/fixtures/out1 @@ -0,0 +1,10 @@ +1 (npm) S 0 1 1 34816 1 4210944 11112 0 0 0 45 8 0 0 20 0 10 0 330296 1089871872 11809 18446744073709551615 4194304 29343848 140726436642896 0 0 0 0 4096 2072112895 0 0 0 17 0 0 0 0 0 0 31441000 31537208 37314560 140726436650815 140726436650847 140726436650847 140726436650986 0 +15 (sh) S 1 1 1 34816 1 4210688 115 0 0 0 0 0 0 0 20 0 1 0 330372 4399104 187 18446744073709551615 94374393548800 94374393655428 140722913272992 0 0 0 0 0 65538 0 0 0 17 0 0 0 0 0 0 94374395756424 94374395761184 94374404673536 140722913278928 140722913278959 140722913278959 140722913284080 0 +16 (node) S 15 1 1 34816 1 4210688 6930 103 0 0 32 2 0 0 20 0 10 0 330373 1068478464 8412 18446744073709551615 4194304 29343848 140727228046064 0 0 0 0 4096 134300162 0 0 0 17 1 0 0 1 0 0 31441000 31537208 52584448 140727228050313 140727228050383 140727228050383 140727228055530 0 +27 (sh) S 16 1 1 34816 1 4210688 111 0 0 0 0 0 0 0 20 0 1 0 330410 4399104 193 18446744073709551615 94848235986944 94848236093572 140727019991184 0 0 0 0 0 65538 0 0 0 17 1 0 0 0 0 0 94848238194568 94848238199328 94848261660672 140727019998122 140727019998165 140727019998165 140727020003312 0 +28 (node) S 27 1 1 34816 1 4210688 3576 268 0 0 12 2 0 0 20 0 10 0 330411 930213888 6760 18446744073709551615 4194304 29343848 140726559664992 0 0 0 0 4096 134300162 0 0 0 17 1 0 0 0 0 0 31441000 31537208 32591872 140726559669117 140726559669199 140726559669199 140726559674346 0 +39 (node) S 28 1 1 34816 1 4210688 47517 0 0 0 151 9 0 0 20 0 6 0 330427 985739264 31859 18446744073709551615 4194304 29343848 140737324503920 0 0 0 0 4096 134234626 0 0 0 17 0 0 0 0 0 0 31441000 31537208 51585024 140737324510060 140737324510159 140737324510159 140737324515306 0 +45 (bash) S 0 45 45 34817 50 4210944 752 256 0 0 2 0 0 0 20 0 1 0 331039 18628608 789 18446744073709551615 4194304 5242124 140724425887696 0 0 0 65536 3670020 1266777851 0 0 0 17 1 0 0 0 0 0 7341384 7388228 30310400 140724425891678 140724425891683 140724425891683 140724425891822 0 +cat: /proc/50/stat: No such file or directory +cat: /proc/51/stat: No such file or directory +52 (xargs) S 45 50 45 34817 50 4210688 179 661 0 0 0 0 0 0 20 0 1 0 331544 4608000 346 18446744073709551615 94587588550656 94587588614028 140735223856048 0 0 0 0 0 2560 0 0 0 17 1 0 0 0 0 0 94587590711464 94587590713504 94587603169280 140735223861006 140735223861035 140735223861035 140735223861225 0 diff --git a/node_modules/pstree.remy/tests/fixtures/out2 b/node_modules/pstree.remy/tests/fixtures/out2 new file mode 100644 index 0000000..3b31137 --- /dev/null +++ b/node_modules/pstree.remy/tests/fixtures/out2 @@ -0,0 +1,29 @@ +cat: /proc/4087/stat: No such file or directory +cat: /proc/4088/stat: No such file or directory +1 (init) S 0 1 1 0 -1 4210944 9227 55994 29 319 7 5 68 16 20 0 1 0 1286281 33660928 855 18446744073709551615 1 1 0 0 0 0 0 4096 536962595 0 0 0 17 4 0 0 3 0 0 0 0 0 0 0 0 0 0 +1032 (ntpd) S 1 1032 1032 0 -1 4211008 178 0 1 0 0 0 0 0 20 0 1 0 1287033 25743360 1058 18446744073709551615 1 1 0 0 0 0 0 4096 27207 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +126 (irqbalance) S 1 126 126 0 -1 1077952832 1217 0 0 0 1 6 0 0 20 0 1 0 1286749 20189184 647 18446744073709551615 1 1 0 0 0 0 0 0 3 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +181 (mysqld) S 1 181 181 0 -1 4210944 6399 0 46 0 8 6 0 0 20 0 22 0 1286761 748453888 14476 18446744073709551615 1 1 0 0 0 0 552967 4096 26345 0 0 0 17 4 0 0 10 0 0 0 0 0 0 0 0 0 0 +194 (memcached) S 1 187 187 0 -1 4210944 252 0 4 0 0 0 0 0 20 0 6 0 1286766 333221888 648 18446744073709551615 1 1 0 0 0 0 0 4096 2 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +243 (dbus-daemon) S 1 243 243 0 -1 4211008 67 0 0 0 0 0 0 0 20 0 1 0 1286779 40087552 598 18446744073709551615 1 1 0 0 0 0 0 0 16385 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +254 (rsyslogd) S 1 254 254 0 -1 4211008 107 0 0 0 2 2 0 0 20 0 3 0 1286782 186601472 696 18446744073709551615 1 1 0 0 0 0 0 16781830 1133601 0 0 0 17 5 0 0 0 0 0 0 0 0 0 0 0 0 0 +265 (systemd-logind) S 1 265 265 0 -1 4210944 276 0 2 0 0 0 0 0 20 0 1 0 1286786 35880960 720 18446744073709551615 1 1 0 0 0 0 0 0 0 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +333 (postgres) S 1 303 303 0 -1 4210688 3169 3466 15 18 0 1 1 1 20 0 1 0 1286817 156073984 5002 18446744073709551615 1 1 0 0 0 0 0 19935232 84487 0 0 0 17 5 0 0 1 0 0 0 0 0 0 0 0 0 0 +359 (postgres) S 333 359 359 0 -1 4210752 90 0 0 0 0 0 0 0 20 0 1 0 1286822 156073984 827 18446744073709551615 1 1 0 0 0 0 0 16805888 2567 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +360 (postgres) S 333 360 360 0 -1 4210752 119 0 0 0 0 0 0 0 20 0 1 0 1286822 156073984 827 18446744073709551615 1 1 0 0 0 0 0 16791554 16901 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +361 (postgres) S 333 361 361 0 -1 4210752 87 0 0 0 0 0 0 0 20 0 1 0 1286822 156073984 827 18446744073709551615 1 1 0 0 0 0 0 16791552 16903 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +362 (postgres) S 333 362 362 0 -1 4210752 292 0 3 0 0 0 0 0 20 0 1 0 1286822 156930048 1373 18446744073709551615 1 1 0 0 0 0 0 19927040 27271 0 0 0 17 5 0 0 0 0 0 0 0 0 0 0 0 0 0 +363 (postgres) S 333 363 363 0 -1 4210752 82 0 0 0 0 0 0 0 20 0 1 0 1286822 115924992 887 18446744073709551615 1 1 0 0 0 0 0 16808450 5 0 0 0 17 5 0 0 0 0 0 0 0 0 0 0 0 0 0 +4050 (npm) S 50 50 50 34817 50 4210688 5109 0 0 0 36 3 0 0 20 0 10 0 1292968 738025472 10051 18446744073709551615 4194304 33165900 140723623956256 0 0 0 0 4096 134300162 0 0 0 17 4 0 0 0 0 0 35263056 35370992 48369664 140723623964237 140723623964294 140723623964294 140723623968712 0 +4060 (sh) S 4050 50 50 34817 50 4210688 121 0 0 0 0 0 0 0 20 0 1 0 1293007 4579328 174 18446744073709551615 94347643936768 94347644049516 140735136055088 0 0 0 0 0 65538 1 0 0 17 5 0 0 0 0 0 94347646148008 94347646153216 94347660038144 140735136063095 140735136063129 140735136063129 140735136071664 0 +4061 (node) S 4060 50 50 34817 50 4210688 6501 0 0 0 42 2 0 0 20 0 6 0 1293008 705769472 10211 18446744073709551615 4194304 33165900 140730532686288 0 0 0 0 4096 2072111671 0 0 0 17 5 0 0 0 0 0 35263056 35370992 45867008 140730532695579 140730532695657 140730532695657 140730532704200 0 +4067 (node) S 4061 50 50 34817 50 4210688 6746 221 0 0 38 3 0 0 20 0 10 0 1293051 738910208 10527 18446744073709551615 4194304 33165900 140724824971632 0 0 0 0 4096 2072111671 0 0 0 17 4 0 0 0 0 0 35263056 35370992 68595712 140724824980995 140724824981063 140724824981063 140724824989640 0 +4079 (sh) S 4067 50 50 34817 50 4210688 118 0 0 0 0 0 0 0 20 0 1 0 1293092 4579328 194 18446744073709551615 94573702131712 94573702244460 140724712357120 0 0 0 0 0 65538 1 0 0 17 4 0 0 0 0 0 94573704342952 94573704348160 94573718511616 140724712361487 140724712361583 140724712361583 140724712370160 0 +4080 (node) S 4079 50 50 34817 50 4210688 2428 0 0 0 8 1 0 0 20 0 6 0 1293093 693059584 7251 18446744073709551615 4194304 33165900 140726023392816 0 0 0 0 4096 134234626 0 0 0 17 5 0 0 0 0 0 35263056 35370992 55226368 140726023396847 140726023396935 140726023396935 140726023405512 0 +4086 (sh) S 4067 50 50 34817 50 4210688 131 244 0 0 0 0 0 0 20 0 1 0 1293143 4579328 200 18446744073709551615 94347550273536 94347550386284 140737219399136 0 0 0 0 0 65538 1 0 0 17 5 0 0 0 0 0 94347552484776 94347552489984 94347554299904 140737219403308 140737219403375 140737219403375 140737219411952 0 +4089 (xargs) S 4086 50 50 34817 50 4210688 333 1924 0 0 0 0 0 0 20 0 1 0 1293143 17600512 477 18446744073709551615 4194304 4232732 140721633759248 0 0 0 0 0 0 1 0 0 17 5 0 0 0 0 0 6331920 6332980 32182272 140721633762891 140721633762920 140721633762920 140721633771497 0 +50 (bash) S 0 50 50 34817 50 4210944 43914 1032463 9 705 44 21 4213 818 20 0 1 0 1286336 42266624 3599 18446744073709551615 4194304 5173404 140732749083280 0 0 0 65536 4 1132560123 1 0 0 17 4 0 0 410 0 0 7273968 7310504 21196800 140732749086490 140732749086517 140732749086517 140732749086702 0 +79 (acpid) S 1 79 79 0 -1 4210752 46 0 0 0 0 0 0 0 20 0 1 0 1286717 4493312 407 18446744073709551615 1 1 0 0 0 0 0 4096 16391 0 0 0 17 5 0 0 0 0 0 0 0 0 0 0 0 0 0 +83 (sshd) S 1 83 83 0 -1 4210944 354 0 27 0 0 0 0 0 20 0 1 0 1286718 62873600 1290 18446744073709551615 1 1 0 0 0 0 0 4096 81925 0 0 0 17 4 0 0 30 0 0 0 0 0 0 0 0 0 0 +94 (cron) S 1 94 94 0 -1 1077952576 103 449 0 1 0 0 0 0 20 0 1 0 1286743 24240128 559 18446744073709551615 1 1 0 0 0 0 0 0 65537 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 +95 (atd) S 1 95 95 0 -1 1077952576 28 0 0 0 0 0 0 0 20 0 1 0 1286743 19615744 41 18446744073709551615 1 1 0 0 0 0 0 0 81923 0 0 0 17 4 0 0 0 0 0 0 0 0 0 0 0 0 0 diff --git a/node_modules/pstree.remy/tests/index.test.js b/node_modules/pstree.remy/tests/index.test.js new file mode 100644 index 0000000..50096b9 --- /dev/null +++ b/node_modules/pstree.remy/tests/index.test.js @@ -0,0 +1,51 @@ +const tap = require('tap'); +const test = tap.test; +const readFile = require('fs').readFileSync; +const spawn = require('child_process').spawn; +const pstree = require('../'); +const { tree, pidsForTree, getStat } = require('../lib/utils'); + +if (process.platform !== 'darwin') { + test('reads from /proc', async (t) => { + const ps = await getStat(); + t.ok(ps.split('\n').length > 1); + }); +} + +test('tree for live env', async (t) => { + const pid = 4079; + const fixture = readFile(__dirname + '/fixtures/out2', 'utf8'); + const ps = await tree(fixture); + t.deepEqual( + pidsForTree(ps, pid).map((_) => _.PID), + ['4080'] + ); +}); + +function testTree(t, runCallCount) { + const sub = spawn('node', [`${__dirname}/fixtures/index.js`, runCallCount], { + stdio: 'pipe', + }); + setTimeout(() => { + const pid = sub.pid; + + pstree(pid, (error, pids) => { + pids.concat([pid]).forEach((p) => { + spawn('kill', ['-s', 'SIGTERM', p]); + }); + + // the fixture launches `sh` which launches node which is why we + // are looking for two processes. + // Important: IDKW but MacOS seems to skip the `sh` process. no idea. + t.equal(pids.length, runCallCount * 2); + t.end(); + }); + }, 1000); +} + +test('can read full process tree', (t) => { + testTree(t, 1); +}); +test('can read full process tree with multiple processes', (t) => { + testTree(t, 2); +}); diff --git a/node_modules/pump/.travis.yml b/node_modules/pump/.travis.yml new file mode 100644 index 0000000..17f9433 --- /dev/null +++ b/node_modules/pump/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.10" + +script: "npm test" diff --git a/node_modules/pump/LICENSE b/node_modules/pump/LICENSE new file mode 100644 index 0000000..757562e --- /dev/null +++ b/node_modules/pump/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathias Buus + +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/pump/README.md b/node_modules/pump/README.md new file mode 100644 index 0000000..4c81471 --- /dev/null +++ b/node_modules/pump/README.md @@ -0,0 +1,65 @@ +# pump + +pump is a small node module that pipes streams together and destroys all of them if one of them closes. + +``` +npm install pump +``` + +[![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump) + +## What problem does it solve? + +When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error. +You are also not able to provide a callback to tell when then pipe has finished. + +pump does these two things for you + +## Usage + +Simply pass the streams you want to pipe together to pump and add an optional callback + +``` js +var pump = require('pump') +var fs = require('fs') + +var source = fs.createReadStream('/dev/random') +var dest = fs.createWriteStream('/dev/null') + +pump(source, dest, function(err) { + console.log('pipe finished', err) +}) + +setTimeout(function() { + dest.destroy() // when dest is closed pump will destroy source +}, 1000) +``` + +You can use pump to pipe more than two streams together as well + +``` js +var transform = someTransformStream() + +pump(source, transform, anotherTransform, dest, function(err) { + console.log('pipe finished', err) +}) +``` + +If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed. + +Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do: + +``` +return pump(s1, s2) // returns s2 +``` + +If you want to return a stream that combines *both* s1 and s2 to a single stream use +[pumpify](https://github.com/mafintosh/pumpify) instead. + +## License + +MIT + +## Related + +`pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. diff --git a/node_modules/pump/index.js b/node_modules/pump/index.js new file mode 100644 index 0000000..c15059f --- /dev/null +++ b/node_modules/pump/index.js @@ -0,0 +1,82 @@ +var once = require('once') +var eos = require('end-of-stream') +var fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes + +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) + +var isFn = function (fn) { + return typeof fn === 'function' +} + +var isFS = function (stream) { + if (!ancient) return false // newer node version do not need to care about fs is a special way + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) +} + +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} + +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) + + var closed = false + stream.on('close', function () { + closed = true + }) + + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) + + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true + + if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + + if (isFn(stream.destroy)) return stream.destroy() + + callback(err || new Error('stream was destroyed')) + } +} + +var call = function (fn) { + fn() +} + +var pipe = function (from, to) { + return from.pipe(to) +} + +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') + + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) + + return streams.reduce(pipe) +} + +module.exports = pump diff --git a/node_modules/pump/package.json b/node_modules/pump/package.json new file mode 100644 index 0000000..7958602 --- /dev/null +++ b/node_modules/pump/package.json @@ -0,0 +1,63 @@ +{ + "_args": [ + [ + "pump@3.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "pump@3.0.0", + "_id": "pump@3.0.0", + "_inBundle": false, + "_integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "_location": "/pump", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "pump@3.0.0", + "name": "pump", + "escapedName": "pump", + "rawSpec": "3.0.0", + "saveSpec": null, + "fetchSpec": "3.0.0" + }, + "_requiredBy": [ + "/cacheable-request/get-stream", + "/get-stream" + ], + "_resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "_spec": "3.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Mathias Buus Madsen", + "email": "mathiasbuus@gmail.com" + }, + "browser": { + "fs": false + }, + "bugs": { + "url": "https://github.com/mafintosh/pump/issues" + }, + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + }, + "description": "pipe streams together and close all of them if one of them closes", + "homepage": "https://github.com/mafintosh/pump#readme", + "keywords": [ + "streams", + "pipe", + "destroy", + "callback" + ], + "license": "MIT", + "name": "pump", + "repository": { + "type": "git", + "url": "git://github.com/mafintosh/pump.git" + }, + "scripts": { + "test": "node test-browser.js && node test-node.js" + }, + "version": "3.0.0" +} diff --git a/node_modules/pump/test-browser.js b/node_modules/pump/test-browser.js new file mode 100644 index 0000000..9a06c8a --- /dev/null +++ b/node_modules/pump/test-browser.js @@ -0,0 +1,66 @@ +var stream = require('stream') +var pump = require('./index') + +var rs = new stream.Readable() +var ws = new stream.Writable() + +rs._read = function (size) { + this.push(Buffer(size).fill('abc')) +} + +ws._write = function (chunk, encoding, cb) { + setTimeout(function () { + cb() + }, 100) +} + +var toHex = function () { + var reverse = new (require('stream').Transform)() + + reverse._transform = function (chunk, enc, callback) { + reverse.push(chunk.toString('hex')) + callback() + } + + return reverse +} + +var wsClosed = false +var rsClosed = false +var callbackCalled = false + +var check = function () { + if (wsClosed && rsClosed && callbackCalled) { + console.log('test-browser.js passes') + clearTimeout(timeout) + } +} + +ws.on('finish', function () { + wsClosed = true + check() +}) + +rs.on('end', function () { + rsClosed = true + check() +}) + +var res = pump(rs, toHex(), toHex(), toHex(), ws, function () { + callbackCalled = true + check() +}) + +if (res !== ws) { + throw new Error('should return last stream') +} + +setTimeout(function () { + rs.push(null) + rs.emit('close') +}, 1000) + +var timeout = setTimeout(function () { + check() + throw new Error('timeout') +}, 5000) diff --git a/node_modules/pump/test-node.js b/node_modules/pump/test-node.js new file mode 100644 index 0000000..561251a --- /dev/null +++ b/node_modules/pump/test-node.js @@ -0,0 +1,53 @@ +var pump = require('./index') + +var rs = require('fs').createReadStream('/dev/random') +var ws = require('fs').createWriteStream('/dev/null') + +var toHex = function () { + var reverse = new (require('stream').Transform)() + + reverse._transform = function (chunk, enc, callback) { + reverse.push(chunk.toString('hex')) + callback() + } + + return reverse +} + +var wsClosed = false +var rsClosed = false +var callbackCalled = false + +var check = function () { + if (wsClosed && rsClosed && callbackCalled) { + console.log('test-node.js passes') + clearTimeout(timeout) + } +} + +ws.on('close', function () { + wsClosed = true + check() +}) + +rs.on('close', function () { + rsClosed = true + check() +}) + +var res = pump(rs, toHex(), toHex(), toHex(), ws, function () { + callbackCalled = true + check() +}) + +if (res !== ws) { + throw new Error('should return last stream') +} + +setTimeout(function () { + rs.destroy() +}, 1000) + +var timeout = setTimeout(function () { + throw new Error('timeout') +}, 5000) diff --git a/node_modules/punycode/LICENSE-MIT.txt b/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/punycode/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +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/punycode/README.md b/node_modules/punycode/README.md new file mode 100644 index 0000000..ee2f9d6 --- /dev/null +++ b/node_modules/punycode/README.md @@ -0,0 +1,122 @@ +# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) + +Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). + +This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: + +* [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) +* [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) +* [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) +* [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) +* [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) + +This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). + +The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install punycode --save +``` + +In [Node.js](https://nodejs.org/): + +```js +const punycode = require('punycode'); +``` + +## API + +### `punycode.decode(string)` + +Converts a Punycode string of ASCII symbols to a string of Unicode symbols. + +```js +// decode domain name parts +punycode.decode('maana-pta'); // 'mañana' +punycode.decode('--dqo34k'); // '☃-⌘' +``` + +### `punycode.encode(string)` + +Converts a string of Unicode symbols to a Punycode string of ASCII symbols. + +```js +// encode domain name parts +punycode.encode('mañana'); // 'maana-pta' +punycode.encode('☃-⌘'); // '--dqo34k' +``` + +### `punycode.toUnicode(input)` + +Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. + +```js +// decode domain names +punycode.toUnicode('xn--maana-pta.com'); +// → 'mañana.com' +punycode.toUnicode('xn----dqo34k.com'); +// → '☃-⌘.com' + +// decode email addresses +punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); +// → 'джумла@джpумлатест.bрфa' +``` + +### `punycode.toASCII(input)` + +Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. + +```js +// encode domain names +punycode.toASCII('mañana.com'); +// → 'xn--maana-pta.com' +punycode.toASCII('☃-⌘.com'); +// → 'xn----dqo34k.com' + +// encode email addresses +punycode.toASCII('джумла@джpумлатест.bрфa'); +// → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' +``` + +### `punycode.ucs2` + +#### `punycode.ucs2.decode(string)` + +Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. + +```js +punycode.ucs2.decode('abc'); +// → [0x61, 0x62, 0x63] +// surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: +punycode.ucs2.decode('\uD834\uDF06'); +// → [0x1D306] +``` + +#### `punycode.ucs2.encode(codePoints)` + +Creates a string based on an array of numeric code point values. + +```js +punycode.ucs2.encode([0x61, 0x62, 0x63]); +// → 'abc' +punycode.ucs2.encode([0x1D306]); +// → '\uD834\uDF06' +``` + +### `punycode.version` + +A string representing the current Punycode.js version number. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +Punycode.js is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/punycode/package.json b/node_modules/punycode/package.json new file mode 100644 index 0000000..4855c98 --- /dev/null +++ b/node_modules/punycode/package.json @@ -0,0 +1,88 @@ +{ + "_args": [ + [ + "punycode@2.1.1", + "/home/other/discord_bot" + ] + ], + "_from": "punycode@2.1.1", + "_id": "punycode@2.1.1", + "_inBundle": false, + "_integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "_location": "/punycode", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "punycode@2.1.1", + "name": "punycode", + "escapedName": "punycode", + "rawSpec": "2.1.1", + "saveSpec": null, + "fetchSpec": "2.1.1" + }, + "_requiredBy": [ + "/tough-cookie" + ], + "_resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "_spec": "2.1.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "bugs": { + "url": "https://github.com/bestiejs/punycode.js/issues" + }, + "contributors": [ + { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + } + ], + "description": "A robust Punycode converter that fully complies to RFC 3492 and RFC 5891, and works on nearly all JavaScript platforms.", + "devDependencies": { + "codecov": "^1.0.1", + "istanbul": "^0.4.1", + "mocha": "^2.5.3" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "LICENSE-MIT.txt", + "punycode.js", + "punycode.es6.js" + ], + "homepage": "https://mths.be/punycode", + "jsnext:main": "punycode.es6.js", + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + }, + "keywords": [ + "punycode", + "unicode", + "idn", + "idna", + "dns", + "url", + "domain" + ], + "license": "MIT", + "main": "punycode.js", + "module": "punycode.es6.js", + "name": "punycode", + "repository": { + "type": "git", + "url": "git+https://github.com/bestiejs/punycode.js.git" + }, + "scripts": { + "prepublish": "node scripts/prepublish.js", + "test": "mocha tests" + }, + "version": "2.1.1" +} diff --git a/node_modules/punycode/punycode.es6.js b/node_modules/punycode/punycode.es6.js new file mode 100644 index 0000000..4610bc9 --- /dev/null +++ b/node_modules/punycode/punycode.es6.js @@ -0,0 +1,441 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = array => String.fromCodePoint(...array); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode }; +export default punycode; diff --git a/node_modules/punycode/punycode.js b/node_modules/punycode/punycode.js new file mode 100644 index 0000000..ea61fd0 --- /dev/null +++ b/node_modules/punycode/punycode.js @@ -0,0 +1,440 @@ +'use strict'; + +/** Highest positive signed 32-bit float value */ +const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +const base = 36; +const tMin = 1; +const tMax = 26; +const skew = 38; +const damp = 700; +const initialBias = 72; +const initialN = 128; // 0x80 +const delimiter = '-'; // '\x2D' + +/** Regular expressions */ +const regexPunycode = /^xn--/; +const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +const errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +const baseMinusTMin = base - tMin; +const floor = Math.floor; +const stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + const result = []; + let length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + const parts = string.split('@'); + let result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + const labels = string.split('.'); + const encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + const output = []; + let counter = 0; + const length = string.length; + while (counter < length) { + const value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + const extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +const ucs2encode = array => String.fromCodePoint(...array); + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +const basicToDigit = function(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +const digitToBasic = function(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +const adapt = function(delta, numPoints, firstTime) { + let k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +const decode = function(input) { + // Don't use UCS-2. + const output = []; + const inputLength = input.length; + let i = 0; + let n = initialN; + let bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + let basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (let j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + let oldi = i; + for (let w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + const digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + const baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + const out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + + } + + return String.fromCodePoint(...output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +const encode = function(input) { + const output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + let inputLength = input.length; + + // Initialize the state. + let n = initialN; + let delta = 0; + let bias = initialBias; + + // Handle the basic code points. + for (const currentValue of input) { + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + let basicLength = output.length; + let handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + let m = maxInt; + for (const currentValue of input) { + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + const handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (const currentValue of input) { + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + if (currentValue == n) { + // Represent delta as a generalized variable-length integer. + let q = delta; + for (let k = base; /* no condition */; k += base) { + const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + const qMinusT = q - t; + const baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +const toUnicode = function(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +const toASCII = function(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +const punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +module.exports = punycode; diff --git a/node_modules/pupa/index.d.ts b/node_modules/pupa/index.d.ts new file mode 100644 index 0000000..762aae0 --- /dev/null +++ b/node_modules/pupa/index.d.ts @@ -0,0 +1,32 @@ +/** +Simple micro templating. + +@param template - Text with placeholders for `data` properties. +@param data - Data to interpolate into `template`. + +@example +``` +import pupa = require('pupa'); + +pupa('The mobile number of {name} is {phone.mobile}', { + name: 'Sindre', + phone: { + mobile: '609 24 363' + } +}); +//=> 'The mobile number of Sindre is 609 24 363' + +pupa('I like {0} and {1}', ['🦄', '🐮']); +//=> 'I like 🦄 and 🐮' + +// Double braces encodes the HTML entities to avoid code injection +pupa('I like {{0}} and {{1}}', ['
🦄
', '🐮']); +//=> 'I like <br>🦄</br> and <i>🐮</i>' +``` +*/ +declare function pupa( + template: string, + data: unknown[] | {[key: string]: any} +): string; + +export = pupa; diff --git a/node_modules/pupa/index.js b/node_modules/pupa/index.js new file mode 100644 index 0000000..85739eb --- /dev/null +++ b/node_modules/pupa/index.js @@ -0,0 +1,39 @@ +'use strict'; +const {htmlEscape} = require('escape-goat'); + +module.exports = (template, data) => { + if (typeof template !== 'string') { + throw new TypeError(`Expected a \`string\` in the first argument, got \`${typeof template}\``); + } + + if (typeof data !== 'object') { + throw new TypeError(`Expected an \`object\` or \`Array\` in the second argument, got \`${typeof data}\``); + } + + // The regex tries to match either a number inside `{{ }}` or a valid JS identifier or key path. + const doubleBraceRegex = /{{(\d+|[a-z$_][a-z\d$_]*?(?:\.[a-z\d$_]*?)*?)}}/gi; + + if (doubleBraceRegex.test(template)) { + template = template.replace(doubleBraceRegex, (_, key) => { + let result = data; + + for (const property of key.split('.')) { + result = result ? result[property] : ''; + } + + return htmlEscape(String(result)); + }); + } + + const braceRegex = /{(\d+|[a-z$_][a-z\d$_]*?(?:\.[a-z\d$_]*?)*?)}/gi; + + return template.replace(braceRegex, (_, key) => { + let result = data; + + for (const property of key.split('.')) { + result = result ? result[property] : ''; + } + + return String(result); + }); +}; diff --git a/node_modules/pupa/license b/node_modules/pupa/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/pupa/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/pupa/package.json b/node_modules/pupa/package.json new file mode 100644 index 0000000..d080b6a --- /dev/null +++ b/node_modules/pupa/package.json @@ -0,0 +1,83 @@ +{ + "_args": [ + [ + "pupa@2.1.1", + "/home/other/discord_bot" + ] + ], + "_from": "pupa@2.1.1", + "_id": "pupa@2.1.1", + "_inBundle": false, + "_integrity": "sha512-l1jNAspIBSFqbT+y+5FosojNpVpF94nlI+wDUpqP9enwOTfHx9f0gh5nB96vl+6yTpsJsypeNrwfzPrKuHB41A==", + "_location": "/pupa", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "pupa@2.1.1", + "name": "pupa", + "escapedName": "pupa", + "rawSpec": "2.1.1", + "saveSpec": null, + "fetchSpec": "2.1.1" + }, + "_requiredBy": [ + "/nodemon/update-notifier", + "/update-notifier" + ], + "_resolved": "https://registry.npmjs.org/pupa/-/pupa-2.1.1.tgz", + "_spec": "2.1.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/pupa/issues" + }, + "dependencies": { + "escape-goat": "^2.0.0" + }, + "description": "Simple micro templating", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/pupa#readme", + "keywords": [ + "string", + "formatting", + "template", + "object", + "format", + "interpolate", + "interpolation", + "templating", + "expand", + "simple", + "replace", + "placeholders", + "values", + "transform", + "micro" + ], + "license": "MIT", + "name": "pupa", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/pupa.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.1.1" +} diff --git a/node_modules/pupa/readme.md b/node_modules/pupa/readme.md new file mode 100644 index 0000000..bb9ab18 --- /dev/null +++ b/node_modules/pupa/readme.md @@ -0,0 +1,63 @@ +# pupa [![Build Status](https://travis-ci.org/sindresorhus/pupa.svg?branch=master)](https://travis-ci.org/sindresorhus/pupa) + +> Simple micro templating + +Useful when all you need is to fill in some placeholders. + + +## Install + +``` +$ npm install pupa +``` + + +## Usage + +```js +const pupa = require('pupa'); + +pupa('The mobile number of {name} is {phone.mobile}', { + name: 'Sindre', + phone: { + mobile: '609 24 363' + } +}); +//=> 'The mobile number of Sindre is 609 24 363' + +pupa('I like {0} and {1}', ['🦄', '🐮']); +//=> 'I like 🦄 and 🐮' + +// Double braces encodes the HTML entities to avoid code injection +pupa('I like {{0}} and {{1}}', ['
🦄
', '🐮']); +//=> 'I like <br>🦄</br> and <i>🐮</i>' +``` + + +## API + +### pupa(template, data) + +#### template + +Type: `string` + +Text with placeholders for `data` properties. + +#### data + +Type: `object | unknown[]` + +Data to interpolate into `template`. + + +## FAQ + +### What about template literals? + +Template literals expand on creation. This module expands the template on execution, which can be useful if either or both template and data are lazily created or user-supplied. + + +## Related + +- [pupa-cli](https://github.com/sindresorhus/pupa-cli) - CLI for this module diff --git a/node_modules/qs/.editorconfig b/node_modules/qs/.editorconfig new file mode 100644 index 0000000..2f08444 --- /dev/null +++ b/node_modules/qs/.editorconfig @@ -0,0 +1,43 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 160 +quote_type = single + +[test/*] +max_line_length = off + +[LICENSE.md] +indent_size = off + +[*.md] +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[LICENSE] +indent_size = 2 +max_line_length = off + +[coverage/**/*] +indent_size = off +indent_style = off +indent = off +max_line_length = off + +[.nycrc] +indent_style = tab diff --git a/node_modules/qs/.eslintrc b/node_modules/qs/.eslintrc new file mode 100644 index 0000000..919dbc0 --- /dev/null +++ b/node_modules/qs/.eslintrc @@ -0,0 +1,38 @@ +{ + "root": true, + + "extends": "@ljharb", + + "ignorePatterns": [ + "dist/", + ], + + "rules": { + "complexity": 0, + "consistent-return": 1, + "func-name-matching": 0, + "id-length": [2, { "min": 1, "max": 25, "properties": "never" }], + "indent": [2, 4], + "max-lines-per-function": [2, { "max": 150 }], + "max-params": [2, 16], + "max-statements": [2, 100], + "multiline-comment-style": 0, + "no-continue": 1, + "no-magic-numbers": 0, + "no-restricted-syntax": [2, "BreakStatement", "DebuggerStatement", "ForInStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "function-paren-newline": 0, + "max-lines-per-function": 0, + "max-statements": 0, + "no-buffer-constructor": 0, + "no-extend-native": 0, + "no-throw-literal": 0, + }, + }, + ], +} diff --git a/node_modules/qs/.github/FUNDING.yml b/node_modules/qs/.github/FUNDING.yml new file mode 100644 index 0000000..0355f4f --- /dev/null +++ b/node_modules/qs/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/qs +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/qs/.nycrc b/node_modules/qs/.nycrc new file mode 100644 index 0000000..1d57cab --- /dev/null +++ b/node_modules/qs/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "dist" + ] +} diff --git a/node_modules/qs/CHANGELOG.md b/node_modules/qs/CHANGELOG.md new file mode 100644 index 0000000..0a6504c --- /dev/null +++ b/node_modules/qs/CHANGELOG.md @@ -0,0 +1,555 @@ +## **6.11.1** +- [Fix] `stringify`: encode comma values more consistently (#463) +- [readme] add usage of `filter` option for injecting custom serialization, i.e. of custom types (#447) +- [meta] remove extraneous code backticks (#457) +- [meta] fix changelog markdown +- [actions] update checkout action +- [actions] restrict action permissions +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `object-inspect`, `tape` + +## **6.11.0** +- [New] [Fix] `stringify`: revert 0e903c0; add `commaRoundTrip` option (#442) +- [readme] fix version badge + +## **6.10.5** +- [Fix] `stringify`: with `arrayFormat: comma`, properly include an explicit `[]` on a single-item array (#434) + +## **6.10.4** +- [Fix] `stringify`: with `arrayFormat: comma`, include an explicit `[]` on a single-item array (#441) +- [meta] use `npmignore` to autogenerate an npmignore file +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbol`, `object-inspect`, `tape` + +## **6.10.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [actions] reuse common workflows +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `tape` + +## **6.10.2** +- [Fix] `stringify`: actually fix cyclic references (#426) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [actions] update codecov uploader +- [actions] update workflows +- [Tests] clean up stringify tests slightly +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect`, `safe-publish-latest`, `tape` + +## **6.10.1** +- [Fix] `stringify`: avoid exception on repeated object values (#402) + +## **6.10.0** +- [New] `stringify`: throw on cycles, instead of an infinite loop (#395, #394, #393) +- [New] `parse`: add `allowSparse` option for collapsing arrays with missing indices (#312) +- [meta] fix README.md (#399) +- [meta] only run `npm run dist` in publish, not install +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbols`, `tape` +- [Tests] fix tests on node v0.6 +- [Tests] use `ljharb/actions/node/install` instead of `ljharb/actions/node/run` +- [Tests] Revert "[meta] ignore eclint transitive audit warning" + +## **6.9.7** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [Tests] clean up stringify tests slightly +- [meta] fix README.md (#399) +- Revert "[meta] ignore eclint transitive audit warning" +- [actions] backport actions from main +- [Dev Deps] backport updates from main + +## **6.9.6** +- [Fix] restore `dist` dir; mistakenly removed in d4f6c32 + +## **6.9.5** +- [Fix] `stringify`: do not encode parens for RFC1738 +- [Fix] `stringify`: fix arrayFormat comma with empty array/objects (#350) +- [Refactor] `format`: remove `util.assign` call +- [meta] add "Allow Edits" workflow; update rebase workflow +- [actions] switch Automatic Rebase workflow to `pull_request_target` event +- [Tests] `stringify`: add tests for #378 +- [Tests] migrate tests to Github Actions +- [Tests] run `nyc` on all tests; use `tape` runner +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `mkdirp`, `object-inspect`, `tape`; add `aud` + +## **6.9.4** +- [Fix] `stringify`: when `arrayFormat` is `comma`, respect `serializeDate` (#364) +- [Refactor] `stringify`: reduce branching (part of #350) +- [Refactor] move `maybeMap` to `utils` +- [Dev Deps] update `browserify`, `tape` + +## **6.9.3** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.9.2** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [meta] ignore eclint transitive audit warning +- [meta] fix indentation in package.json +- [meta] add tidelift marketing copy +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `object-inspect`, `has-symbols`, `tape`, `mkdirp`, `iconv-lite` +- [actions] add automatic rebasing / merge commit blocking + +## **6.9.1** +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [Fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config` +- [Tests] use shared travis-ci config + +## **6.9.0** +- [New] `parse`/`stringify`: Pass extra key/value argument to `decoder` (#333) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `evalmd` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] add `posttest` using `npx aud` to run `npm audit` without a lockfile +- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16` +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray + +## **6.8.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Tests] clean up stringify tests slightly +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Refactor] `stringify`: reduce branching +- [meta] do not publish workflow files + +## **6.8.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.8.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `has-symbols`, `iconv-lite`, `mkdirp`, `object-inspect` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [actions] add automatic rebasing / merge commit blocking + +## **6.8.0** +- [New] add `depth=false` to preserve the original key; [Fix] `depth=0` should preserve the original key (#326) +- [New] [Fix] stringify symbols and bigints +- [Fix] ensure node 0.12 can stringify Symbols +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `safe-publish-latest`, `iconv-lite`, `tape` +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended (#326) +- [Tests] use `eclint` instead of `editorconfig-tools` +- [docs] readme: add security note +- [meta] add github sponsorship +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause + +## **6.7.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Tests] use `nyc` for coverage +- [Tests] clean up stringify tests slightly + +## **6.7.2** +- [Fix] proper comma parsing of URL-encoded commas (#361) +- [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) + +## **6.7.1** +- [Fix] `parse`: Fix parsing array from object with `comma` true (#359) +- [Fix] `parse`: with comma true, handle field that holds an array of arrays (#335) +- [fix] `parse`: with comma true, do not split non-string values (#334) +- [Fix] `parse`: throw a TypeError instead of an Error for bad charset (#349) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Refactor] `formats`: tiny bit of cleanup. +- readme: add security note +- [meta] add tidelift marketing copy +- [meta] add `funding` field +- [meta] add FUNDING.yml +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `safe-publish-latest`, `evalmd`, `iconv-lite`, `mkdirp`, `object-inspect`, `browserify` +- [Tests] `parse`: add passing `arrayFormat` tests +- [Tests] use shared travis-ci configs +- [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +- [Tests] add tests for `depth=0` and `depth=false` behavior, both current and intuitive/intended +- [Tests] use `eclint` instead of `editorconfig-tools` +- [actions] add automatic rebasing / merge commit blocking + +## **6.7.0** +- [New] `stringify`/`parse`: add `comma` as an `arrayFormat` option (#276, #219) +- [Fix] correctly parse nested arrays (#212) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source, also with an array source +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] `stringify`/`utils`: cache `Array.isArray` +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] temporarily allow coverage to fail + +## **6.6.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `formats`: tiny bit of cleanup. +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor]: `stringify`/`utils`: cache `Array.isArray` +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [meta] Fixes typo in CHANGELOG.md +- [actions] backport actions from main +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] always use `String(x)` over `x.toString()` +- [Dev Deps] backport from main + +## **6.6.0** +- [New] Add support for iso-8859-1, utf8 "sentinel" and numeric entities (#268) +- [New] move two-value combine to a `utils` function (#189) +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` (#260) +- [Fix] `stringify`: do not crash in an obscure combo of `interpretNumericEntities`, a bad custom `decoder`, & `iso-8859-1` +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Refactor] `parse`/`stringify`: clean up `charset` options checking; fix defaults +- [Refactor] add missing defaults +- [Refactor] `parse`: one less `concat` call +- [Refactor] `utils`: `compactQueue`: make it explicitly side-effecting +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`, `iconv-lite`, `safe-publish-latest`, `tape` +- [Tests] up to `node` `v10.10`, `v9.11`, `v8.12`, `v6.14`, `v4.9`; pin included builds to LTS + +## **6.5.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clean up license text so it’s properly detected as BSD-3-Clause +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.5.2** +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Refactor] utils: `module.exports` one thing, instead of mutating `exports` (#230) +- [Dev Deps] update `browserify`, `eslint`, `iconv-lite`, `safer-buffer`, `tape`, `browserify` + +## **6.5.1** +- [Fix] Fix parsing & compacting very deep objects (#224) +- [Refactor] name utils functions +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` +- [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` so newer npm doesn’t break older node +- [Tests] Use precise dist for Node.js 0.6 runtime (#225) +- [Tests] make 0.6 required, now that it’s passing +- [Tests] on `node` `v8.2`; fix npm on node 0.6 + +## **6.5.0** +- [New] add `utils.assign` +- [New] pass default encoder/decoder to custom encoder/decoder functions (#206) +- [New] `parse`/`stringify`: add `ignoreQueryPrefix`/`addQueryPrefix` options, respectively (#213) +- [Fix] Handle stringifying empty objects with addQueryPrefix (#217) +- [Fix] do not mutate `options` argument (#207) +- [Refactor] `parse`: cache index to reuse in else statement (#182) +- [Docs] add various badges to readme (#208) +- [Dev Deps] update `eslint`, `browserify`, `iconv-lite`, `tape` +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 +- [Tests] add `editorconfig-tools` + +## **6.4.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.4.0** +- [New] `qs.stringify`: add `encodeValuesOnly` option +- [Fix] follow `allowPrototypes` option during merge (#201, #201) +- [Fix] support keys starting with brackets (#202, #200) +- [Fix] chmod a-x +- [Dev Deps] update `eslint` +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds +- [eslint] reduce warnings + +## **6.3.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.3.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Dev Deps] update `eslint` +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.3.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties (thanks, @snyk!) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `iconv-lite`, `qs-iconv`, `tape` +- [Tests] on all node minors; improve test matrix +- [Docs] document stringify option `allowDots` (#195) +- [Docs] add empty object and array values example (#195) +- [Docs] Fix minor inconsistency/typo (#192) +- [Docs] document stringify option `sort` (#191) +- [Refactor] `stringify`: throw faster with an invalid encoder +- [Refactor] remove unnecessary escapes (#184) +- Remove contributing.md, since `qs` is no longer part of `hapi` (#183) + +## **6.3.0** +- [New] Add support for RFC 1738 (#174, #173) +- [New] `stringify`: Add `serializeDate` option to customize Date serialization (#159) +- [Fix] ensure `utils.merge` handles merging two arrays +- [Refactor] only constructors should be capitalized +- [Refactor] capitalized var names are for constructors only +- [Refactor] avoid using a sparse array +- [Robustness] `formats`: cache `String#replace` +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` +- [Tests] up to `node` `v6.8`, `v4.6`; improve test matrix +- [Tests] flesh out arrayLimit/arrayFormat tests (#107) +- [Tests] skip Object.create tests when null objects are not available +- [Tests] Turn on eslint for test files (#175) + +## **6.2.4** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + +## **6.2.3** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.2.2** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## **6.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values +- [Refactor] Be explicit and use `Object.prototype.hasOwnProperty.call` +- [Tests] remove `parallelshell` since it does not reliably report failures +- [Tests] up to `node` `v6.3`, `v5.12` +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `qs-iconv` + +## [**6.2.0**](https://github.com/ljharb/qs/issues?milestone=36&state=closed) +- [New] pass Buffers to the encoder/decoder directly (#161) +- [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160) +- [Fix] fix compacting of nested sparse arrays (#150) + +## **6.1.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.1.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## [**6.1.0**](https://github.com/ljharb/qs/issues?milestone=35&state=closed) +- [New] allowDots option for `stringify` (#151) +- [Fix] "sort" option should work at a depth of 3 or more (#151) +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## **6.0.4** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.0.3** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed) +- Revert ES6 requirement and restore support for node down to v0.8. + +## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed) +- [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json + +## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed) +- [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4 + +## **5.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values + +## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed) +- [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string + +## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed) +- [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost +- [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign +- [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute + +## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object + +## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed) +- [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". + +## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed) +- [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46 + +## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31 +- [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects + +## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed) +- [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present +- [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays +- [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters? + +## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed) +- [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit +- [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20 + +## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed) +- [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values + +## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed) +- [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters +- [**#15**](https://github.com/ljharb/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README + +## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed) +- [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index diff --git a/node_modules/qs/LICENSE.md b/node_modules/qs/LICENSE.md new file mode 100644 index 0000000..fecf6b6 --- /dev/null +++ b/node_modules/qs/LICENSE.md @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/ljharb/qs/graphs/contributors) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/qs/README.md b/node_modules/qs/README.md new file mode 100644 index 0000000..6635471 --- /dev/null +++ b/node_modules/qs/README.md @@ -0,0 +1,663 @@ +# qs [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A querystring parsing and stringifying library with some added security. + +Lead Maintainer: [Jordan Harband](https://github.com/ljharb) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var qs = require('qs'); +var assert = require('assert'); + +var obj = qs.parse('a=c'); +assert.deepEqual(obj, { a: 'c' }); + +var str = qs.stringify(obj); +assert.equal(str, 'a=c'); +``` + +### Parsing Objects + +[](#preventEval) +```javascript +qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +assert.deepEqual(qs.parse('foo[bar]=baz'), { + foo: { + bar: 'baz' + } +}); +``` + +When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); +assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); +assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); +``` + +URI encoded strings work too: + +```javascript +assert.deepEqual(qs.parse('a%5Bb%5D=c'), { + a: { b: 'c' } +}); +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { + foo: { + bar: { + baz: 'foobarbaz' + } + } +}); +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +var expected = { + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +}; +var string = 'a[b][c][d][e][f][g][h][i]=j'; +assert.deepEqual(qs.parse(string), expected); +``` + +This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: + +```javascript +var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); +assert.deepEqual(limited, { a: 'b' }); +``` + +To bypass the leading question mark, use `ignoreQueryPrefix`: + +```javascript +var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); +assert.deepEqual(prefixed, { a: 'b', c: 'd' }); +``` + +An optional delimiter can also be passed: + +```javascript +var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); +assert.deepEqual(delimited, { a: 'b', c: 'd' }); +``` + +Delimiters can be a regular expression too: + +```javascript +var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +var withDots = qs.parse('a.b=c', { allowDots: true }); +assert.deepEqual(withDots, { a: { b: 'c' } }); +``` + +If you have to deal with legacy browsers or services, there's +also support for decoding percent-encoded octets as iso-8859-1: + +```javascript +var oldCharset = qs.parse('a=%A7', { charset: 'iso-8859-1' }); +assert.deepEqual(oldCharset, { a: '§' }); +``` + +Some services add an initial `utf8=✓` value to forms so that old +Internet Explorer versions are more likely to submit the form as +utf-8. Additionally, the server can check the value against wrong +encodings of the checkmark character and detect that a query string +or `application/x-www-form-urlencoded` body was *not* sent as +utf-8, eg. if the form had an `accept-charset` parameter or the +containing page had a different character set. + +**qs** supports this mechanism via the `charsetSentinel` option. +If specified, the `utf8` parameter will be omitted from the +returned object. It will be used to switch to `iso-8859-1`/`utf-8` +mode depending on how the checkmark is encoded. + +**Important**: When you specify both the `charset` option and the +`charsetSentinel` option, the `charset` will be overridden when +the request contains a `utf8` parameter from which the actual +charset can be deduced. In that sense the `charset` will behave +as the default charset rather than the authoritative charset. + +```javascript +var detectedAsUtf8 = qs.parse('utf8=%E2%9C%93&a=%C3%B8', { + charset: 'iso-8859-1', + charsetSentinel: true +}); +assert.deepEqual(detectedAsUtf8, { a: 'ø' }); + +// Browsers encode the checkmark as ✓ when submitting as iso-8859-1: +var detectedAsIso8859_1 = qs.parse('utf8=%26%2310003%3B&a=%F8', { + charset: 'utf-8', + charsetSentinel: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: 'ø' }); +``` + +If you want to decode the `&#...;` syntax to the actual character, +you can specify the `interpretNumericEntities` option as well: + +```javascript +var detectedAsIso8859_1 = qs.parse('a=%26%239786%3B', { + charset: 'iso-8859-1', + interpretNumericEntities: true +}); +assert.deepEqual(detectedAsIso8859_1, { a: '☺' }); +``` + +It also works when the charset has been detected in `charsetSentinel` +mode. + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +var withArray = qs.parse('a[]=b&a[]=c'); +assert.deepEqual(withArray, { a: ['b', 'c'] }); +``` + +You may specify an index as well: + +```javascript +var withIndexes = qs.parse('a[1]=c&a[0]=b'); +assert.deepEqual(withIndexes, { a: ['b', 'c'] }); +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +var noSparse = qs.parse('a[1]=b&a[15]=c'); +assert.deepEqual(noSparse, { a: ['b', 'c'] }); +``` + +You may also use `allowSparse` option to parse sparse arrays: + +```javascript +var sparseArray = qs.parse('a[1]=2&a[3]=5', { allowSparse: true }); +assert.deepEqual(sparseArray, { a: [, '2', , '5'] }); +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +var withEmptyString = qs.parse('a[]=&a[]=b'); +assert.deepEqual(withEmptyString, { a: ['', 'b'] }); + +var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); +assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key. This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array. + +```javascript +var withMaxIndex = qs.parse('a[100]=b'); +assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); +assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); +assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +var mixedNotation = qs.parse('a[0]=b&a[b]=c'); +assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); +``` + +You can also create arrays of objects: + +```javascript +var arraysOfObjects = qs.parse('a[][b]=c'); +assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); +``` + +Some people use comma to join array, **qs** can parse it: +```javascript +var arraysOfObjects = qs.parse('a=b,c', { comma: true }) +assert.deepEqual(arraysOfObjects, { a: ['b', 'c'] }) +``` +(_this cannot convert nested objects, such as `a={b:1},{c:d}`_) + +### Parsing primitive/scalar values (numbers, booleans, null, etc) + +By default, all values are parsed as strings. This behavior will not change and is explained in [issue #91](https://github.com/ljharb/qs/issues/91). + +```javascript +var primitiveValues = qs.parse('a=15&b=true&c=null'); +assert.deepEqual(primitiveValues, { a: '15', b: 'true', c: 'null' }); +``` + +If you wish to auto-convert values which look like numbers, booleans, and other values into their primitive counterparts, you can use the [query-types Express JS middleware](https://github.com/xpepermint/query-types) which will auto-convert all request query parameters. + +### Stringifying + +[](#preventEval) +```javascript +qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +assert.equal(qs.stringify({ a: 'b' }), 'a=b'); +assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); +assert.equal(unencoded, 'a[b]=c'); +``` + +Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: +```javascript +var encodedValues = qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } +); +assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); +``` + +This encoding can also be replaced by a custom encoding method set as `encoder` option: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { + // Passed in values `a`, `b`, `c` + return // Return encoded string +}}) +``` + +_(Note: the `encoder` option does not apply if `encode` is `false`)_ + +Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str) { + // Passed in values `x`, `z` + return // Return decoded string +}}) +``` + +You can encode keys and values using different logic by using the type argument provided to the encoder: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return // Encoded key + } else if (type === 'value') { + return // Encoded value + } +}}) +``` + +The type argument is also provided to the decoder: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return // Decoded key + } else if (type === 'value') { + return // Decoded value + } +}}) +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); +// 'a=b&a=c&a=d' +``` + +You may use the `arrayFormat` option to specify the format of the output array: + +```javascript +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }) +// 'a=b,c' +``` + +Note: when using `arrayFormat` set to `'comma'`, you can also pass the `commaRoundTrip` option set to `true` or `false`, to append `[]` on single-item arrays, so that they can round trip through a parse. + +When objects are stringified, by default they use bracket notation: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); +// 'a[b][c]=d&a[b][e]=f' +``` + +You may override this to use dot notation by setting the `allowDots` option to `true`: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); +// 'a.b.c=d&a.b.e=f' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +assert.equal(qs.stringify({ a: '' }), 'a='); +``` + +Key with no values (such as an empty object or array) will return nothing: + +```javascript +assert.equal(qs.stringify({ a: [] }), ''); +assert.equal(qs.stringify({ a: {} }), ''); +assert.equal(qs.stringify({ a: [{}] }), ''); +assert.equal(qs.stringify({ a: { b: []} }), ''); +assert.equal(qs.stringify({ a: { b: {}} }), ''); +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); +``` + +The query string may optionally be prepended with a question mark: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); +``` + +The delimiter may be overridden with stringify as well: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); +``` + +If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: + +```javascript +var date = new Date(7); +assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); +assert.equal( + qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), + 'a=7' +); +``` + +You may use the `sort` option to affect the order of parameter keys: + +```javascript +function alphabeticalSort(a, b) { + return a.localeCompare(b); +} +assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); +// 'a=b&c=d&e[f]=123&e[g][0]=4' +qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); +// 'a=b&e=f' +qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); +// 'a[0]=b&a[2]=d' +``` + +You could also use `filter` to inject custom serialization for user defined types. Consider you're working with +some api that expects query strings of the format for ranges: + +``` +https://domain.com/endpoint?range=30...70 +``` + +For which you model as: + +```javascript +class Range { + constructor(from, to) { + this.from = from; + this.to = to; + } +} +``` + +You could _inject_ a custom serializer to handle values of this type: + +```javascript +qs.stringify( + { + range: new Range(30, 70), + }, + { + filter: (prefix, value) => { + if (value instanceof Range) { + return `${value.from}...${value.to}`; + } + // serialize the usual way + return value; + }, + } +); +// range=30...70 +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +var withNull = qs.stringify({ a: null, b: '' }); +assert.equal(withNull, 'a=&b='); +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +var equalsInsensitive = qs.parse('a&b='); +assert.deepEqual(equalsInsensitive, { a: '', b: '' }); +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +assert.equal(strictNull, 'a&b='); +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); +assert.deepEqual(parsedStrictNull, { a: null, b: '' }); +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); +assert.equal(nullsSkipped, 'a=b'); +``` + +If you're communicating with legacy systems, you can switch to `iso-8859-1` +using the `charset` option: + +```javascript +var iso = qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }); +assert.equal(iso, '%E6=%E6'); +``` + +Characters that don't exist in `iso-8859-1` will be converted to numeric +entities, similar to what browsers do: + +```javascript +var numeric = qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }); +assert.equal(numeric, 'a=%26%239786%3B'); +``` + +You can use the `charsetSentinel` option to announce the character by +including an `utf8=✓` parameter with the proper encoding if the checkmark, +similar to what Ruby on Rails and others do when submitting forms. + +```javascript +var sentinel = qs.stringify({ a: '☺' }, { charsetSentinel: true }); +assert.equal(sentinel, 'utf8=%E2%9C%93&a=%E2%98%BA'); + +var isoSentinel = qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }); +assert.equal(isoSentinel, 'utf8=%26%2310003%3B&a=%E6'); +``` + +### Dealing with special character sets + +By default the encoding and decoding of characters is done in `utf-8`, +and `iso-8859-1` support is also built in via the `charset` parameter. + +If you wish to encode querystrings to a different character set (i.e. +[Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the +[`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: + +```javascript +var encoder = require('qs-iconv/encoder')('shift_jis'); +var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); +assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); +``` + +This also works for decoding of query strings: + +```javascript +var decoder = require('qs-iconv/decoder')('shift_jis'); +var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); +assert.deepEqual(obj, { a: 'こんにちは!' }); +``` + +### RFC 3986 and RFC 1738 space encoding + +RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. +In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. + +``` +assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); +``` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +## qs for enterprise + +Available as part of the Tidelift Subscription + +The maintainers of qs and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-qs?utm_source=npm-qs&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +[package-url]: https://npmjs.org/package/qs +[npm-version-svg]: https://versionbadg.es/ljharb/qs.svg +[deps-svg]: https://david-dm.org/ljharb/qs.svg +[deps-url]: https://david-dm.org/ljharb/qs +[dev-deps-svg]: https://david-dm.org/ljharb/qs/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/qs#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/qs.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/qs.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/qs.svg +[downloads-url]: https://npm-stat.com/charts.html?package=qs +[codecov-image]: https://codecov.io/gh/ljharb/qs/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/qs/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/qs +[actions-url]: https://github.com/ljharb/qs/actions diff --git a/node_modules/qs/dist/qs.js b/node_modules/qs/dist/qs.js new file mode 100644 index 0000000..cbe8a21 --- /dev/null +++ b/node_modules/qs/dist/qs.js @@ -0,0 +1,2066 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i -1) { + return val.split(','); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(val); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== '__proto__') { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; + +},{"./utils":5}],4:[function(require,module,exports){ +'use strict'; + +var getSideChannel = require('side-channel'); +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + commaRoundTrip, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; + +},{"./formats":1,"./utils":5,"side-channel":16}],5:[function(require,module,exports){ +'use strict'; + +var formats = require('./formats'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + /* eslint operator-linebreak: [2, "before"] */ + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; + +},{"./formats":1}],6:[function(require,module,exports){ + +},{}],7:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); + +var callBind = require('./'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + +},{"./":8,"get-intrinsic":11}],8:[function(require,module,exports){ +'use strict'; + +var bind = require('function-bind'); +var GetIntrinsic = require('get-intrinsic'); + +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); + +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} + +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + +},{"function-bind":10,"get-intrinsic":11}],9:[function(require,module,exports){ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +},{}],10:[function(require,module,exports){ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; + +},{"./implementation":9}],11:[function(require,module,exports){ +'use strict'; + +var undefined; + +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = require('has-symbols')(); + +var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +try { + null.error; // eslint-disable-line no-unused-expressions +} catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = require('function-bind'); +var hasOwn = require('has'); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + +},{"function-bind":10,"has":14,"has-symbols":12}],12:[function(require,module,exports){ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + +},{"./shams":13}],13:[function(require,module,exports){ +'use strict'; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + +},{}],14:[function(require,module,exports){ +'use strict'; + +var bind = require('function-bind'); + +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); + +},{"function-bind":10}],15:[function(require,module,exports){ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; +var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; +var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; +var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; +var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; +var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var functionToString = Function.prototype.toString; +var $match = String.prototype.match; +var $slice = String.prototype.slice; +var $replace = String.prototype.replace; +var $toUpperCase = String.prototype.toUpperCase; +var $toLowerCase = String.prototype.toLowerCase; +var $test = RegExp.prototype.test; +var $concat = Array.prototype.concat; +var $join = Array.prototype.join; +var $arrSlice = Array.prototype.slice; +var $floor = Math.floor; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; +var gOPS = Object.getOwnPropertySymbols; +var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; +var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; +// ie, `has-tostringtag/shams +var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; +var isEnumerable = Object.prototype.propertyIsEnumerable; + +var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); + +function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1000 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); +} + +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + +module.exports = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes(s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; +} + +function quote(s) { + return $replace.call(String(s), /"/g, '"'); +} + +function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } +function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } + +// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives +function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; +} + +function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; +} + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has(obj, key) { + return hasOwn.call(obj, key); +} + +function toStr(obj) { + return objectToString.call(obj); +} + +function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; +} + +function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; +} + +function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; +} + +function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; +} + +function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); +} + +function markBoxed(str) { + return 'Object(' + str + ')'; +} + +function weakCollectionOf(type) { + return type + ' { ? }'; +} + +function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; +} + +function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; +} + +function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; +} + +function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; +} + +function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; +} + +},{"./util.inspect":6}],16:[function(require,module,exports){ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bind/callBound'); +var inspect = require('object-inspect'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); +var $Map = GetIntrinsic('%Map%', true); + +var $weakMapGet = callBound('WeakMap.prototype.get', true); +var $weakMapSet = callBound('WeakMap.prototype.set', true); +var $weakMapHas = callBound('WeakMap.prototype.has', true); +var $mapGet = callBound('Map.prototype.get', true); +var $mapSet = callBound('Map.prototype.set', true); +var $mapHas = callBound('Map.prototype.has', true); + +/* + * This function traverses the list returning the node corresponding to the + * given key. + * + * That node is also moved to the head of the list, so that if it's accessed + * again we don't need to traverse the whole list. By doing so, all the recently + * used nodes can be accessed relatively quickly. + */ +var listGetNode = function (list, key) { // eslint-disable-line consistent-return + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } +}; + +var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; +}; +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = { // eslint-disable-line no-param-reassign + key: key, + next: objects.next, + value: value + }; + } +}; +var listHas = function (objects, key) { + return !!listGetNode(objects, key); +}; + +module.exports = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + /* + * Initialize the linked list as an empty node, so that we don't have + * to special-case handling of the first node: we can always refer to + * it as (previous node).next, instead of something like (list).head + */ + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; +}; + +},{"call-bind/callBound":7,"get-intrinsic":11,"object-inspect":15}]},{},[2])(2) +}); diff --git a/node_modules/qs/lib/formats.js b/node_modules/qs/lib/formats.js new file mode 100644 index 0000000..f36cf20 --- /dev/null +++ b/node_modules/qs/lib/formats.js @@ -0,0 +1,23 @@ +'use strict'; + +var replace = String.prototype.replace; +var percentTwenties = /%20/g; + +var Format = { + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; + +module.exports = { + 'default': Format.RFC3986, + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 +}; diff --git a/node_modules/qs/lib/index.js b/node_modules/qs/lib/index.js new file mode 100644 index 0000000..0d6a97d --- /dev/null +++ b/node_modules/qs/lib/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var stringify = require('./stringify'); +var parse = require('./parse'); +var formats = require('./formats'); + +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; diff --git a/node_modules/qs/lib/parse.js b/node_modules/qs/lib/parse.js new file mode 100644 index 0000000..a4ac4fa --- /dev/null +++ b/node_modules/qs/lib/parse.js @@ -0,0 +1,263 @@ +'use strict'; + +var utils = require('./utils'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var defaults = { + allowDots: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: 'utf-8', + charsetSentinel: false, + comma: false, + decoder: utils.decode, + delimiter: '&', + depth: 5, + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1000, + parseArrays: true, + plainObjects: false, + strictNullHandling: false +}; + +var interpretNumericEntities = function (str) { + return str.replace(/&#(\d+);/g, function ($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); +}; + +var parseArrayValue = function (val, options) { + if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { + return val.split(','); + } + + return val; +}; + +// This is what browsers will submit when the ✓ character occurs in an +// application/x-www-form-urlencoded body and the encoding of the page containing +// the form is iso-8859-1, or when the submitted form has an accept-charset +// attribute of iso-8859-1. Presumably also with other charsets that do not contain +// the ✓ character, such as us-ascii. +var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + +// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. +var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + +var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + val = utils.maybeMap( + parseArrayValue(part.slice(pos + 1), options), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(val); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + if (has.call(obj, key)) { + obj[key] = utils.combine(obj[key], val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options, valuesParsed) { + var leaf = valuesParsed ? val : parseArrayValue(val, options); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + obj = [].concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if (!options.parseArrays && cleanRoot === '') { + obj = { 0: leaf }; + } else if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else if (cleanRoot !== '__proto__') { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = options.depth > 0 && brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options, valuesParsed); +}; + +var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + return { + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); +}; diff --git a/node_modules/qs/lib/stringify.js b/node_modules/qs/lib/stringify.js new file mode 100644 index 0000000..997d3ee --- /dev/null +++ b/node_modules/qs/lib/stringify.js @@ -0,0 +1,320 @@ +'use strict'; + +var getSideChannel = require('side-channel'); +var utils = require('./utils'); +var formats = require('./formats'); +var has = Object.prototype.hasOwnProperty; + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } +}; + +var isArray = Array.isArray; +var push = Array.prototype.push; +var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); +}; + +var toISO = Date.prototype.toISOString; + +var defaultFormat = formats['default']; +var defaults = { + addQueryPrefix: false, + allowDots: false, + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; +}; + +var sentinel = {}; + +var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel +) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, encoder); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + strictNullHandling, + skipNulls, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; +}; + +var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (opts && opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if (opts && 'indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (options.skipNulls && obj[key] === null) { + continue; + } + pushToArray(keys, stringify( + obj[key], + key, + generateArrayPrefix, + commaRoundTrip, + options.strictNullHandling, + options.skipNulls, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + + return joined.length > 0 ? prefix + joined : ''; +}; diff --git a/node_modules/qs/lib/utils.js b/node_modules/qs/lib/utils.js new file mode 100644 index 0000000..1e54538 --- /dev/null +++ b/node_modules/qs/lib/utils.js @@ -0,0 +1,252 @@ +'use strict'; + +var formats = require('./formats'); + +var has = Object.prototype.hasOwnProperty; +var isArray = Array.isArray; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } +}; + +var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +var decode = function (str, decoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } +}; + +var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + /* eslint operator-linebreak: [2, "before"] */ + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + compactQueue(queue); + + return value; +}; + +var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +var combine = function combine(a, b) { + return [].concat(a, b); +}; + +var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +}; + +module.exports = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isRegExp: isRegExp, + maybeMap: maybeMap, + merge: merge +}; diff --git a/node_modules/qs/package.json b/node_modules/qs/package.json new file mode 100644 index 0000000..2d4f880 --- /dev/null +++ b/node_modules/qs/package.json @@ -0,0 +1,105 @@ +{ + "_from": "qs@6.11.1", + "_id": "qs@6.11.1", + "_inBundle": false, + "_integrity": "sha512-0wsrzgTz/kAVIeuxSjnpGC56rzYtr6JT/2BwEvMaPhFIoYa1aGO8LbzuU1R0uUYQkLpWBTOj0l/CLAJB64J6nQ==", + "_location": "/qs", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "qs@6.11.1", + "name": "qs", + "escapedName": "qs", + "rawSpec": "6.11.1", + "saveSpec": null, + "fetchSpec": "6.11.1" + }, + "_requiredBy": [ + "/getstream" + ], + "_resolved": "https://registry.npmjs.org/qs/-/qs-6.11.1.tgz", + "_shasum": "6c29dff97f0c0060765911ba65cbc9764186109f", + "_spec": "qs@6.11.1", + "_where": "/home/other/discord_bot/node_modules/getstream", + "bugs": { + "url": "https://github.com/ljharb/qs/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "dependencies": { + "side-channel": "^1.0.4" + }, + "deprecated": false, + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.1", + "aud": "^2.0.2", + "browserify": "^16.5.2", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "has-symbols": "^1.0.3", + "iconv-lite": "^0.5.1", + "in-publish": "^2.0.1", + "mkdirp": "^0.5.5", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.3", + "qs-iconv": "^1.0.4", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "tape": "^5.6.3" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/ljharb/qs", + "keywords": [ + "querystring", + "qs", + "query", + "url", + "parse", + "stringify" + ], + "license": "BSD-3-Clause", + "main": "lib/index.js", + "name": "qs", + "publishConfig": { + "ignore": [ + "!dist/*", + "bower.json", + "component.json", + ".github/workflows" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/qs.git" + }, + "scripts": { + "dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js", + "lint": "eslint --ext=js,mjs .", + "postlint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "posttest": "aud --production", + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest && npm run dist", + "pretest": "npm run --silent readme && npm run --silent lint", + "readme": "evalmd README.md", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'" + }, + "version": "6.11.1" +} diff --git a/node_modules/qs/test/parse.js b/node_modules/qs/test/parse.js new file mode 100644 index 0000000..7d7b4dd --- /dev/null +++ b/node_modules/qs/test/parse.js @@ -0,0 +1,855 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; + +test('parse()', function (t) { + t.test('parses a simple string', function (st) { + st.deepEqual(qs.parse('0=foo'), { 0: 'foo' }); + st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' }); + st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } }); + st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } }); + st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } }); + st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null }); + st.deepEqual(qs.parse('foo'), { foo: '' }); + st.deepEqual(qs.parse('foo='), { foo: '' }); + st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' }); + st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' }); + st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' }); + st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' }); + st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' }); + st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null }); + st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' }); + st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), { + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + st.end(); + }); + + t.test('arrayFormat: brackets allows only explicit arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'brackets' }), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('arrayFormat: indices allows only indexed arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'indices' }), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('arrayFormat: comma allows only comma-separated arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'comma' }), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('arrayFormat: repeat allows only repeated values', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'repeat' }), { a: 'b,c' }); + st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); + st.end(); + }); + + t.test('allows enabling dot notation', function (st) { + st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' }); + st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string'); + t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string'); + t.deepEqual( + qs.parse('a[b][c][d][e][f][g][h]=i'), + { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, + 'defaults to a depth of 5' + ); + + t.test('only parses one level when depth = 1', function (st) { + st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } }); + st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } }); + st.end(); + }); + + t.test('uses original key when depth = 0', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: 0 }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: 0 }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.test('uses original key when depth = false', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: false }), { 'a[0]': 'b', 'a[1]': 'c' }); + st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: false }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); + st.end(); + }); + + t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array'); + + t.test('parses an explicit array', function (st) { + st.deepEqual(qs.parse('a[]=b'), { a: ['b'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] }); + st.end(); + }); + + t.test('parses a mix of simple and explicit arrays', function (st) { + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + + st.end(); + }); + + t.test('parses a nested array', function (st) { + st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } }); + st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } }); + st.end(); + }); + + t.test('allows to specify array indices', function (st) { + st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] }); + st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } }); + st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] }); + st.end(); + }); + + t.test('limits specific array indices to arrayLimit', function (st) { + st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); + + st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a'), { a: { 21: 'a' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number'); + + t.test('supports encoded = signs', function (st) { + st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' }); + st.end(); + }); + + t.test('is ok with url encoded strings', function (st) { + st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } }); + st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } }); + st.end(); + }); + + t.test('allows brackets in the value', function (st) { + st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' }); + st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' }); + st.end(); + }); + + t.test('allows empty values', function (st) { + st.deepEqual(qs.parse(''), {}); + st.deepEqual(qs.parse(null), {}); + st.deepEqual(qs.parse(undefined), {}); + st.end(); + }); + + t.test('transforms arrays to objects', function (st) { + st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } }); + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } }); + st.end(); + }); + + t.test('transforms arrays to objects (dot notation)', function (st) { + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] }); + st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + st.end(); + }); + + t.test('correctly prunes undefined values when converting an array to an object', function (st) { + st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } }); + st.end(); + }); + + t.test('supports malformed uri characters', function (st) { + st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null }); + st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' }); + st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' }); + st.end(); + }); + + t.test('doesn\'t produce empty keys', function (st) { + st.deepEqual(qs.parse('_r=1&'), { _r: '1' }); + st.end(); + }); + + t.test('cannot access Object prototype', function (st) { + qs.parse('constructor[prototype][bad]=bad'); + qs.parse('bad[constructor][prototype][bad]=bad'); + st.equal(typeof Object.prototype.bad, 'undefined'); + st.end(); + }); + + t.test('parses arrays of objects', function (st) { + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] }); + st.end(); + }); + + t.test('allows for empty strings in arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] }); + + st.deepEqual( + qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 20 + array indices: null then empty string works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 0 + array brackets: null then empty string works' + ); + + st.deepEqual( + qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 20 + array indices: empty string then null works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 0 + array brackets: empty string then null works' + ); + + st.deepEqual( + qs.parse('a[]=&a[]=b&a[]=c'), + { a: ['', 'b', 'c'] }, + 'array brackets: empty strings work' + ); + st.end(); + }); + + t.test('compacts sparse arrays', function (st) { + st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] }); + st.end(); + }); + + t.test('parses sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] }); + st.end(); + }); + + t.test('parses semi-parsed strings', function (st) { + st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } }); + st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } }); + st.end(); + }); + + t.test('parses buffers correctly', function (st) { + var b = SaferBuffer.from('test'); + st.deepEqual(qs.parse({ a: b }), { a: b }); + st.end(); + }); + + t.test('parses jquery-param strings', function (st) { + // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8' + var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8'; + var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] }; + st.deepEqual(qs.parse(encoded), expected); + st.end(); + }); + + t.test('continues parsing when no parent is found', function (st) { + st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' }); + st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' }); + st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' }); + st.end(); + }); + + t.test('does not error when parsing a very long array', function (st) { + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str = str + '&' + str; + } + + st.doesNotThrow(function () { + qs.parse(str); + }); + + st.end(); + }); + + t.test('should not throw when a native prototype has an enumerable property', function (st) { + Object.prototype.crash = ''; + Array.prototype.crash = ''; + st.doesNotThrow(qs.parse.bind(null, 'a=b')); + st.deepEqual(qs.parse('a=b'), { a: 'b' }); + st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c')); + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + st.end(); + }); + + t.test('parses a string with an alternative string delimiter', function (st) { + st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('parses a string with an alternative RegExp delimiter', function (st) { + st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not use non-splittable objects as delimiters', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding parameter limit', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' }); + st.end(); + }); + + t.test('allows setting the parameter limit to Infinity', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding array limit', function (st) { + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } }); + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + st.end(); + }); + + t.test('allows disabling array parsing', function (st) { + var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false }); + st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } }); + st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array'); + + var emptyBrackets = qs.parse('a[]=b', { parseArrays: false }); + st.deepEqual(emptyBrackets, { a: { 0: 'b' } }); + st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array'); + + st.end(); + }); + + t.test('allows for query string prefix', function (st) { + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); + + st.end(); + }); + + t.test('parses an object', function (st) { + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses string with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] }); + st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } }); + st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' }); + st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null }); + + // test cases inversed from from stringify tests + st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] }); + + st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] }); + + st.end(); + }); + + t.test('parses values with comma as array divider', function (st) { + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' }); + st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] }); + st.end(); + }); + + t.test('use number decoder, parses string that has one number with comma option enabled', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (!isNaN(Number(str))) { + return parseFloat(str); + } + return defaultDecoder(str, defaultDecoder, charset, type); + }; + + st.deepEqual(qs.parse('foo=1', { comma: true, decoder: decoder }), { foo: 1 }); + st.deepEqual(qs.parse('foo=0', { comma: true, decoder: decoder }), { foo: 0 }); + + st.end(); + }); + + t.test('parses brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) { + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=', { comma: true }), { foo: [['1', '2', '3'], ''] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] }); + st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] }); + + st.end(); + }); + + t.test('parses comma delimited array while having percent-encoded comma treated as normal text', function (st) { + st.deepEqual(qs.parse('foo=a%2Cb', { comma: true }), { foo: 'a,b' }); + st.deepEqual(qs.parse('foo=a%2C%20b,d', { comma: true }), { foo: ['a, b', 'd'] }); + st.deepEqual(qs.parse('foo=a%2C%20b,c%2C%20d', { comma: true }), { foo: ['a, b', 'c, d'] }); + + st.end(); + }); + + t.test('parses an object in dot notation', function (st) { + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input, { allowDots: true }); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses an object and not child values', function (st) { + var input = { + 'user[name]': { 'pop[bob]': { test: 3 } }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': { test: 3 } }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + st.deepEqual(result, { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + var parsed; + + st.doesNotThrow(function () { + parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + st.equal('bar' in parsed.foo, true); + st.equal('baz' in parsed.foo, true); + st.equal(parsed.foo.bar, 'baz'); + st.deepEqual(parsed.foo.baz, a); + st.end(); + }); + + t.test('does not crash when parsing deep objects', function (st) { + var parsed; + var str = 'foo'; + + for (var i = 0; i < 5000; i++) { + str += '[p]'; + } + + str += '=bar'; + + st.doesNotThrow(function () { + parsed = qs.parse(str, { depth: 5000 }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + + var depth = 0; + var ref = parsed.foo; + while ((ref = ref.p)) { + depth += 1; + } + + st.equal(depth, 5000, 'parsed is 5000 properties deep'); + + st.end(); + }); + + t.test('parses null objects correctly', { skip: !Object.create }, function (st) { + var a = Object.create(null); + a.b = 'c'; + + st.deepEqual(qs.parse(a), { b: 'c' }); + var result = qs.parse({ a: a }); + st.equal('a' in result, true, 'result has "a" property'); + st.deepEqual(result.a, a); + st.end(); + }); + + t.test('parses dates correctly', function (st) { + var now = new Date(); + st.deepEqual(qs.parse({ a: now }), { a: now }); + st.end(); + }); + + t.test('parses regular expressions correctly', function (st) { + var re = /^test$/; + st.deepEqual(qs.parse({ a: re }), { a: re }); + st.end(); + }); + + t.test('does not allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {}); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {}); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: false }), + {}, + 'bare "toString" results in {}' + ); + + st.end(); + }); + + t.test('can allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: true }), + { toString: '' }, + 'bare "toString" results in { toString: "" }' + ); + + st.end(); + }); + + t.test('params starting with a closing bracket', function (st) { + st.deepEqual(qs.parse(']=toString'), { ']': 'toString' }); + st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' }); + st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' }); + st.end(); + }); + + t.test('params starting with a starting bracket', function (st) { + st.deepEqual(qs.parse('[=toString'), { '[': 'toString' }); + st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' }); + st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' }); + st.end(); + }); + + t.test('add keys to objects', function (st) { + st.deepEqual( + qs.parse('a[b]=c&a=d'), + { a: { b: 'c', d: true } }, + 'can add keys to objects' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString'), + { a: { b: 'c' } }, + 'can not overwrite prototype' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { allowPrototypes: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with allowPrototypes true' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { plainObjects: true }), + { __proto__: null, a: { __proto__: null, b: 'c', toString: true } }, + 'can overwrite prototype with plainObjects true' + ); + + st.end(); + }); + + t.test('dunder proto is ignored', function (st) { + var payload = 'categories[__proto__]=login&categories[__proto__]&categories[length]=42'; + var result = qs.parse(payload, { allowPrototypes: true }); + + st.deepEqual( + result, + { + categories: { + length: '42' + } + }, + 'silent [[Prototype]] payload' + ); + + var plainResult = qs.parse(payload, { allowPrototypes: true, plainObjects: true }); + + st.deepEqual( + plainResult, + { + __proto__: null, + categories: { + __proto__: null, + length: '42' + } + }, + 'silent [[Prototype]] payload: plain objects' + ); + + var query = qs.parse('categories[__proto__]=cats&categories[__proto__]=dogs&categories[some][json]=toInject', { allowPrototypes: true }); + + st.notOk(Array.isArray(query.categories), 'is not an array'); + st.notOk(query.categories instanceof Array, 'is not instanceof an array'); + st.deepEqual(query.categories, { some: { json: 'toInject' } }); + st.equal(JSON.stringify(query.categories), '{"some":{"json":"toInject"}}', 'stringifies as a non-array'); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true }), + { + foo: { + bar: 'stuffs' + } + }, + 'hidden values' + ); + + st.deepEqual( + qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true, plainObjects: true }), + { + __proto__: null, + foo: { + __proto__: null, + bar: 'stuffs' + } + }, + 'hidden values: plain objects' + ); + + st.end(); + }); + + t.test('can return null objects', { skip: !Object.create }, function (st) { + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected); + st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a[0] = 'b'; + expectedArray.a.c = 'd'; + st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray); + st.end(); + }); + + t.test('can parse with custom encoding', function (st) { + st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', { + decoder: function (str) { + var reg = /%([0-9A-F]{2})/ig; + var result = []; + var parts = reg.exec(str); + while (parts) { + result.push(parseInt(parts[1], 16)); + parts = reg.exec(str); + } + return String(iconv.decode(SaferBuffer.from(result), 'shift_jis')); + } + }), { 県: '大阪府' }); + st.end(); + }); + + t.test('receives the default decoder as a second argument', function (st) { + st.plan(1); + qs.parse('a', { + decoder: function (str, defaultDecoder) { + st.equal(defaultDecoder, utils.decode); + } + }); + st.end(); + }); + + t.test('throws error with wrong decoder', function (st) { + st['throws'](function () { + qs.parse({}, { decoder: 'string' }); + }, new TypeError('Decoder has to be a function.')); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.parse('a[b]=true', options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.parse('a=b', { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('parses an iso-8859-1 string if asked to', function (st) { + st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' }); + st.end(); + }); + + var urlEncodedCheckmarkInUtf8 = '%E2%9C%93'; + var urlEncodedOSlashInUtf8 = '%C3%B8'; + var urlEncodedNumCheckmark = '%26%2310003%3B'; + var urlEncodedNumSmiley = '%26%239786%3B'; + + t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' }); + st.end(); + }); + + t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) { + st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' }); + st.end(); + }); + + t.test('should ignore an utf8 sentinel with an unknown value', function (st) { + st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' }); + st.end(); + }); + + t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) { + st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' }); + st.end(); + }); + + t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, { + charset: 'iso-8859-1', + decoder: function (str, defaultDecoder, charset) { + return str ? defaultDecoder(str, defaultDecoder, charset) : null; + }, + interpretNumericEntities: true + }), { foo: null, bar: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) { + st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '☺' }); + st.end(); + }); + + t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) { + st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' }); + st.end(); + }); + + t.test('allows for decoding keys and values differently', function (st) { + var decoder = function (str, defaultDecoder, charset, type) { + if (type === 'key') { + return defaultDecoder(str, defaultDecoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultDecoder(str, defaultDecoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.parse('KeY=vAlUe', { decoder: decoder }), { key: 'VALUE' }); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/qs/test/stringify.js b/node_modules/qs/test/stringify.js new file mode 100644 index 0000000..3227273 --- /dev/null +++ b/node_modules/qs/test/stringify.js @@ -0,0 +1,954 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); +var SaferBuffer = require('safer-buffer').Buffer; +var hasSymbols = require('has-symbols'); +var hasBigInt = typeof BigInt === 'function'; + +test('stringify()', function (t) { + t.test('stringifies a querystring object', function (st) { + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: 1 }), 'a=1'); + st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2'); + st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z'); + st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC'); + st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80'); + st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90'); + st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7'); + st.end(); + }); + + t.test('stringifies falsy values', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(null, { strictNullHandling: true }), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(0), ''); + st.end(); + }); + + t.test('stringifies symbols', { skip: !hasSymbols() }, function (st) { + st.equal(qs.stringify(Symbol.iterator), ''); + st.equal(qs.stringify([Symbol.iterator]), '0=Symbol%28Symbol.iterator%29'); + st.equal(qs.stringify({ a: Symbol.iterator }), 'a=Symbol%28Symbol.iterator%29'); + st.equal( + qs.stringify({ a: [Symbol.iterator] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=Symbol%28Symbol.iterator%29' + ); + st.end(); + }); + + t.test('stringifies bigints', { skip: !hasBigInt }, function (st) { + var three = BigInt(3); + var encodeWithN = function (value, defaultEncoder, charset) { + var result = defaultEncoder(value, defaultEncoder, charset); + return typeof value === 'bigint' ? result + 'n' : result; + }; + st.equal(qs.stringify(three), ''); + st.equal(qs.stringify([three]), '0=3'); + st.equal(qs.stringify([three], { encoder: encodeWithN }), '0=3n'); + st.equal(qs.stringify({ a: three }), 'a=3'); + st.equal(qs.stringify({ a: three }, { encoder: encodeWithN }), 'a=3n'); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[]=3' + ); + st.equal( + qs.stringify({ a: [three] }, { encodeValuesOnly: true, encoder: encodeWithN, arrayFormat: 'brackets' }), + 'a[]=3n' + ); + st.end(); + }); + + t.test('adds query prefix', function (st) { + st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); + st.end(); + }); + + t.test('with query prefix, outputs blank string given an empty object', function (st) { + st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); + st.end(); + }); + + t.test('stringifies nested falsy values', function (st) { + st.equal(qs.stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D='); + st.equal(qs.stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), 'a%5Bb%5D%5Bc%5D'); + st.equal(qs.stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies a nested object', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies a nested object with dots notation', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); + st.end(); + }); + + t.test('stringifies an array value', function (st) { + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), + 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }), + 'a=b%2Cc%2Cd', + 'comma => comma' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'default => indices' + ); + st.end(); + }); + + t.test('omits nulls when asked', function (st) { + st.equal(qs.stringify({ a: 'b', c: null }, { skipNulls: true }), 'a=b'); + st.end(); + }); + + t.test('omits nested nulls when asked', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('omits array indices when asked', function (st) { + st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); + st.end(); + }); + + t.test('stringifies an array value with one item vs multiple items', function (st) { + st.test('non-array item', function (s2t) { + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true }), 'a=c'); + + s2t.end(); + }); + + st.test('array with a single item', function (s2t) { + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a[]=c'); // so it parses back as an array + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true }), 'a[0]=c'); + + s2t.end(); + }); + + st.test('array with multiple items', function (s2t) { + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c&a[1]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c&a[]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true }), 'a[0]=c&a[1]=d'); + + s2t.end(); + }); + + st.test('array with multiple items with a comma inside', function (s2t) { + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c%2Cd,e'); + s2t.equal(qs.stringify({ a: ['c,d', 'e'] }, { arrayFormat: 'comma' }), 'a=c%2Cd%2Ce'); + + s2t.end(); + }); + + st.end(); + }); + + t.test('stringifies a nested array value', function (st) { + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[b][0]=c&a[b][1]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[b][]=c&a[b][]=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a[b]=c,d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true }), 'a[b][0]=c&a[b][1]=d'); + st.end(); + }); + + t.test('stringifies comma and empty array values', function (st) { + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'indices' }), 'a[0]=,&a[1]=&a[2]=c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'brackets' }), 'a[]=,&a[]=&a[]=c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'comma' }), 'a=,,,c,d%'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: false, arrayFormat: 'repeat' }), 'a=,&a=&a=c,d%'); + + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=%2C&a[1]=&a[2]=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=%2C&a[]=&a[]=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=%2C,,c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=%2C&a=&a=c%2Cd%25'); + + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), 'a%5B0%5D=%2C&a%5B1%5D=&a%5B2%5D=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }), 'a%5B%5D=%2C&a%5B%5D=&a%5B%5D=c%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), 'a=%2C%2C%2Cc%2Cd%25'); + st.equal(qs.stringify({ a: [',', '', 'c,d%'] }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), 'a=%2C&a=&a=c%2Cd%25'); + + st.end(); + }); + + t.test('stringifies comma and empty non-array values', function (st) { + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'indices' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'brackets' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'comma' }), 'a=,&b=&c=c,d%'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: false, arrayFormat: 'repeat' }), 'a=,&b=&c=c,d%'); + + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: true, arrayFormat: 'repeat' }), 'a=%2C&b=&c=c%2Cd%25'); + + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'indices' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'brackets' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'comma' }), 'a=%2C&b=&c=c%2Cd%25'); + st.equal(qs.stringify({ a: ',', b: '', c: 'c,d%' }, { encode: true, encodeValuesOnly: false, arrayFormat: 'repeat' }), 'a=%2C&b=&c=c%2Cd%25'); + + st.end(); + }); + + t.test('stringifies a nested array value with dots notation', function (st) { + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'indices' } + ), + 'a.b[0]=c&a.b[1]=d', + 'indices: stringifies with dots + indices' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'brackets' } + ), + 'a.b[]=c&a.b[]=d', + 'brackets: stringifies with dots + brackets' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true, arrayFormat: 'comma' } + ), + 'a.b=c,d', + 'comma: stringifies with dots + comma' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encodeValuesOnly: true } + ), + 'a.b[0]=c&a.b[1]=d', + 'default: stringifies with dots + indices' + ); + st.end(); + }); + + t.test('stringifies an object inside an array', function (st) { + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices' }), + 'a%5B0%5D%5Bb%5D=c', // a[0][b]=c + 'indices => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets' }), + 'a%5B%5D%5Bb%5D=c', // a[][b]=c + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }), + 'a%5B0%5D%5Bb%5D=c', + 'default => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices' }), + 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', + 'indices => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets' }), + 'a%5B%5D%5Bb%5D%5Bc%5D%5B%5D=1', + 'brackets => brackets' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }), + 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an array with mixed objects and primitives', function (st) { + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), + 'a[][b]=1&a[]=2&a[]=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), + '???', + 'brackets => brackets', + { skip: 'TODO: figure out what this should do' } + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an object inside an array with dots notation', function (st) { + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b=c', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false } + ), + 'a[0].b=c', + 'default => indices' + ); + + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b.c[0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b.c[]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false } + ), + 'a[0].b.c[0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('does not omit object keys when indices = false', function (st) { + st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when indices=true', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat=indices', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses repeat notation for arrays when no arrayFormat=repeat', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); + st.end(); + }); + + t.test('uses brackets notation for arrays when no arrayFormat=brackets', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); + st.end(); + }); + + t.test('stringifies a complicated object', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies an empty value', function (st) { + st.equal(qs.stringify({ a: '' }), 'a='); + st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a'); + + st.equal(qs.stringify({ a: '', b: '' }), 'a=&b='); + st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); + + st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D='); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); + + st.end(); + }); + + t.test('stringifies an empty array in different arrayFormat', function (st) { + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false }), 'b[0]=&c=c'); + // arrayFormat default + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices' }), 'b[0]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' }), 'b[]=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', commaRoundTrip: true }), 'b[]=&c=c'); + // with strictNullHandling + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', strictNullHandling: true }), 'b[0]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', strictNullHandling: true }), 'b[]&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }), 'b[]&c=c'); + // with skipNulls + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', skipNulls: true }), 'c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', skipNulls: true }), 'c=c'); + + st.end(); + }); + + t.test('stringifies a null object', { skip: !Object.create }, function (st) { + var obj = Object.create(null); + obj.a = 'b'; + st.equal(qs.stringify(obj), 'a=b'); + st.end(); + }); + + t.test('returns an empty string for invalid input', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(''), ''); + st.end(); + }); + + t.test('stringifies an object with a null object as a child', { skip: !Object.create }, function (st) { + var obj = { a: Object.create(null) }; + + obj.a.b = 'c'; + st.equal(qs.stringify(obj), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('drops keys with a value of undefined', function (st) { + st.equal(qs.stringify({ a: undefined }), ''); + + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D'); + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D='); + st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); + st.end(); + }); + + t.test('url encodes values', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('stringifies a date', function (st) { + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + st.equal(qs.stringify({ a: now }), str); + st.end(); + }); + + t.test('stringifies the weird object from qs', function (st) { + st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + st.end(); + }); + + t.test('skips properties that are part of the object prototype', function (st) { + Object.prototype.crash = 'test'; + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + delete Object.prototype.crash; + st.end(); + }); + + t.test('stringifies boolean values', function (st) { + st.equal(qs.stringify({ a: true }), 'a=true'); + st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true'); + st.equal(qs.stringify({ b: false }), 'b=false'); + st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies buffer values', function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test'); + st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test'); + st.end(); + }); + + t.test('stringifies an object using an alternative delimiter', function (st) { + st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = qs.stringify({ a: 'b', c: 'd' }); + global.Buffer = tempBuffer; + st.equal(result, 'a=b&c=d'); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + st['throws']( + function () { qs.stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var circular = { + a: 'value' + }; + circular.a = circular; + st['throws']( + function () { qs.stringify(circular); }, + /RangeError: Cyclic object value/, + 'cyclic values throw' + ); + + var arr = ['a']; + st.doesNotThrow( + function () { qs.stringify({ x: arr, y: arr }); }, + 'non-cyclic values do not throw' + ); + + st.end(); + }); + + t.test('non-circular duplicated references can still work', function (st) { + var hourOfDay = { + 'function': 'hour_of_day' + }; + + var p1 = { + 'function': 'gte', + arguments: [hourOfDay, 0] + }; + var p2 = { + 'function': 'lte', + arguments: [hourOfDay, 23] + }; + + st.equal( + qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true }), + 'filters[$and][0][function]=gte&filters[$and][0][arguments][0][function]=hour_of_day&filters[$and][0][arguments][1]=0&filters[$and][1][function]=lte&filters[$and][1][arguments][0][function]=hour_of_day&filters[$and][1][arguments][1]=23' + ); + + st.end(); + }); + + t.test('selects properties when filter=array', function (st) { + st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); + st.equal(qs.stringify({ a: 1 }, { filter: [] }), ''); + + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' } + ), + 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2] } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('supports custom representations when filter=function', function (st) { + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + calls += 1; + if (calls === 1) { + st.equal(prefix, '', 'prefix is empty'); + st.equal(value, obj); + } else if (prefix === 'c') { + return void 0; + } else if (value instanceof Date) { + st.equal(prefix, 'e[f]'); + return value.getTime(); + } + return value; + }; + + st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); + st.equal(calls, 5); + st.end(); + }); + + t.test('can disable uri encoding', function (st) { + st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); + st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c'); + st.end(); + }); + + t.test('can sort the keys', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); + st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + st.end(); + }); + + t.test('can sort the keys at depth 3 or more too', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: sort, encode: false } + ), + 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb' + ); + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: null, encode: false } + ), + 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b' + ); + st.end(); + }); + + t.test('can stringify with custom encoding', function (st) { + st.equal(qs.stringify({ 県: '大阪府', '': '' }, { + encoder: function (str) { + if (str.length === 0) { + return ''; + } + var buf = iconv.encode(str, 'shiftjis'); + var result = []; + for (var i = 0; i < buf.length; ++i) { + result.push(buf.readUInt8(i).toString(16)); + } + return '%' + result.join('%'); + } + }), '%8c%a7=%91%e5%8d%e3%95%7b&='); + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(2); + qs.stringify({ a: 1 }, { + encoder: function (str, defaultEncoder) { + st.equal(defaultEncoder, utils.encode); + } + }); + st.end(); + }); + + t.test('throws error with wrong encoder', function (st) { + st['throws'](function () { + qs.stringify({}, { encoder: 'string' }); + }, new TypeError('Encoder has to be a function.')); + st.end(); + }); + + t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { + st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, { + encoder: function (buffer) { + if (typeof buffer === 'string') { + return buffer; + } + return String.fromCharCode(buffer.readUInt8(0) + 97); + } + }), 'a=b'); + + st.equal(qs.stringify({ a: SaferBuffer.from('a b') }, { + encoder: function (buffer) { + return buffer; + } + }), 'a=a b'); + st.end(); + }); + + t.test('serializeDate option', function (st) { + var date = new Date(); + st.equal( + qs.stringify({ a: date }), + 'a=' + date.toISOString().replace(/:/g, '%3A'), + 'default is toISOString' + ); + + var mutatedDate = new Date(); + mutatedDate.toISOString = function () { + throw new SyntaxError(); + }; + st['throws'](function () { + mutatedDate.toISOString(); + }, SyntaxError); + st.equal( + qs.stringify({ a: mutatedDate }), + 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), + 'toISOString works even when method is not locally present' + ); + + var specificDate = new Date(6); + st.equal( + qs.stringify( + { a: specificDate }, + { serializeDate: function (d) { return d.getTime() * 7; } } + ), + 'a=42', + 'custom serializeDate function called' + ); + + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma' + } + ), + 'a=' + date.getTime(), + 'works with arrayFormat comma' + ); + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma', + commaRoundTrip: true + } + ), + 'a%5B%5D=' + date.getTime(), + 'works with arrayFormat comma' + ); + + st.end(); + }); + + t.test('RFC 1738 serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC1738 }), 'a+b=a+b'); + + st.equal(qs.stringify({ 'foo(ref)': 'bar' }, { format: qs.formats.RFC1738 }), 'foo(ref)=bar'); + + st.end(); + }); + + t.test('RFC 3986 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC3986 }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Backward compatibility to RFC 3986', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }), 'a%20b=a%20b'); + + st.end(); + }); + + t.test('Edge cases and unknown formats', function (st) { + ['UFO1234', false, 1234, null, {}, []].forEach(function (format) { + st['throws']( + function () { + qs.stringify({ a: 'b c' }, { format: format }); + }, + new TypeError('Unknown format option provided.') + ); + }); + st.end(); + }); + + t.test('encodeValuesOnly', function (st) { + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } + ), + 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] } + ), + 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h' + ); + st.end(); + }); + + t.test('encodeValuesOnly - strictNullHandling', function (st) { + st.equal( + qs.stringify( + { a: { b: null } }, + { encodeValuesOnly: true, strictNullHandling: true } + ), + 'a[b]' + ); + st.end(); + }); + + t.test('throws if an invalid charset is specified', function (st) { + st['throws'](function () { + qs.stringify({ a: 'b' }, { charset: 'foobar' }); + }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); + st.end(); + }); + + t.test('respects a charset of iso-8859-1', function (st) { + st.equal(qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }), '%E6=%E6'); + st.end(); + }); + + t.test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function (st) { + st.equal(qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B'); + st.end(); + }); + + t.test('respects an explicit charset of utf-8 (the default)', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charset: 'utf-8' }), 'a=%C3%A6'); + st.end(); + }); + + t.test('adds the right sentinel when instructed to and the charset is utf-8', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' }), 'utf8=%E2%9C%93&a=%C3%A6'); + st.end(); + }); + + t.test('adds the right sentinel when instructed to and the charset is iso-8859-1', function (st) { + st.equal(qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }), 'utf8=%26%2310003%3B&a=%E6'); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.stringify({}, options); + st.deepEqual(options, {}); + st.end(); + }); + + t.test('strictNullHandling works with custom filter', function (st) { + var filter = function (prefix, value) { + return value; + }; + + var options = { strictNullHandling: true, filter: filter }; + st.equal(qs.stringify({ key: null }, options), 'key'); + st.end(); + }); + + t.test('strictNullHandling works with null serializeDate', function (st) { + var serializeDate = function () { + return null; + }; + var options = { strictNullHandling: true, serializeDate: serializeDate }; + var date = new Date(); + st.equal(qs.stringify({ key: date }, options), 'key'); + st.end(); + }); + + t.test('allows for encoding keys and values differently', function (st) { + var encoder = function (str, defaultEncoder, charset, type) { + if (type === 'key') { + return defaultEncoder(str, defaultEncoder, charset, type).toLowerCase(); + } + if (type === 'value') { + return defaultEncoder(str, defaultEncoder, charset, type).toUpperCase(); + } + throw 'this should never happen! type: ' + type; + }; + + st.deepEqual(qs.stringify({ KeY: 'vAlUe' }, { encoder: encoder }), 'key=VALUE'); + st.end(); + }); + + t.test('objects inside arrays', function (st) { + var obj = { a: { b: { c: 'd', e: 'f' } } }; + var withArray = { a: { b: [{ c: 'd', e: 'f' }] } }; + + st.equal(qs.stringify(obj, { encode: false }), 'a[b][c]=d&a[b][e]=f', 'no array, no arrayFormat'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'bracket' }), 'a[b][c]=d&a[b][e]=f', 'no array, bracket'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'indices' }), 'a[b][c]=d&a[b][e]=f', 'no array, indices'); + st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'comma' }), 'a[b][c]=d&a[b][e]=f', 'no array, comma'); + + st.equal(qs.stringify(withArray, { encode: false }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, no arrayFormat'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'bracket' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, bracket'); + st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'indices' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, indices'); + st.equal( + qs.stringify(withArray, { encode: false, arrayFormat: 'comma' }), + '???', + 'array, comma', + { skip: 'TODO: figure out what this should do' } + ); + + st.end(); + }); + + t.test('stringifies sparse arrays', function (st) { + /* eslint no-sparse-arrays: 0 */ + st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true }), 'a[1]=2&a[4]=1'); + st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true }), 'a[1][b][2][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true }), 'a[1][2][3][c]=1'); + st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true }), 'a[1][2][3][c][1]=1'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/qs/test/utils.js b/node_modules/qs/test/utils.js new file mode 100644 index 0000000..aa84dfd --- /dev/null +++ b/node_modules/qs/test/utils.js @@ -0,0 +1,136 @@ +'use strict'; + +var test = require('tape'); +var inspect = require('object-inspect'); +var SaferBuffer = require('safer-buffer').Buffer; +var forEach = require('for-each'); +var utils = require('../lib/utils'); + +test('merge()', function (t) { + t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null'); + + t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array'); + + t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); + + var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); + t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); + + var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); + t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); + + var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); + t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); + + var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); + t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); + + var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar'); + t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); + + t.test( + 'avoids invoking array setters unnecessarily', + { skip: typeof Object.defineProperty !== 'function' }, + function (st) { + var setCount = 0; + var getCount = 0; + var observed = []; + Object.defineProperty(observed, 0, { + get: function () { + getCount += 1; + return { bar: 'baz' }; + }, + set: function () { setCount += 1; } + }); + utils.merge(observed, [null]); + st.equal(setCount, 0); + st.equal(getCount, 1); + observed[0] = observed[0]; // eslint-disable-line no-self-assign + st.equal(setCount, 1); + st.equal(getCount, 2); + st.end(); + } + ); + + t.end(); +}); + +test('assign()', function (t) { + var target = { a: 1, b: 2 }; + var source = { b: 3, c: 4 }; + var result = utils.assign(target, source); + + t.equal(result, target, 'returns the target'); + t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); + t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); + + t.end(); +}); + +test('combine()', function (t) { + t.test('both arrays', function (st) { + var a = [1]; + var b = [2]; + var combined = utils.combine(a, b); + + st.deepEqual(a, [1], 'a is not mutated'); + st.deepEqual(b, [2], 'b is not mutated'); + st.notEqual(a, combined, 'a !== combined'); + st.notEqual(b, combined, 'b !== combined'); + st.deepEqual(combined, [1, 2], 'combined is a + b'); + + st.end(); + }); + + t.test('one array, one non-array', function (st) { + var aN = 1; + var a = [aN]; + var bN = 2; + var b = [bN]; + + var combinedAnB = utils.combine(aN, b); + st.deepEqual(b, [bN], 'b is not mutated'); + st.notEqual(aN, combinedAnB, 'aN + b !== aN'); + st.notEqual(a, combinedAnB, 'aN + b !== a'); + st.notEqual(bN, combinedAnB, 'aN + b !== bN'); + st.notEqual(b, combinedAnB, 'aN + b !== b'); + st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); + + var combinedABn = utils.combine(a, bN); + st.deepEqual(a, [aN], 'a is not mutated'); + st.notEqual(aN, combinedABn, 'a + bN !== aN'); + st.notEqual(a, combinedABn, 'a + bN !== a'); + st.notEqual(bN, combinedABn, 'a + bN !== bN'); + st.notEqual(b, combinedABn, 'a + bN !== b'); + st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); + + st.end(); + }); + + t.test('neither is an array', function (st) { + var combined = utils.combine(1, 2); + st.notEqual(1, combined, '1 + 2 !== 1'); + st.notEqual(2, combined, '1 + 2 !== 2'); + st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); + + st.end(); + }); + + t.end(); +}); + +test('isBuffer()', function (t) { + forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) { + t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer'); + }); + + var fakeBuffer = { constructor: Buffer }; + t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer'); + + var saferBuffer = SaferBuffer.from('abc'); + t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); + + var buffer = Buffer.from && Buffer.alloc ? Buffer.from('abc') : new Buffer('abc'); + t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer'); + t.end(); +}); diff --git a/node_modules/rc/LICENSE.APACHE2 b/node_modules/rc/LICENSE.APACHE2 new file mode 100644 index 0000000..6366c04 --- /dev/null +++ b/node_modules/rc/LICENSE.APACHE2 @@ -0,0 +1,15 @@ +Apache License, Version 2.0 + +Copyright (c) 2011 Dominic Tarr + +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/rc/LICENSE.BSD b/node_modules/rc/LICENSE.BSD new file mode 100644 index 0000000..96bb796 --- /dev/null +++ b/node_modules/rc/LICENSE.BSD @@ -0,0 +1,26 @@ +Copyright (c) 2013, Dominic Tarr +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those +of the authors and should not be interpreted as representing official policies, +either expressed or implied, of the FreeBSD Project. diff --git a/node_modules/rc/LICENSE.MIT b/node_modules/rc/LICENSE.MIT new file mode 100644 index 0000000..6eafbd7 --- /dev/null +++ b/node_modules/rc/LICENSE.MIT @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2011 Dominic Tarr + +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/rc/README.md b/node_modules/rc/README.md new file mode 100644 index 0000000..e6522e2 --- /dev/null +++ b/node_modules/rc/README.md @@ -0,0 +1,227 @@ +# rc + +The non-configurable configuration loader for lazy people. + +## Usage + +The only option is to pass rc the name of your app, and your default configuration. + +```javascript +var conf = require('rc')(appname, { + //defaults go here. + port: 2468, + + //defaults which are objects will be merged, not replaced + views: { + engine: 'jade' + } +}); +``` + +`rc` will return your configuration options merged with the defaults you specify. +If you pass in a predefined defaults object, it will be mutated: + +```javascript +var conf = {}; +require('rc')(appname, conf); +``` + +If `rc` finds any config files for your app, the returned config object will have +a `configs` array containing their paths: + +```javascript +var appCfg = require('rc')(appname, conf); +appCfg.configs[0] // /etc/appnamerc +appCfg.configs[1] // /home/dominictarr/.config/appname +appCfg.config // same as appCfg.configs[appCfg.configs.length - 1] +``` + +## Standards + +Given your application name (`appname`), rc will look in all the obvious places for configuration. + + * command line arguments, parsed by minimist _(e.g. `--foo baz`, also nested: `--foo.bar=baz`)_ + * environment variables prefixed with `${appname}_` + * or use "\_\_" to indicate nested properties
_(e.g. `appname_foo__bar__baz` => `foo.bar.baz`)_ + * if you passed an option `--config file` then from that file + * a local `.${appname}rc` or the first found looking in `./ ../ ../../ ../../../` etc. + * `$HOME/.${appname}rc` + * `$HOME/.${appname}/config` + * `$HOME/.config/${appname}` + * `$HOME/.config/${appname}/config` + * `/etc/${appname}rc` + * `/etc/${appname}/config` + * the defaults object you passed in. + +All configuration sources that were found will be flattened into one object, +so that sources **earlier** in this list override later ones. + + +## Configuration File Formats + +Configuration files (e.g. `.appnamerc`) may be in either [json](http://json.org/example) or [ini](http://en.wikipedia.org/wiki/INI_file) format. **No** file extension (`.json` or `.ini`) should be used. The example configurations below are equivalent: + + +#### Formatted as `ini` + +``` +; You can include comments in `ini` format if you want. + +dependsOn=0.10.0 + + +; `rc` has built-in support for ini sections, see? + +[commands] + www = ./commands/www + console = ./commands/repl + + +; You can even do nested sections + +[generators.options] + engine = ejs + +[generators.modules] + new = generate-new + engine = generate-backend + +``` + +#### Formatted as `json` + +```javascript +{ + // You can even comment your JSON, if you want + "dependsOn": "0.10.0", + "commands": { + "www": "./commands/www", + "console": "./commands/repl" + }, + "generators": { + "options": { + "engine": "ejs" + }, + "modules": { + "new": "generate-new", + "backend": "generate-backend" + } + } +} +``` + +Comments are stripped from JSON config via [strip-json-comments](https://github.com/sindresorhus/strip-json-comments). + +> Since ini, and env variables do not have a standard for types, your application needs be prepared for strings. + +To ensure that string representations of booleans and numbers are always converted into their proper types (especially useful if you intend to do strict `===` comparisons), consider using a module such as [parse-strings-in-object](https://github.com/anselanza/parse-strings-in-object) to wrap the config object returned from rc. + + +## Simple example demonstrating precedence +Assume you have an application like this (notice the hard-coded defaults passed to rc): +``` +const conf = require('rc')('myapp', { + port: 12345, + mode: 'test' +}); + +console.log(JSON.stringify(conf, null, 2)); +``` +You also have a file `config.json`, with these contents: +``` +{ + "port": 9000, + "foo": "from config json", + "something": "else" +} +``` +And a file `.myapprc` in the same folder, with these contents: +``` +{ + "port": "3001", + "foo": "bar" +} +``` +Here is the expected output from various commands: + +`node .` +``` +{ + "port": "3001", + "mode": "test", + "foo": "bar", + "_": [], + "configs": [ + "/Users/stephen/repos/conftest/.myapprc" + ], + "config": "/Users/stephen/repos/conftest/.myapprc" +} +``` +*Default `mode` from hard-coded object is retained, but port is overridden by `.myapprc` file (automatically found based on appname match), and `foo` is added.* + + +`node . --foo baz` +``` +{ + "port": "3001", + "mode": "test", + "foo": "baz", + "_": [], + "configs": [ + "/Users/stephen/repos/conftest/.myapprc" + ], + "config": "/Users/stephen/repos/conftest/.myapprc" +} +``` +*Same result as above but `foo` is overridden because command-line arguments take precedence over `.myapprc` file.* + +`node . --foo barbar --config config.json` +``` +{ + "port": 9000, + "mode": "test", + "foo": "barbar", + "something": "else", + "_": [], + "config": "config.json", + "configs": [ + "/Users/stephen/repos/conftest/.myapprc", + "config.json" + ] +} +``` +*Now the `port` comes from the `config.json` file specified (overriding the value from `.myapprc`), and `foo` value is overriden by command-line despite also being specified in the `config.json` file.* + + + +## Advanced Usage + +#### Pass in your own `argv` + +You may pass in your own `argv` as the third argument to `rc`. This is in case you want to [use your own command-line opts parser](https://github.com/dominictarr/rc/pull/12). + +```javascript +require('rc')(appname, defaults, customArgvParser); +``` + +## Pass in your own parser + +If you have a special need to use a non-standard parser, +you can do so by passing in the parser as the 4th argument. +(leave the 3rd as null to get the default args parser) + +```javascript +require('rc')(appname, defaults, null, parser); +``` + +This may also be used to force a more strict format, +such as strict, valid JSON only. + +## Note on Performance + +`rc` is running `fs.statSync`-- so make sure you don't use it in a hot code path (e.g. a request handler) + + +## License + +Multi-licensed under the two-clause BSD License, MIT License, or Apache License, version 2.0 diff --git a/node_modules/rc/browser.js b/node_modules/rc/browser.js new file mode 100644 index 0000000..8c230c5 --- /dev/null +++ b/node_modules/rc/browser.js @@ -0,0 +1,7 @@ + +// when this is loaded into the browser, +// just use the defaults... + +module.exports = function (name, defaults) { + return defaults +} diff --git a/node_modules/rc/cli.js b/node_modules/rc/cli.js new file mode 100755 index 0000000..ab05b60 --- /dev/null +++ b/node_modules/rc/cli.js @@ -0,0 +1,4 @@ +#! /usr/bin/env node +var rc = require('./index') + +console.log(JSON.stringify(rc(process.argv[2]), false, 2)) diff --git a/node_modules/rc/index.js b/node_modules/rc/index.js new file mode 100755 index 0000000..65eb47a --- /dev/null +++ b/node_modules/rc/index.js @@ -0,0 +1,53 @@ +var cc = require('./lib/utils') +var join = require('path').join +var deepExtend = require('deep-extend') +var etc = '/etc' +var win = process.platform === "win32" +var home = win + ? process.env.USERPROFILE + : process.env.HOME + +module.exports = function (name, defaults, argv, parse) { + if('string' !== typeof name) + throw new Error('rc(name): name *must* be string') + if(!argv) + argv = require('minimist')(process.argv.slice(2)) + defaults = ( + 'string' === typeof defaults + ? cc.json(defaults) : defaults + ) || {} + + parse = parse || cc.parse + + var env = cc.env(name + '_') + + var configs = [defaults] + var configFiles = [] + function addConfigFile (file) { + if (configFiles.indexOf(file) >= 0) return + var fileConfig = cc.file(file) + if (fileConfig) { + configs.push(parse(fileConfig)) + configFiles.push(file) + } + } + + // which files do we look at? + if (!win) + [join(etc, name, 'config'), + join(etc, name + 'rc')].forEach(addConfigFile) + if (home) + [join(home, '.config', name, 'config'), + join(home, '.config', name), + join(home, '.' + name, 'config'), + join(home, '.' + name + 'rc')].forEach(addConfigFile) + addConfigFile(cc.find('.'+name+'rc')) + if (env.config) addConfigFile(env.config) + if (argv.config) addConfigFile(argv.config) + + return deepExtend.apply(null, configs.concat([ + env, + argv, + configFiles.length ? {configs: configFiles, config: configFiles[configFiles.length - 1]} : undefined, + ])) +} diff --git a/node_modules/rc/lib/utils.js b/node_modules/rc/lib/utils.js new file mode 100644 index 0000000..8b3beff --- /dev/null +++ b/node_modules/rc/lib/utils.js @@ -0,0 +1,104 @@ +'use strict'; +var fs = require('fs') +var ini = require('ini') +var path = require('path') +var stripJsonComments = require('strip-json-comments') + +var parse = exports.parse = function (content) { + + //if it ends in .json or starts with { then it must be json. + //must be done this way, because ini accepts everything. + //can't just try and parse it and let it throw if it's not ini. + //everything is ini. even json with a syntax error. + + if(/^\s*{/.test(content)) + return JSON.parse(stripJsonComments(content)) + return ini.parse(content) + +} + +var file = exports.file = function () { + var args = [].slice.call(arguments).filter(function (arg) { return arg != null }) + + //path.join breaks if it's a not a string, so just skip this. + for(var i in args) + if('string' !== typeof args[i]) + return + + var file = path.join.apply(null, args) + var content + try { + return fs.readFileSync(file,'utf-8') + } catch (err) { + return + } +} + +var json = exports.json = function () { + var content = file.apply(null, arguments) + return content ? parse(content) : null +} + +var env = exports.env = function (prefix, env) { + env = env || process.env + var obj = {} + var l = prefix.length + for(var k in env) { + if(k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) { + + var keypath = k.substring(l).split('__') + + // Trim empty strings from keypath array + var _emptyStringIndex + while ((_emptyStringIndex=keypath.indexOf('')) > -1) { + keypath.splice(_emptyStringIndex, 1) + } + + var cursor = obj + keypath.forEach(function _buildSubObj(_subkey,i){ + + // (check for _subkey first so we ignore empty strings) + // (check for cursor to avoid assignment to primitive objects) + if (!_subkey || typeof cursor !== 'object') + return + + // If this is the last key, just stuff the value in there + // Assigns actual value from env variable to final key + // (unless it's just an empty string- in that case use the last valid key) + if (i === keypath.length-1) + cursor[_subkey] = env[k] + + + // Build sub-object if nothing already exists at the keypath + if (cursor[_subkey] === undefined) + cursor[_subkey] = {} + + // Increment cursor used to track the object at the current depth + cursor = cursor[_subkey] + + }) + + } + + } + + return obj +} + +var find = exports.find = function () { + var rel = path.join.apply(null, [].slice.call(arguments)) + + function find(start, rel) { + var file = path.join(start, rel) + try { + fs.statSync(file) + return file + } catch (err) { + if(path.dirname(start) !== start) // root + return find(path.dirname(start), rel) + } + } + return find(process.cwd(), rel) +} + + diff --git a/node_modules/rc/package.json b/node_modules/rc/package.json new file mode 100644 index 0000000..4d929b1 --- /dev/null +++ b/node_modules/rc/package.json @@ -0,0 +1,68 @@ +{ + "_args": [ + [ + "rc@1.2.8", + "/home/other/discord_bot" + ] + ], + "_from": "rc@1.2.8", + "_id": "rc@1.2.8", + "_inBundle": false, + "_integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "_location": "/rc", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "rc@1.2.8", + "name": "rc", + "escapedName": "rc", + "rawSpec": "1.2.8", + "saveSpec": null, + "fetchSpec": "1.2.8" + }, + "_requiredBy": [ + "/registry-auth-token", + "/registry-url" + ], + "_resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "_spec": "1.2.8", + "_where": "/home/other/discord_bot", + "author": { + "name": "Dominic Tarr", + "email": "dominic.tarr@gmail.com", + "url": "dominictarr.com" + }, + "bin": { + "rc": "cli.js" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/dominictarr/rc/issues" + }, + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "description": "hardwired configuration loader", + "homepage": "https://github.com/dominictarr/rc#readme", + "keywords": [ + "config", + "rc", + "unix", + "defaults" + ], + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "main": "index.js", + "name": "rc", + "repository": { + "type": "git", + "url": "git+https://github.com/dominictarr/rc.git" + }, + "scripts": { + "test": "set -e; node test/test.js; node test/ini.js; node test/nested-env-vars.js" + }, + "version": "1.2.8" +} diff --git a/node_modules/rc/test/ini.js b/node_modules/rc/test/ini.js new file mode 100644 index 0000000..e6857f8 --- /dev/null +++ b/node_modules/rc/test/ini.js @@ -0,0 +1,16 @@ +var cc =require('../lib/utils') +var INI = require('ini') +var assert = require('assert') + +function test(obj) { + + var _json, _ini + var json = cc.parse (_json = JSON.stringify(obj)) + var ini = cc.parse (_ini = INI.stringify(obj)) + console.log(_ini, _json) + assert.deepEqual(json, ini) +} + + +test({hello: true}) + diff --git a/node_modules/rc/test/nested-env-vars.js b/node_modules/rc/test/nested-env-vars.js new file mode 100644 index 0000000..0ecd176 --- /dev/null +++ b/node_modules/rc/test/nested-env-vars.js @@ -0,0 +1,50 @@ + +var seed = Math.random(); +var n = 'rc'+ seed; +var N = 'RC'+ seed; +var assert = require('assert') + + +// Basic usage +process.env[n+'_someOpt__a'] = 42 +process.env[n+'_someOpt__x__'] = 99 +process.env[n+'_someOpt__a__b'] = 186 +process.env[n+'_someOpt__a__b__c'] = 243 +process.env[n+'_someOpt__x__y'] = 1862 +process.env[n+'_someOpt__z'] = 186577 + +// Should ignore empty strings from orphaned '__' +process.env[n+'_someOpt__z__x__'] = 18629 +process.env[n+'_someOpt__w__w__'] = 18629 + +// Leading '__' should ignore everything up to 'z' +process.env[n+'___z__i__'] = 9999 + +// should ignore case for config name section. +process.env[N+'_test_upperCase'] = 187 + +function testPrefix(prefix) { + var config = require('../')(prefix, { + option: true + }) + + console.log('\n\n------ nested-env-vars ------\n',{prefix: prefix}, '\n', config); + + assert.equal(config.option, true) + assert.equal(config.someOpt.a, 42) + assert.equal(config.someOpt.x, 99) + // Should not override `a` once it's been set + assert.equal(config.someOpt.a/*.b*/, 42) + // Should not override `x` once it's been set + assert.equal(config.someOpt.x/*.y*/, 99) + assert.equal(config.someOpt.z, 186577) + // Should not override `z` once it's been set + assert.equal(config.someOpt.z/*.x*/, 186577) + assert.equal(config.someOpt.w.w, 18629) + assert.equal(config.z.i, 9999) + + assert.equal(config.test_upperCase, 187) +} + +testPrefix(n); +testPrefix(N); diff --git a/node_modules/rc/test/test.js b/node_modules/rc/test/test.js new file mode 100644 index 0000000..4f63351 --- /dev/null +++ b/node_modules/rc/test/test.js @@ -0,0 +1,59 @@ + +var n = 'rc'+Math.random() +var assert = require('assert') + +process.env[n+'_envOption'] = 42 + +var config = require('../')(n, { + option: true +}) + +console.log(config) + +assert.equal(config.option, true) +assert.equal(config.envOption, 42) + +var customArgv = require('../')(n, { + option: true +}, { // nopt-like argv + option: false, + envOption: 24, + argv: { + remain: [], + cooked: ['--no-option', '--envOption', '24'], + original: ['--no-option', '--envOption=24'] + } +}) + +console.log(customArgv) + +assert.equal(customArgv.option, false) +assert.equal(customArgv.envOption, 24) + +var fs = require('fs') +var path = require('path') +var jsonrc = path.resolve('.' + n + 'rc'); + +fs.writeFileSync(jsonrc, [ + '{', + '// json overrides default', + '"option": false,', + '/* env overrides json */', + '"envOption": 24', + '}' +].join('\n')); + +var commentedJSON = require('../')(n, { + option: true +}) + +fs.unlinkSync(jsonrc); + +console.log(commentedJSON) + +assert.equal(commentedJSON.option, false) +assert.equal(commentedJSON.envOption, 42) + +assert.equal(commentedJSON.config, jsonrc) +assert.equal(commentedJSON.configs.length, 1) +assert.equal(commentedJSON.configs[0], jsonrc) diff --git a/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000..f478d58 --- /dev/null +++ b/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/readable-stream/GOVERNANCE.md b/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000..16ffb93 --- /dev/null +++ b/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..2873b3b --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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/readable-stream/README.md b/node_modules/readable-stream/README.md new file mode 100644 index 0000000..19117c1 --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/readable-stream/errors-browser.js b/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000..fb8e73e --- /dev/null +++ b/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/node_modules/readable-stream/errors.js b/node_modules/readable-stream/errors.js new file mode 100644 index 0000000..8471526 --- /dev/null +++ b/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/readable-stream/experimentalWarning.js b/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000..78e8414 --- /dev/null +++ b/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..19abfa6 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..24a6bdd --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..df1f608 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..1ccb715 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..292415e --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000..742c5a4 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000..69bda49 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000..31a17c4 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000..59c671b --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/from-browser.js b/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 0000000..a4ce56f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 0000000..0a34ee9 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000..e6f3924 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000..3fbf892 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000..9332a3f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000..ce2ad5b --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 0000000..ade59e7 --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/node_modules/readable-stream/readable-browser.js b/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000..adbf60d --- /dev/null +++ b/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..9e0ca12 --- /dev/null +++ b/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/readable-web-to-node-stream/README.md b/node_modules/readable-web-to-node-stream/README.md new file mode 100644 index 0000000..4a717d8 --- /dev/null +++ b/node_modules/readable-web-to-node-stream/README.md @@ -0,0 +1,71 @@ +![Karma CI](https://github.com/Borewit/readable-web-to-node-stream/workflows/Karma%20CI/badge.svg) +[![NPM version](https://badge.fury.io/js/readable-web-to-node-stream.svg)](https://npmjs.org/package/readable-web-to-node-stream) +[![npm downloads](http://img.shields.io/npm/dm/readable-web-to-node-stream.svg)](https://npmcharts.com/compare/readable-web-to-node-stream) +[![dependencies Status](https://david-dm.org/Borewit/readable-web-to-node-stream/status.svg)](https://david-dm.org/Borewit/readable-web-to-node-stream) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/readable-web-to-node-stream/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/readable-web-to-node-stream?targetFile=package.json) +[![Codacy Badge](https://app.codacy.com/project/badge/Grade/d4b511481b3a4634b6ca5c0724407eb9)](https://www.codacy.com/gh/Borewit/peek-readable/dashboard?utm_source=github.com&utm_medium=referral&utm_content=Borewit/peek-readable&utm_campaign=Badge_Grade) +[![Coverage Status](https://coveralls.io/repos/github/Borewit/readable-web-to-node-stream/badge.svg?branch=master)](https://coveralls.io/github/Borewit/readable-web-to-node-stream?branch=master) +[![Minified size](https://badgen.net/bundlephobia/min/readable-web-to-node-stream)](https://bundlephobia.com/result?p=readable-web-to-node-stream) + +# readable-web-to-node-stream + +Converts a [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) into a [Node.js readable stream](https://nodejs.org/api/stream.html#stream_readable_streams). + +## Installation +Install via [npm](http://npmjs.org/): + +```bash +npm install readable-web-to-node-stream +``` +or or [yarn](https://yarnpkg.com/): +```bash +yarn add readable-web-to-node-stream +``` + +## Compatibility + +Source is written in TypeScript and compiled to ECMAScript 2017 (ES8). + +Unit tests are performed on the following browsers: + +* Google Chrome 74.0 +* Firefox 68.0 +* Safari 12.0 +* Opera 60.0 + +## Example + +Import readable-web-stream-to-node in JavaScript: +```js +const {ReadableWebToNodeStream} = require('readable-web-to-node-stream'); + +async function download(url) { + const response = await fetch(url); + const readableWebStream = response.body; + const nodeStream = new ReadableWebToNodeStream(readableWebStream); +} +``` + +## API + +**constructor(stream: ReadableStream): Promise** + +`stream: ReadableStream`: the [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader). + +**close(): Promise** +Will cancel close the Readable-node stream, and will release Web-API-readable-stream. + +**waitForReadToComplete(): Promise** +If there is no unresolved read call to Web-API Readable​Stream immediately returns, otherwise it will wait until the read is resolved. + +## Licence + +(The MIT License) + +Copyright (c) 2019 Borewit + +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/readable-web-to-node-stream/lib/index.d.ts b/node_modules/readable-web-to-node-stream/lib/index.d.ts new file mode 100644 index 0000000..7d7145b --- /dev/null +++ b/node_modules/readable-web-to-node-stream/lib/index.d.ts @@ -0,0 +1,39 @@ +import { Readable } from 'readable-stream'; +/** + * Converts a Web-API stream into Node stream.Readable class + * Node stream readable: https://nodejs.org/api/stream.html#stream_readable_streams + * Web API readable-stream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + * Node readable stream: https://nodejs.org/api/stream.html#stream_readable_streams + */ +export declare class ReadableWebToNodeStream extends Readable { + bytesRead: number; + released: boolean; + /** + * Default web API stream reader + * https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader + */ + private reader; + private pendingRead; + /** + * + * @param stream Readable​Stream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + */ + constructor(stream: ReadableStream); + /** + * Implementation of readable._read(size). + * When readable._read() is called, if data is available from the resource, + * the implementation should begin pushing that data into the read queue + * https://nodejs.org/api/stream.html#stream_readable_read_size_1 + */ + _read(): Promise; + /** + * If there is no unresolved read call to Web-API Readable​Stream immediately returns; + * otherwise will wait until the read is resolved. + */ + waitForReadToComplete(): Promise; + /** + * Close wrapper + */ + close(): Promise; + private syncAndRelease; +} diff --git a/node_modules/readable-web-to-node-stream/lib/index.js b/node_modules/readable-web-to-node-stream/lib/index.js new file mode 100644 index 0000000..1efaea1 --- /dev/null +++ b/node_modules/readable-web-to-node-stream/lib/index.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadableWebToNodeStream = void 0; +const readable_stream_1 = require("readable-stream"); +/** + * Converts a Web-API stream into Node stream.Readable class + * Node stream readable: https://nodejs.org/api/stream.html#stream_readable_streams + * Web API readable-stream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + * Node readable stream: https://nodejs.org/api/stream.html#stream_readable_streams + */ +class ReadableWebToNodeStream extends readable_stream_1.Readable { + /** + * + * @param stream Readable​Stream: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream + */ + constructor(stream) { + super(); + this.bytesRead = 0; + this.released = false; + this.reader = stream.getReader(); + } + /** + * Implementation of readable._read(size). + * When readable._read() is called, if data is available from the resource, + * the implementation should begin pushing that data into the read queue + * https://nodejs.org/api/stream.html#stream_readable_read_size_1 + */ + async _read() { + // Should start pushing data into the queue + // Read data from the underlying Web-API-readable-stream + if (this.released) { + this.push(null); // Signal EOF + return; + } + this.pendingRead = this.reader.read(); + const data = await this.pendingRead; + // clear the promise before pushing pushing new data to the queue and allow sequential calls to _read() + delete this.pendingRead; + if (data.done || this.released) { + this.push(null); // Signal EOF + } + else { + this.bytesRead += data.value.length; + this.push(data.value); // Push new data to the queue + } + } + /** + * If there is no unresolved read call to Web-API Readable​Stream immediately returns; + * otherwise will wait until the read is resolved. + */ + async waitForReadToComplete() { + if (this.pendingRead) { + await this.pendingRead; + } + } + /** + * Close wrapper + */ + async close() { + await this.syncAndRelease(); + } + async syncAndRelease() { + this.released = true; + await this.waitForReadToComplete(); + await this.reader.releaseLock(); + } +} +exports.ReadableWebToNodeStream = ReadableWebToNodeStream; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/readable-web-to-node-stream/lib/index.spec.js b/node_modules/readable-web-to-node-stream/lib/index.spec.js new file mode 100644 index 0000000..98ddd4e --- /dev/null +++ b/node_modules/readable-web-to-node-stream/lib/index.spec.js @@ -0,0 +1,147 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseReadableStream = void 0; +localStorage.debug = 'readable-web-to-node-stream'; +const assert = require("assert"); +const mmb = require("music-metadata-browser"); +const index_1 = require("./index"); +async function httpGetByUrl(url) { + const response = await fetch(url); + const headers = []; + response.headers.forEach(header => { + headers.push(header); + }); + assert.ok(response.ok, `HTTP error status=${response.status}: ${response.statusText}`); + assert.ok(response.body, 'HTTP-stream'); + return response; +} +async function parseReadableStream(stream, fileInfo, options) { + const ns = new index_1.ReadableWebToNodeStream(stream); + const res = await mmb.parseNodeStream(ns, fileInfo, options); + await ns.close(); + return res; +} +exports.parseReadableStream = parseReadableStream; +const tiuqottigeloot_vol24_Tracks = [ + { + url: '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/01%20-%20Diablo%20Swing%20Orchestra%20-%20Heroines.mp3', + duration: 322.612245, + metaData: { + title: 'Heroines', + artist: 'Diablo Swing Orchestra' + } + }, + { + url: '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/02%20-%20Eclectek%20-%20We%20Are%20Going%20To%20Eclecfunk%20Your%20Ass.mp3', + duration: 190.093061, + metaData: { + title: 'We Are Going to Eclecfunk Your Ass', + artist: 'Eclectek' + } + } /* , + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/03%20-%20Auto-Pilot%20-%20Seventeen.mp3', + duration: 214.622041, + metaData: { + title: 'Seventeen', + artist: 'Auto-Pilot' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/04%20-%20Muha%20-%20Microphone.mp3', + duration: 181.838367, + metaData: { + title: 'Microphone', + artist: 'Muha' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/05%20-%20Just%20Plain%20Ant%20-%20Stumble.mp3', + duration: 86.047347, + metaData: { + title: 'Stumble', + artist: 'Just Plain Ant' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/06%20-%20Sleaze%20-%20God%20Damn.mp3', + duration: 226.795102, + metaData: { + title: 'God Damn', + artist: 'Sleaze' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/07%20-%20Juanitos%20-%20Hola%20Hola%20Bossa%20Nova.mp3', + duration: 207.072653, + metaData: { + title: 'Hola Hola Bossa Nova', + artist: 'Juanitos' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/08%20-%20Entertainment%20For%20The%20Braindead%20-%20Resolutions%20(Chris%20Summer%20Remix).mp3', + duration: 314.331429, + metaData: { + title: 'Resolutions (Chris Summer remix)', + artist: 'Entertainment for the Braindead' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/09%20-%20Nobara%20Hayakawa%20-%20Trail.mp3', + duration: 204.042449, + metaData: { + title: 'Trail', + artist: 'Nobara Hayakawa' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/10%20-%20Paper%20Navy%20-%20Tongue%20Tied.mp3', + duration: 201.116735, + metaData: { + title: 'Tongue Tied', + artist: 'Paper Navy' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/11%20-%2060%20Tigres%20-%20Garage.mp3', + duration: 245.394286, + metaData: { + title: 'Garage', + artist: '60 Tigres' + } + }, + { + url: + '/Various%20Artists%20-%202009%20-%20netBloc%20Vol%2024_%20tiuqottigeloot%20%5BMP3-V2%5D/12%20-%20CM%20aka%20Creative%20-%20The%20Cycle%20(Featuring%20Mista%20Mista).mp3', + duration: 221.44, + metaData: { + title: 'The Cycle (feat. Mista Mista)', + artist: 'CM aka Creative' + } + } */ +]; +describe('Parse WebAmp tracks', () => { + tiuqottigeloot_vol24_Tracks.forEach(track => { + it(`track ${track.metaData.artist} - ${track.metaData.title}`, async () => { + const url = 'https://raw.githubusercontent.com/Borewit/test-audio/958e057' + track.url; + const response = await httpGetByUrl(url); + const metadata = await parseReadableStream(response.body, { + size: parseInt(response.headers.get('Content-Length'), 10), + mimeType: response.headers.get('Content-Type') + }); + expect(metadata.common.artist).toEqual(track.metaData.artist); + expect(metadata.common.title).toEqual(track.metaData.title); + }, 20000); + }); +}); +//# sourceMappingURL=index.spec.js.map \ No newline at end of file diff --git a/node_modules/readable-web-to-node-stream/package.json b/node_modules/readable-web-to-node-stream/package.json new file mode 100644 index 0000000..057c39f --- /dev/null +++ b/node_modules/readable-web-to-node-stream/package.json @@ -0,0 +1,84 @@ +{ + "name": "readable-web-to-node-stream", + "version": "3.0.2", + "description": "Converts a Web-API readable-stream into a Node readable-stream.", + "main": "lib/index.js", + "files": [ + "lib/**/*.js", + "lib/**/*.d.ts" + ], + "engines": { + "node": ">=8" + }, + "types": "lib/index.d.ts", + "scripts": { + "clean": "del-cli lib/**/*.js lib/**/*.js.map lib/**/*.d.ts coverage", + "compile-lib": "tsc -p lib/tsconfig.json", + "compile-test": "tsc -p lib/tsconfig.spec.json", + "prepublishOnly": "yarn run build", + "build": "npm run compile-lib && npm run compile-test", + "tslint": "tslint 'lib/**/*.ts' --exclude 'lib/**/*.d.ts'", + "eslint": "eslint karma.conf.js", + "lint": "npm run tslint && npm run eslint", + "test": "karma start --single-run", + "karma": "karma start", + "karma-firefox": "karma start --browsers Firefox", + "karma-once": "karma start --browsers Chrome --single-run", + "travis-karma": "karma start --browsers Firefox --single-run --reporters coverage-istanbul,spec", + "browserstack": "karma start --browsers bs_win_chrome,bs_win_firefox,bs_osx_safari --single-run --reporters coverage-istanbul,spec", + "travis-karma-browserstack": "karma start --browsers bs_win_chrome,bs_win_firefox,bs_osx_safari --single-run --reporters coverage-istanbul,spec,BrowserStack", + "post-coveralls": "coveralls < coverage/lcov.info", + "post-codacy": " codacy-coverage < coverage/lcov.info" + }, + "keywords": [ + "stream.readable", + "web", + "node", + "browser", + "stream", + "covert", + "coverter", + "readable", + "readablestream" + ], + "repository": "https://github.com/Borewit/readable-web-to-node-stream.git", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/Borewit/readable-web-to-node-stream/issues" + }, + "dependencies": { + "readable-stream": "^3.6.0" + }, + "devDependencies": { + "@types/jasmine": "^3.8.1", + "@types/node": "^16.3.1", + "@types/readable-stream": "^2.3.9", + "coveralls": "^3.1.0", + "del-cli": "^3.0.1", + "eslint": "^7.18.0", + "istanbul-instrumenter-loader": "^3.0.1", + "jasmine-core": "^3.8.0", + "karma": "^6.3.4", + "karma-browserstack-launcher": "^1.6.0", + "karma-chrome-launcher": "^3.1.0", + "karma-coverage-istanbul-reporter": "^3.0.3", + "karma-firefox-launcher": "^2.1.0", + "karma-jasmine": "^4.0.1", + "karma-jasmine-html-reporter": "^1.7.0", + "karma-spec-reporter": "^0.0.32", + "karma-webpack": "^5.0.0", + "music-metadata-browser": "^2.2.7", + "ts-loader": "^8.0.14", + "tslint": "^6.1.3", + "typescript": "^4.3.5", + "webpack": "^4.46.0" + } +} diff --git a/node_modules/readdirp/LICENSE b/node_modules/readdirp/LICENSE new file mode 100644 index 0000000..037cbb4 --- /dev/null +++ b/node_modules/readdirp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) + +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/readdirp/README.md b/node_modules/readdirp/README.md new file mode 100644 index 0000000..465593c --- /dev/null +++ b/node_modules/readdirp/README.md @@ -0,0 +1,122 @@ +# readdirp [![Weekly downloads](https://img.shields.io/npm/dw/readdirp.svg)](https://github.com/paulmillr/readdirp) + +Recursive version of [fs.readdir](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback). Exposes a **stream API** and a **promise API**. + + +```sh +npm install readdirp +``` + +```javascript +const readdirp = require('readdirp'); + +// Use streams to achieve small RAM & CPU footprint. +// 1) Streams example with for-await. +for await (const entry of readdirp('.')) { + const {path} = entry; + console.log(`${JSON.stringify({path})}`); +} + +// 2) Streams example, non for-await. +// Print out all JS files along with their size within the current folder & subfolders. +readdirp('.', {fileFilter: '*.js', alwaysStat: true}) + .on('data', (entry) => { + const {path, stats: {size}} = entry; + console.log(`${JSON.stringify({path, size})}`); + }) + // Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted + .on('warn', error => console.error('non-fatal error', error)) + .on('error', error => console.error('fatal error', error)) + .on('end', () => console.log('done')); + +// 3) Promise example. More RAM and CPU than streams / for-await. +const files = await readdirp.promise('.'); +console.log(files.map(file => file.path)); + +// Other options. +readdirp('test', { + fileFilter: '*.js', + directoryFilter: ['!.git', '!*modules'] + // directoryFilter: (di) => di.basename.length === 9 + type: 'files_directories', + depth: 1 +}); +``` + +For more examples, check out `examples` directory. + +## API + +`const stream = readdirp(root[, options])` — **Stream API** + +- Reads given root recursively and returns a `stream` of [entry infos](#entryinfo) +- Optionally can be used like `for await (const entry of stream)` with node.js 10+ (`asyncIterator`). +- `on('data', (entry) => {})` [entry info](#entryinfo) for every file / dir. +- `on('warn', (error) => {})` non-fatal `Error` that prevents a file / dir from being processed. Example: inaccessible to the user. +- `on('error', (error) => {})` fatal `Error` which also ends the stream. Example: illegal options where passed. +- `on('end')` — we are done. Called when all entries were found and no more will be emitted. +- `on('close')` — stream is destroyed via `stream.destroy()`. + Could be useful if you want to manually abort even on a non fatal error. + At that point the stream is no longer `readable` and no more entries, warning or errors are emitted +- To learn more about streams, consult the very detailed [nodejs streams documentation](https://nodejs.org/api/stream.html) + or the [stream-handbook](https://github.com/substack/stream-handbook) + +`const entries = await readdirp.promise(root[, options])` — **Promise API**. Returns a list of [entry infos](#entryinfo). + +First argument is awalys `root`, path in which to start reading and recursing into subdirectories. + +### options + +- `fileFilter: ["*.js"]`: filter to include or exclude files. A `Function`, Glob string or Array of glob strings. + - **Function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry + - **Glob string**: a string (e.g., `*.js`) which is matched using [picomatch](https://github.com/micromatch/picomatch), so go there for more + information. Globstars (`**`) are not supported since specifying a recursive pattern for an already recursive function doesn't make sense. Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files. + - **Array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown. + `['*.json', '*.js']` includes all JavaScript and Json files. + `['!.git', '!node_modules']` includes all directories except the '.git' and 'node_modules'. + - Directories that do not pass a filter will not be recursed into. +- `directoryFilter: ['!.git']`: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into. +- `depth: 5`: depth at which to stop recursing even if more subdirectories are found +- `type: 'files'`: determines if data events on the stream should be emitted for `'files'` (default), `'directories'`, `'files_directories'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes. +- `alwaysStat: false`: always return `stats` property for every file. Default is `false`, readdirp will return `Dirent` entries. Setting it to `true` can double readdir execution time - use it only when you need file `size`, `mtime` etc. Cannot be enabled on node <10.10.0. +- `lstat: false`: include symlink entries in the stream along with files. When `true`, `fs.lstat` would be used instead of `fs.stat` + +### `EntryInfo` + +Has the following properties: + +- `path: 'assets/javascripts/react.js'`: path to the file/directory (relative to given root) +- `fullPath: '/Users/dev/projects/app/assets/javascripts/react.js'`: full path to the file/directory found +- `basename: 'react.js'`: name of the file/directory +- `dirent: fs.Dirent`: built-in [dir entry object](https://nodejs.org/api/fs.html#fs_class_fs_dirent) - only with `alwaysStat: false` +- `stats: fs.Stats`: built in [stat object](https://nodejs.org/api/fs.html#fs_class_fs_stats) - only with `alwaysStat: true` + +## Changelog + +- 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks. + Before, it could have entered infinite loop. +- 3.4 (Mar 19, 2020) adds support for directory-based symlinks. +- 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with `highWaterMark` option. Fixes race conditions related to `for-await` looping. +- 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic. +- 3.1 (Jul 7, 2019) brings `bigint` support to `stat` output on Windows. This is backwards-incompatible for some cases. Be careful. It you use it incorrectly, you'll see "TypeError: Cannot mix BigInt and other types, use explicit conversions". +- 3.0 brings huge performance improvements and stream backpressure support. +- Upgrading 2.x to 3.x: + - Signature changed from `readdirp(options)` to `readdirp(root, options)` + - Replaced callback API with promise API. + - Renamed `entryType` option to `type` + - Renamed `entryType: 'both'` to `'files_directories'` + - `EntryInfo` + - Renamed `stat` to `stats` + - Emitted only when `alwaysStat: true` + - `dirent` is emitted instead of `stats` by default with `alwaysStat: false` + - Renamed `name` to `basename` + - Removed `parentDir` and `fullParentDir` properties +- Supported node.js versions: + - 3.x: node 8+ + - 2.x: node 0.6+ + +## License + +Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller () + +MIT License, see [LICENSE](LICENSE) file. diff --git a/node_modules/readdirp/index.d.ts b/node_modules/readdirp/index.d.ts new file mode 100644 index 0000000..cbbd76c --- /dev/null +++ b/node_modules/readdirp/index.d.ts @@ -0,0 +1,43 @@ +// TypeScript Version: 3.2 + +/// + +import * as fs from 'fs'; +import { Readable } from 'stream'; + +declare namespace readdir { + interface EntryInfo { + path: string; + fullPath: string; + basename: string; + stats?: fs.Stats; + dirent?: fs.Dirent; + } + + interface ReaddirpOptions { + root?: string; + fileFilter?: string | string[] | ((entry: EntryInfo) => boolean); + directoryFilter?: string | string[] | ((entry: EntryInfo) => boolean); + type?: 'files' | 'directories' | 'files_directories' | 'all'; + lstat?: boolean; + depth?: number; + alwaysStat?: boolean; + } + + interface ReaddirpStream extends Readable, AsyncIterable { + read(): EntryInfo; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + function promise( + root: string, + options?: ReaddirpOptions + ): Promise; +} + +declare function readdir( + root: string, + options?: readdir.ReaddirpOptions +): readdir.ReaddirpStream; + +export = readdir; diff --git a/node_modules/readdirp/index.js b/node_modules/readdirp/index.js new file mode 100644 index 0000000..cf739b2 --- /dev/null +++ b/node_modules/readdirp/index.js @@ -0,0 +1,287 @@ +'use strict'; + +const fs = require('fs'); +const { Readable } = require('stream'); +const sysPath = require('path'); +const { promisify } = require('util'); +const picomatch = require('picomatch'); + +const readdir = promisify(fs.readdir); +const stat = promisify(fs.stat); +const lstat = promisify(fs.lstat); +const realpath = promisify(fs.realpath); + +/** + * @typedef {Object} EntryInfo + * @property {String} path + * @property {String} fullPath + * @property {fs.Stats=} stats + * @property {fs.Dirent=} dirent + * @property {String} basename + */ + +const BANG = '!'; +const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR'; +const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]); +const FILE_TYPE = 'files'; +const DIR_TYPE = 'directories'; +const FILE_DIR_TYPE = 'files_directories'; +const EVERYTHING_TYPE = 'all'; +const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; + +const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code); +const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10)); +const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5)); + +const normalizeFilter = filter => { + if (filter === undefined) return; + if (typeof filter === 'function') return filter; + + if (typeof filter === 'string') { + const glob = picomatch(filter.trim()); + return entry => glob(entry.basename); + } + + if (Array.isArray(filter)) { + const positive = []; + const negative = []; + for (const item of filter) { + const trimmed = item.trim(); + if (trimmed.charAt(0) === BANG) { + negative.push(picomatch(trimmed.slice(1))); + } else { + positive.push(picomatch(trimmed)); + } + } + + if (negative.length > 0) { + if (positive.length > 0) { + return entry => + positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename)); + } + return entry => !negative.some(f => f(entry.basename)); + } + return entry => positive.some(f => f(entry.basename)); + } +}; + +class ReaddirpStream extends Readable { + static get defaultOptions() { + return { + root: '.', + /* eslint-disable no-unused-vars */ + fileFilter: (path) => true, + directoryFilter: (path) => true, + /* eslint-enable no-unused-vars */ + type: FILE_TYPE, + lstat: false, + depth: 2147483648, + alwaysStat: false + }; + } + + constructor(options = {}) { + super({ + objectMode: true, + autoDestroy: true, + highWaterMark: options.highWaterMark || 4096 + }); + const opts = { ...ReaddirpStream.defaultOptions, ...options }; + const { root, type } = opts; + + this._fileFilter = normalizeFilter(opts.fileFilter); + this._directoryFilter = normalizeFilter(opts.directoryFilter); + + const statMethod = opts.lstat ? lstat : stat; + // Use bigint stats if it's windows and stat() supports options (node 10+). + if (wantBigintFsStats) { + this._stat = path => statMethod(path, { bigint: true }); + } else { + this._stat = statMethod; + } + + this._maxDepth = opts.depth; + this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type); + this._wantsEverything = type === EVERYTHING_TYPE; + this._root = sysPath.resolve(root); + this._isDirent = ('Dirent' in fs) && !opts.alwaysStat; + this._statsProp = this._isDirent ? 'dirent' : 'stats'; + this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent }; + + // Launch stream with one parent, the root dir. + this.parents = [this._exploreDir(root, 1)]; + this.reading = false; + this.parent = undefined; + } + + async _read(batch) { + if (this.reading) return; + this.reading = true; + + try { + while (!this.destroyed && batch > 0) { + const { path, depth, files = [] } = this.parent || {}; + + if (files.length > 0) { + const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path)); + for (const entry of await Promise.all(slice)) { + if (this.destroyed) return; + + const entryType = await this._getEntryType(entry); + if (entryType === 'directory' && this._directoryFilter(entry)) { + if (depth <= this._maxDepth) { + this.parents.push(this._exploreDir(entry.fullPath, depth + 1)); + } + + if (this._wantsDir) { + this.push(entry); + batch--; + } + } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) { + if (this._wantsFile) { + this.push(entry); + batch--; + } + } + } + } else { + const parent = this.parents.pop(); + if (!parent) { + this.push(null); + break; + } + this.parent = await parent; + if (this.destroyed) return; + } + } + } catch (error) { + this.destroy(error); + } finally { + this.reading = false; + } + } + + async _exploreDir(path, depth) { + let files; + try { + files = await readdir(path, this._rdOptions); + } catch (error) { + this._onError(error); + } + return { files, depth, path }; + } + + async _formatEntry(dirent, path) { + let entry; + try { + const basename = this._isDirent ? dirent.name : dirent; + const fullPath = sysPath.resolve(sysPath.join(path, basename)); + entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename }; + entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); + } catch (err) { + this._onError(err); + } + return entry; + } + + _onError(err) { + if (isNormalFlowError(err) && !this.destroyed) { + this.emit('warn', err); + } else { + this.destroy(err); + } + } + + async _getEntryType(entry) { + // entry may be undefined, because a warning or an error were emitted + // and the statsProp is undefined + const stats = entry && entry[this._statsProp]; + if (!stats) { + return; + } + if (stats.isFile()) { + return 'file'; + } + if (stats.isDirectory()) { + return 'directory'; + } + if (stats && stats.isSymbolicLink()) { + const full = entry.fullPath; + try { + const entryRealPath = await realpath(full); + const entryRealPathStats = await lstat(entryRealPath); + if (entryRealPathStats.isFile()) { + return 'file'; + } + if (entryRealPathStats.isDirectory()) { + const len = entryRealPath.length; + if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) { + const recursiveError = new Error( + `Circular symlink detected: "${full}" points to "${entryRealPath}"` + ); + recursiveError.code = RECURSIVE_ERROR_CODE; + return this._onError(recursiveError); + } + return 'directory'; + } + } catch (error) { + this._onError(error); + } + } + } + + _includeAsFile(entry) { + const stats = entry && entry[this._statsProp]; + + return stats && this._wantsEverything && !stats.isDirectory(); + } +} + +/** + * @typedef {Object} ReaddirpArguments + * @property {Function=} fileFilter + * @property {Function=} directoryFilter + * @property {String=} type + * @property {Number=} depth + * @property {String=} root + * @property {Boolean=} lstat + * @property {Boolean=} bigint + */ + +/** + * Main function which ends up calling readdirRec and reads all files and directories in given root recursively. + * @param {String} root Root directory + * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth + */ +const readdirp = (root, options = {}) => { + let type = options.entryType || options.type; + if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility + if (type) options.type = type; + if (!root) { + throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)'); + } else if (typeof root !== 'string') { + throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)'); + } else if (type && !ALL_TYPES.includes(type)) { + throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`); + } + + options.root = root; + return new ReaddirpStream(options); +}; + +const readdirpPromise = (root, options = {}) => { + return new Promise((resolve, reject) => { + const files = []; + readdirp(root, options) + .on('data', entry => files.push(entry)) + .on('end', () => resolve(files)) + .on('error', error => reject(error)); + }); +}; + +readdirp.promise = readdirpPromise; +readdirp.ReaddirpStream = ReaddirpStream; +readdirp.default = readdirp; + +module.exports = readdirp; diff --git a/node_modules/readdirp/package.json b/node_modules/readdirp/package.json new file mode 100644 index 0000000..54c210b --- /dev/null +++ b/node_modules/readdirp/package.json @@ -0,0 +1,161 @@ +{ + "_args": [ + [ + "readdirp@3.6.0", + "/home/other/discord_bot" + ] + ], + "_from": "readdirp@3.6.0", + "_id": "readdirp@3.6.0", + "_inBundle": false, + "_integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "_location": "/readdirp", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "readdirp@3.6.0", + "name": "readdirp", + "escapedName": "readdirp", + "rawSpec": "3.6.0", + "saveSpec": null, + "fetchSpec": "3.6.0" + }, + "_requiredBy": [ + "/chokidar" + ], + "_resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "_spec": "3.6.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Thorsten Lorenz", + "email": "thlorenz@gmx.de", + "url": "thlorenz.com" + }, + "bugs": { + "url": "https://github.com/paulmillr/readdirp/issues" + }, + "contributors": [ + { + "name": "Thorsten Lorenz", + "email": "thlorenz@gmx.de", + "url": "thlorenz.com" + }, + { + "name": "Paul Miller", + "url": "https://paulmillr.com" + } + ], + "dependencies": { + "picomatch": "^2.2.1" + }, + "description": "Recursive version of fs.readdir with streaming API.", + "devDependencies": { + "@types/node": "^14", + "chai": "^4.2", + "chai-subset": "^1.6", + "dtslint": "^3.3.0", + "eslint": "^7.0.0", + "mocha": "^7.1.1", + "nyc": "^15.0.0", + "rimraf": "^3.0.0", + "typescript": "^4.0.3" + }, + "engines": { + "node": ">=8.10.0" + }, + "eslintConfig": { + "root": true, + "extends": "eslint:recommended", + "parserOptions": { + "ecmaVersion": 9, + "sourceType": "script" + }, + "env": { + "node": true, + "es6": true + }, + "rules": { + "array-callback-return": "error", + "no-empty": [ + "error", + { + "allowEmptyCatch": true + } + ], + "no-else-return": [ + "error", + { + "allowElseIf": false + } + ], + "no-lonely-if": "error", + "no-var": "error", + "object-shorthand": "error", + "prefer-arrow-callback": [ + "error", + { + "allowNamedFunctions": true + } + ], + "prefer-const": [ + "error", + { + "ignoreReadBeforeAssign": true + } + ], + "prefer-destructuring": [ + "error", + { + "object": true, + "array": false + } + ], + "prefer-spread": "error", + "prefer-template": "error", + "radix": "error", + "semi": "error", + "strict": "error", + "quotes": [ + "error", + "single" + ] + } + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/paulmillr/readdirp", + "keywords": [ + "recursive", + "fs", + "stream", + "streams", + "readdir", + "filesystem", + "find", + "filter" + ], + "license": "MIT", + "main": "index.js", + "name": "readdirp", + "nyc": { + "reporter": [ + "html", + "text" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/paulmillr/readdirp.git" + }, + "scripts": { + "dtslint": "dtslint", + "lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .", + "mocha": "mocha --exit", + "nyc": "nyc", + "test": "npm run lint && nyc npm run mocha" + }, + "version": "3.6.0" +} diff --git a/node_modules/regenerator-runtime/LICENSE b/node_modules/regenerator-runtime/LICENSE new file mode 100644 index 0000000..cde61b6 --- /dev/null +++ b/node_modules/regenerator-runtime/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2014-present, Facebook, Inc. + +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/regenerator-runtime/README.md b/node_modules/regenerator-runtime/README.md new file mode 100644 index 0000000..e8702ba --- /dev/null +++ b/node_modules/regenerator-runtime/README.md @@ -0,0 +1,31 @@ +# regenerator-runtime + +Standalone runtime for +[Regenerator](https://github.com/facebook/regenerator)-compiled generator +and `async` functions. + +To import the runtime as a module (recommended), either of the following +import styles will work: +```js +// CommonJS +const regeneratorRuntime = require("regenerator-runtime"); + +// ECMAScript 2015 +import regeneratorRuntime from "regenerator-runtime"; +``` + +To ensure that `regeneratorRuntime` is defined globally, either of the +following styles will work: +```js +// CommonJS +require("regenerator-runtime/runtime"); + +// ECMAScript 2015 +import "regenerator-runtime/runtime.js"; +``` + +To get the absolute file system path of `runtime.js`, evaluate the +following expression: +```js +require("regenerator-runtime/path").path +``` diff --git a/node_modules/regenerator-runtime/package.json b/node_modules/regenerator-runtime/package.json new file mode 100644 index 0000000..3fe1740 --- /dev/null +++ b/node_modules/regenerator-runtime/package.json @@ -0,0 +1,50 @@ +{ + "_args": [ + [ + "regenerator-runtime@0.13.9", + "/home/other/discord_bot" + ] + ], + "_from": "regenerator-runtime@0.13.9", + "_id": "regenerator-runtime@0.13.9", + "_inBundle": false, + "_integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==", + "_location": "/regenerator-runtime", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "regenerator-runtime@0.13.9", + "name": "regenerator-runtime", + "escapedName": "regenerator-runtime", + "rawSpec": "0.13.9", + "saveSpec": null, + "fetchSpec": "0.13.9" + }, + "_requiredBy": [ + "/@babel/runtime" + ], + "_resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "_spec": "0.13.9", + "_where": "/home/other/discord_bot", + "author": { + "name": "Ben Newman", + "email": "bn@cs.stanford.edu" + }, + "description": "Runtime for Regenerator-compiled generator and async functions.", + "keywords": [ + "regenerator", + "runtime", + "generator", + "async" + ], + "license": "MIT", + "main": "runtime.js", + "name": "regenerator-runtime", + "repository": { + "type": "git", + "url": "https://github.com/facebook/regenerator/tree/master/packages/runtime" + }, + "sideEffects": true, + "version": "0.13.9" +} diff --git a/node_modules/regenerator-runtime/path.js b/node_modules/regenerator-runtime/path.js new file mode 100644 index 0000000..ced878b --- /dev/null +++ b/node_modules/regenerator-runtime/path.js @@ -0,0 +1,11 @@ +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +exports.path = require("path").join( + __dirname, + "runtime.js" +); diff --git a/node_modules/regenerator-runtime/runtime.js b/node_modules/regenerator-runtime/runtime.js new file mode 100644 index 0000000..a64424e --- /dev/null +++ b/node_modules/regenerator-runtime/runtime.js @@ -0,0 +1,754 @@ +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +var runtime = (function (exports) { + "use strict"; + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + try { + // IE 8 has a broken Object.defineProperty that only works on DOM objects. + define({}, ""); + } catch (err) { + define = function(obj, key, value) { + return obj[key] = value; + }; + } + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + exports.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + define(IteratorPrototype, iteratorSymbol, function () { + return this; + }); + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = GeneratorFunctionPrototype; + define(Gp, "constructor", GeneratorFunctionPrototype); + define(GeneratorFunctionPrototype, "constructor", GeneratorFunction); + GeneratorFunction.displayName = define( + GeneratorFunctionPrototype, + toStringTagSymbol, + "GeneratorFunction" + ); + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + define(prototype, method, function(arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + define(AsyncIterator.prototype, asyncIteratorSymbol, function () { + return this; + }); + exports.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl + ); + + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + // Note: ["return"] must be used for ES3 parsing compatibility. + if (delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + define(Gp, toStringTagSymbol, "Generator"); + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + define(Gp, iteratorSymbol, function() { + return this; + }); + + define(Gp, "toString", function() { + return "[object Generator]"; + }); + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + exports.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; + } + }; + + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + +}( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + typeof module === "object" ? module.exports : {} +)); + +try { + regeneratorRuntime = runtime; +} catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, in modern engines + // we can explicitly access globalThis. In older engines we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + if (typeof globalThis === "object") { + globalThis.regeneratorRuntime = runtime; + } else { + Function("r", "regeneratorRuntime = r")(runtime); + } +} diff --git a/node_modules/registry-auth-token/CHANGELOG.md b/node_modules/registry-auth-token/CHANGELOG.md new file mode 100644 index 0000000..e96f146 --- /dev/null +++ b/node_modules/registry-auth-token/CHANGELOG.md @@ -0,0 +1,134 @@ +# Change Log + +All notable changes will be documented in this file. + +## [4.2.0] - 2020-07-13 + +### Changes + +- Add support for `NPM_CONFIG_USERCONFIG` environment variable (Ben Sorohan) + +## [4.1.0] - 2020-01-17 + +### Changes + +- Add support for legacy auth token on the registry url (Gustav Blomér) + +## [4.0.0] - 2019-06-17 + +### BREAKING + +- Minimum node.js version requirement is now v6 + +### Changes + +- Upgraded dependencies (Espen Hovlandsdal) + +## [3.4.0] - 2019-03-20 + +### Changes + +- Enabled legacy auth token to be read from environment variable (Martin Flodin) + +## [3.3.2] - 2018-01-26 + +### Changes + +- Support password with ENV variable tokens (Nowell Strite) + +## [3.3.1] - 2017-05-02 + +### Fixes + +- Auth legacy token is basic auth (Hutson Betts) + +## [3.3.0] - 2017-04-24 + +### Changes + +- Support legacy auth token config key (Zoltan Kochan) +- Use safe-buffer module for backwards-compatible base64 encoding/decoding (Espen Hovlandsdal) +- Change to standard.js coding style (Espen Hovlandsdal) + +## [3.2.0] - 2017-04-20 + +### Changes + +- Allow passing parsed npmrc from outside (Zoltan Kochan) + +## [3.1.2] - 2017-04-07 + +### Changes + +- Avoid infinite loop on invalid URL (Zoltan Kochan) + +## [3.1.1] - 2017-04-06 + +### Changes + +- Nerf-dart URLs even if recursive is set to false (Espen Hovlandsdal) + +## [3.1.0] - 2016-10-19 + +### Changes + +- Return the password and username for Basic authorization (Zoltan Kochan) + +## [3.0.1] - 2016-08-07 + +### Changes + +- Fix recursion bug (Lukas Eipert) +- Implement alternative base64 encoding/decoding implementation for Node 6 (Lukas Eipert) + +## [3.0.0] - 2016-08-04 + +### Added + +- Support for Basic Authentication (username/password) (Lukas Eipert) + +### Changes + +- The result format of the output changed from a simple string to an object which contains the token type + +```js + // before: returns 'tokenString' + // after: returns {token: 'tokenString', type: 'Bearer'} + getAuthToken() +``` + +## [2.1.1] - 2016-07-10 + +### Changes + +- Fix infinite loop when recursively resolving registry URLs on Windows (Espen Hovlandsdal) + +## [2.1.0] - 2016-07-07 + +### Added + +- Add feature to find configured registry URL for a scope (Espen Hovlandsdal) + +## [2.0.0] - 2016-06-17 + +### Changes + +- Fix tokens defined by reference to environment variables (Dan MacTough) + +## [1.1.1] - 2016-04-26 + +### Changes + +- Fix for registries with port number in URL (Ryan Day) + +[1.1.1]: https://github.com/rexxars/registry-auth-token/compare/a5b4fe2f5ff982110eb8a813ba1b3b3c5d851af1...v1.1.1 +[2.0.0]: https://github.com/rexxars/registry-auth-token/compare/v1.1.1...v2.0.0 +[2.1.0]: https://github.com/rexxars/registry-auth-token/compare/v2.0.0...v2.1.0 +[2.1.1]: https://github.com/rexxars/registry-auth-token/compare/v2.1.0...v2.1.1 +[3.0.0]: https://github.com/rexxars/registry-auth-token/compare/v2.1.1...v3.0.0 +[3.0.1]: https://github.com/rexxars/registry-auth-token/compare/v3.0.0...v3.0.1 +[3.1.0]: https://github.com/rexxars/registry-auth-token/compare/v3.0.1...v3.1.0 +[3.1.1]: https://github.com/rexxars/registry-auth-token/compare/v3.1.0...v3.1.1 +[3.1.2]: https://github.com/rexxars/registry-auth-token/compare/v3.1.1...v3.1.2 +[3.2.0]: https://github.com/rexxars/registry-auth-token/compare/v3.1.2...v3.2.0 +[3.3.0]: https://github.com/rexxars/registry-auth-token/compare/v3.2.0...v3.3.0 diff --git a/node_modules/registry-auth-token/LICENSE b/node_modules/registry-auth-token/LICENSE new file mode 100644 index 0000000..0de12e3 --- /dev/null +++ b/node_modules/registry-auth-token/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Espen Hovlandsdal + +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/registry-auth-token/README.md b/node_modules/registry-auth-token/README.md new file mode 100644 index 0000000..084dc0a --- /dev/null +++ b/node_modules/registry-auth-token/README.md @@ -0,0 +1,65 @@ +# registry-auth-token + +[![npm version](http://img.shields.io/npm/v/registry-auth-token.svg?style=flat-square)](http://browsenpm.org/package/registry-auth-token)[![Build Status](http://img.shields.io/travis/rexxars/registry-auth-token/main.svg?style=flat-square)](https://travis-ci.org/rexxars/registry-auth-token) + +Get the auth token set for an npm registry from `.npmrc`. Also allows fetching the configured registry URL for a given npm scope. + +## Installing + +``` +npm install --save registry-auth-token +``` + +## Usage + +Returns an object containing `token` and `type`, or `undefined` if no token can be found. `type` can be either `Bearer` or `Basic`. + +```js +var getAuthToken = require('registry-auth-token') +var getRegistryUrl = require('registry-auth-token/registry-url') + +// Get auth token and type for default `registry` set in `.npmrc` +console.log(getAuthToken()) // {token: 'someToken', type: 'Bearer'} + +// Get auth token for a specific registry URL +console.log(getAuthToken('//registry.foo.bar')) + +// Find the registry auth token for a given URL (with deep path): +// If registry is at `//some.host/registry` +// URL passed is `//some.host/registry/deep/path` +// Will find token the closest matching path; `//some.host/registry` +console.log(getAuthToken('//some.host/registry/deep/path', {recursive: true})) + +// Find the configured registry url for scope `@foobar`. +// Falls back to the global registry if not defined. +console.log(getRegistryUrl('@foobar')) + +// Use the npm config that is passed in +console.log(getRegistryUrl('http://registry.foobar.eu/', { + npmrc: { + 'registry': 'http://registry.foobar.eu/', + '//registry.foobar.eu/:_authToken': 'qar' + } +})) +``` + +## Return value + +```js +// If auth info can be found: +{token: 'someToken', type: 'Bearer'} + +// Or: +{token: 'someOtherToken', type: 'Basic'} + +// Or, if nothing is found: +undefined +``` + +## Security + +Please be careful when using this. Leaking your auth token is dangerous. + +## License + +MIT-licensed. See LICENSE. diff --git a/node_modules/registry-auth-token/base64.js b/node_modules/registry-auth-token/base64.js new file mode 100644 index 0000000..ff0f6cb --- /dev/null +++ b/node_modules/registry-auth-token/base64.js @@ -0,0 +1,12 @@ +function decodeBase64 (base64) { + return Buffer.from(base64, 'base64').toString('utf8') +} + +function encodeBase64 (string) { + return Buffer.from(string, 'utf8').toString('base64') +} + +module.exports = { + decodeBase64: decodeBase64, + encodeBase64: encodeBase64 +} diff --git a/node_modules/registry-auth-token/index.js b/node_modules/registry-auth-token/index.js new file mode 100644 index 0000000..28eedfd --- /dev/null +++ b/node_modules/registry-auth-token/index.js @@ -0,0 +1,142 @@ +var url = require('url') +var base64 = require('./base64') + +var decodeBase64 = base64.decodeBase64 +var encodeBase64 = base64.encodeBase64 + +var tokenKey = ':_authToken' +var legacyTokenKey = ':_auth' +var userKey = ':username' +var passwordKey = ':_password' + +module.exports = function () { + var checkUrl + var options + if (arguments.length >= 2) { + checkUrl = arguments[0] + options = arguments[1] + } else if (typeof arguments[0] === 'string') { + checkUrl = arguments[0] + } else { + options = arguments[0] + } + options = options || {} + options.npmrc = options.npmrc || require('rc')('npm', { registry: 'https://registry.npmjs.org/' }, { + config: process.env.npm_config_userconfig || process.env.NPM_CONFIG_USERCONFIG + }) + checkUrl = checkUrl || options.npmrc.registry + return getRegistryAuthInfo(checkUrl, options) || getLegacyAuthInfo(options.npmrc) +} + +function getRegistryAuthInfo (checkUrl, options) { + var parsed = url.parse(checkUrl, false, true) + var pathname + + while (pathname !== '/' && parsed.pathname !== pathname) { + pathname = parsed.pathname || '/' + + var regUrl = '//' + parsed.host + pathname.replace(/\/$/, '') + var authInfo = getAuthInfoForUrl(regUrl, options.npmrc) + if (authInfo) { + return authInfo + } + + // break if not recursive + if (!options.recursive) { + return /\/$/.test(checkUrl) + ? undefined + : getRegistryAuthInfo(url.resolve(checkUrl, '.'), options) + } + + parsed.pathname = url.resolve(normalizePath(pathname), '..') || '/' + } + + return undefined +} + +function getLegacyAuthInfo (npmrc) { + if (!npmrc._auth) { + return undefined + } + + var token = replaceEnvironmentVariable(npmrc._auth) + + return { token: token, type: 'Basic' } +} + +function normalizePath (path) { + return path[path.length - 1] === '/' ? path : path + '/' +} + +function getAuthInfoForUrl (regUrl, npmrc) { + // try to get bearer token + var bearerAuth = getBearerToken(npmrc[regUrl + tokenKey] || npmrc[regUrl + '/' + tokenKey]) + if (bearerAuth) { + return bearerAuth + } + + // try to get basic token + var username = npmrc[regUrl + userKey] || npmrc[regUrl + '/' + userKey] + var password = npmrc[regUrl + passwordKey] || npmrc[regUrl + '/' + passwordKey] + var basicAuth = getTokenForUsernameAndPassword(username, password) + if (basicAuth) { + return basicAuth + } + + var basicAuthWithToken = getLegacyAuthToken(npmrc[regUrl + legacyTokenKey] || npmrc[regUrl + '/' + legacyTokenKey]) + if (basicAuthWithToken) { + return basicAuthWithToken + } + + return undefined +} + +function replaceEnvironmentVariable (token) { + return token.replace(/^\$\{?([^}]*)\}?$/, function (fullMatch, envVar) { + return process.env[envVar] + }) +} + +function getBearerToken (tok) { + if (!tok) { + return undefined + } + + // check if bearer token is set as environment variable + var token = replaceEnvironmentVariable(tok) + + return { token: token, type: 'Bearer' } +} + +function getTokenForUsernameAndPassword (username, password) { + if (!username || !password) { + return undefined + } + + // passwords are base64 encoded, so we need to decode it + // See https://github.com/npm/npm/blob/v3.10.6/lib/config/set-credentials-by-uri.js#L26 + var pass = decodeBase64(replaceEnvironmentVariable(password)) + + // a basic auth token is base64 encoded 'username:password' + // See https://github.com/npm/npm/blob/v3.10.6/lib/config/get-credentials-by-uri.js#L70 + var token = encodeBase64(username + ':' + pass) + + // we found a basicToken token so let's exit the loop + return { + token: token, + type: 'Basic', + password: pass, + username: username + } +} + +function getLegacyAuthToken (tok) { + if (!tok) { + return undefined + } + + // check if legacy auth token is set as environment variable + var token = replaceEnvironmentVariable(tok) + + return { token: token, type: 'Basic' } +} diff --git a/node_modules/registry-auth-token/package.json b/node_modules/registry-auth-token/package.json new file mode 100644 index 0000000..8d89747 --- /dev/null +++ b/node_modules/registry-auth-token/package.json @@ -0,0 +1,79 @@ +{ + "_args": [ + [ + "registry-auth-token@4.2.1", + "/home/other/discord_bot" + ] + ], + "_from": "registry-auth-token@4.2.1", + "_id": "registry-auth-token@4.2.1", + "_inBundle": false, + "_integrity": "sha512-6gkSb4U6aWJB4SF2ZvLb76yCBjcvufXBqvvEx1HbmKPkutswjW1xNVRY0+daljIYRbogN7O0etYSlbiaEQyMyw==", + "_location": "/registry-auth-token", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "registry-auth-token@4.2.1", + "name": "registry-auth-token", + "escapedName": "registry-auth-token", + "rawSpec": "4.2.1", + "saveSpec": null, + "fetchSpec": "4.2.1" + }, + "_requiredBy": [ + "/package-json" + ], + "_resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-4.2.1.tgz", + "_spec": "4.2.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "Espen Hovlandsdal", + "email": "espen@hovlandsdal.com" + }, + "bugs": { + "url": "https://github.com/rexxars/registry-auth-token/issues" + }, + "dependencies": { + "rc": "^1.2.8" + }, + "description": "Get the auth token set for an npm registry (if any)", + "devDependencies": { + "istanbul": "^0.4.2", + "mocha": "^6.1.4", + "require-uncached": "^1.0.2", + "standard": "^12.0.1" + }, + "engines": { + "node": ">=6.0.0" + }, + "homepage": "https://github.com/rexxars/registry-auth-token#readme", + "keywords": [ + "npm", + "conf", + "config", + "npmconf", + "registry", + "auth", + "token", + "authtoken" + ], + "license": "MIT", + "main": "index.js", + "name": "registry-auth-token", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/rexxars/registry-auth-token.git" + }, + "scripts": { + "coverage": "istanbul cover _mocha", + "posttest": "standard", + "test": "mocha" + }, + "standard": { + "ignore": [ + "coverage/**" + ] + }, + "version": "4.2.1" +} diff --git a/node_modules/registry-auth-token/registry-url.js b/node_modules/registry-auth-token/registry-url.js new file mode 100644 index 0000000..b4532d6 --- /dev/null +++ b/node_modules/registry-auth-token/registry-url.js @@ -0,0 +1,5 @@ +module.exports = function (scope, npmrc) { + var rc = npmrc || require('rc')('npm', { registry: 'https://registry.npmjs.org/' }) + var url = rc[scope + ':registry'] || rc.registry + return url.slice(-1) === '/' ? url : url + '/' +} diff --git a/node_modules/registry-url/index.d.ts b/node_modules/registry-url/index.d.ts new file mode 100644 index 0000000..5f2c586 --- /dev/null +++ b/node_modules/registry-url/index.d.ts @@ -0,0 +1,33 @@ +declare const registryUrl: { + /** + Get the set npm registry URL. + + @param scope - Retrieve the registry URL associated with an [npm scope](https://docs.npmjs.com/misc/scope). If the provided scope is not in the user's `.npmrc` file, then `registry-url` will check for the existence of `registry`, or if that's not set, fallback to the default npm registry. + + @example + ``` + import registryUrl = require('registry-url'); + + // # .npmrc + // registry = 'https://custom-registry.com/' + + console.log(registryUrl()); + //=> 'https://custom-registry.com/' + + + // # .npmrc + // @myco:registry = 'https://custom-registry.com/' + + console.log(registryUrl('@myco')); + //=> 'https://custom-registry.com/' + ``` + */ + (scope?: string): string; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function registryUrl(scope?: string): string; + // export = registryUrl; + default: typeof registryUrl; +}; + +export = registryUrl; diff --git a/node_modules/registry-url/index.js b/node_modules/registry-url/index.js new file mode 100644 index 0000000..23ea1f8 --- /dev/null +++ b/node_modules/registry-url/index.js @@ -0,0 +1,12 @@ +'use strict'; +const rc = require('rc'); + +const registryUrl = scope => { + const result = rc('npm', {registry: 'https://registry.npmjs.org/'}); + const url = result[`${scope}:registry`] || result.config_registry || result.registry; + return url.slice(-1) === '/' ? url : `${url}/`; +}; + +module.exports = registryUrl; +// TODO: Remove this for the next major release +module.exports.default = registryUrl; diff --git a/node_modules/registry-url/license b/node_modules/registry-url/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/registry-url/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/registry-url/package.json b/node_modules/registry-url/package.json new file mode 100644 index 0000000..571a7d8 --- /dev/null +++ b/node_modules/registry-url/package.json @@ -0,0 +1,79 @@ +{ + "_args": [ + [ + "registry-url@5.1.0", + "/home/other/discord_bot" + ] + ], + "_from": "registry-url@5.1.0", + "_id": "registry-url@5.1.0", + "_inBundle": false, + "_integrity": "sha512-8acYXXTI0AkQv6RAOjE3vOaIXZkT9wo4LOFbBKYQEEnnMNBpKqdUrI6S4NT0KPIo/WVvJ5tE/X5LF/TQUf0ekw==", + "_location": "/registry-url", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "registry-url@5.1.0", + "name": "registry-url", + "escapedName": "registry-url", + "rawSpec": "5.1.0", + "saveSpec": null, + "fetchSpec": "5.1.0" + }, + "_requiredBy": [ + "/package-json" + ], + "_resolved": "https://registry.npmjs.org/registry-url/-/registry-url-5.1.0.tgz", + "_spec": "5.1.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "ava": { + "serial": true + }, + "bugs": { + "url": "https://github.com/sindresorhus/registry-url/issues" + }, + "dependencies": { + "rc": "^1.2.8" + }, + "description": "Get the set npm registry URL", + "devDependencies": { + "ava": "^1.4.1", + "import-fresh": "^3.0.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/registry-url#readme", + "keywords": [ + "npm", + "conf", + "config", + "npmconf", + "registry", + "url", + "uri", + "scope" + ], + "license": "MIT", + "name": "registry-url", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/registry-url.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "5.1.0" +} diff --git a/node_modules/registry-url/readme.md b/node_modules/registry-url/readme.md new file mode 100644 index 0000000..dfcb99a --- /dev/null +++ b/node_modules/registry-url/readme.md @@ -0,0 +1,50 @@ +# registry-url [![Build Status](https://travis-ci.org/sindresorhus/registry-url.svg?branch=master)](https://travis-ci.org/sindresorhus/registry-url) + +> Get the set npm registry URL + +It's usually `https://registry.npmjs.org/`, but it's [configurable](https://docs.npmjs.com/misc/registry). + +Use this if you do anything with the npm registry as users will expect it to use their configured registry. + + +## Install + +``` +$ npm install registry-url +``` + + +## Usage + +```ini +# .npmrc +registry = 'https://custom-registry.com/' +``` + +```js +const registryUrl = require('registry-url'); + +console.log(registryUrl()); +//=> 'https://custom-registry.com/' +``` + +It can also retrieve the registry URL associated with an [npm scope](https://docs.npmjs.com/misc/scope). + +```ini +# .npmrc +@myco:registry = 'https://custom-registry.com/' +``` + +```js +const registryUrl = require('registry-url'); + +console.log(registryUrl('@myco')); +//=> 'https://custom-registry.com/' +``` + +If the provided scope is not in the user's `.npmrc` file, then `registry-url` will check for the existence of `registry`, or if that's not set, fallback to the default npm registry. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/responselike/LICENSE b/node_modules/responselike/LICENSE new file mode 100644 index 0000000..8829a00 --- /dev/null +++ b/node_modules/responselike/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2017 Luke Childs + +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/responselike/README.md b/node_modules/responselike/README.md new file mode 100644 index 0000000..6361931 --- /dev/null +++ b/node_modules/responselike/README.md @@ -0,0 +1,77 @@ +# responselike + +> A response-like object for mocking a Node.js HTTP response stream + +[![Build Status](https://travis-ci.org/lukechilds/responselike.svg?branch=master)](https://travis-ci.org/lukechilds/responselike) +[![Coverage Status](https://coveralls.io/repos/github/lukechilds/responselike/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/responselike?branch=master) +[![npm](https://img.shields.io/npm/dm/responselike.svg)](https://www.npmjs.com/package/responselike) +[![npm](https://img.shields.io/npm/v/responselike.svg)](https://www.npmjs.com/package/responselike) + +Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). Useful for formatting cached responses so they can be consumed by code expecting a real response. + +## Install + +```shell +npm install --save responselike +``` + +Or if you're just using for testing you'll want: + +```shell +npm install --save-dev responselike +``` + +## Usage + +```js +const Response = require('responselike'); + +const response = new Response(200, { foo: 'bar' }, Buffer.from('Hi!'), 'https://example.com'); + +response.statusCode; +// 200 +response.headers; +// { foo: 'bar' } +response.body; +// +response.url; +// 'https://example.com' + +response.pipe(process.stdout); +// Hi! +``` + + +## API + +### new Response(statusCode, headers, body, url) + +Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). + +#### statusCode + +Type: `number` + +HTTP response status code. + +#### headers + +Type: `object` + +HTTP headers object. Keys will be automatically lowercased. + +#### body + +Type: `buffer` + +A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. + +#### url + +Type: `string` + +Request URL string. + +## License + +MIT © Luke Childs diff --git a/node_modules/responselike/package.json b/node_modules/responselike/package.json new file mode 100644 index 0000000..3297653 --- /dev/null +++ b/node_modules/responselike/package.json @@ -0,0 +1,72 @@ +{ + "_args": [ + [ + "responselike@1.0.2", + "/home/other/discord_bot" + ] + ], + "_from": "responselike@1.0.2", + "_id": "responselike@1.0.2", + "_inBundle": false, + "_integrity": "sha1-kYcg7ztjHFZCvgaPFa3lpG9Loec=", + "_location": "/responselike", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "responselike@1.0.2", + "name": "responselike", + "escapedName": "responselike", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/cacheable-request" + ], + "_resolved": "https://registry.npmjs.org/responselike/-/responselike-1.0.2.tgz", + "_spec": "1.0.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "lukechilds" + }, + "bugs": { + "url": "https://github.com/lukechilds/responselike/issues" + }, + "dependencies": { + "lowercase-keys": "^1.0.0" + }, + "description": "A response-like object for mocking a Node.js HTTP response stream", + "devDependencies": { + "ava": "^0.22.0", + "coveralls": "^2.13.1", + "eslint-config-xo-lukechilds": "^1.0.0", + "get-stream": "^3.0.0", + "nyc": "^11.1.0", + "xo": "^0.19.0" + }, + "homepage": "https://github.com/lukechilds/responselike#readme", + "keywords": [ + "http", + "https", + "response", + "mock", + "request", + "responselike" + ], + "license": "MIT", + "main": "src/index.js", + "name": "responselike", + "repository": { + "type": "git", + "url": "git+https://github.com/lukechilds/responselike.git" + }, + "scripts": { + "coverage": "nyc report --reporter=text-lcov | coveralls", + "test": "xo && nyc ava" + }, + "version": "1.0.2", + "xo": { + "extends": "xo-lukechilds" + } +} diff --git a/node_modules/responselike/src/index.js b/node_modules/responselike/src/index.js new file mode 100644 index 0000000..b17b481 --- /dev/null +++ b/node_modules/responselike/src/index.js @@ -0,0 +1,34 @@ +'use strict'; + +const Readable = require('stream').Readable; +const lowercaseKeys = require('lowercase-keys'); + +class Response extends Readable { + constructor(statusCode, headers, body, url) { + if (typeof statusCode !== 'number') { + throw new TypeError('Argument `statusCode` should be a number'); + } + if (typeof headers !== 'object') { + throw new TypeError('Argument `headers` should be an object'); + } + if (!(body instanceof Buffer)) { + throw new TypeError('Argument `body` should be a buffer'); + } + if (typeof url !== 'string') { + throw new TypeError('Argument `url` should be a string'); + } + + super(); + this.statusCode = statusCode; + this.headers = lowercaseKeys(headers); + this.body = body; + this.url = url; + } + + _read() { + this.push(this.body); + this.push(null); + } +} + +module.exports = Response; diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..f8d3ec9 --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..6f1e827 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,84 @@ +{ + "_args": [ + [ + "safe-buffer@5.2.1", + "/home/other/discord_bot" + ] + ], + "_from": "safe-buffer@5.2.1", + "_id": "safe-buffer@5.2.1", + "_inBundle": false, + "_integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "_location": "/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "safe-buffer@5.2.1", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "5.2.1", + "saveSpec": null, + "fetchSpec": "5.2.1" + }, + "_requiredBy": [ + "/ecdsa-sig-formatter", + "/faye", + "/jwa", + "/jws", + "/tunnel-agent", + "/websocket-driver" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "_spec": "5.2.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "name": "safe-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "types": "index.d.ts", + "version": "5.2.1" +} diff --git a/node_modules/semver-diff/index.d.ts b/node_modules/semver-diff/index.d.ts new file mode 100644 index 0000000..d6f6a42 --- /dev/null +++ b/node_modules/semver-diff/index.d.ts @@ -0,0 +1,58 @@ +declare namespace semverDiff { + type Result = + | 'major' + | 'premajor' + | 'minor' + | 'preminor' + | 'patch' + | 'prepatch' + | 'prerelease' + | 'build'; +} + +/** +Get the diff type of two [semver](https://github.com/npm/node-semver) versions: `0.0.1 0.0.2` → `patch`. + +@returns The difference type between two semver versions, or `undefined` if they're identical or the second one is lower than the first. + +@example +``` +import semverDiff = require('semver-diff'); + +semverDiff('1.1.1', '1.1.2'); +//=> 'patch' + +semverDiff('1.1.1-foo', '1.1.2'); +//=> 'prepatch' + +semverDiff('0.0.1', '1.0.0'); +//=> 'major' + +semverDiff('0.0.1-foo', '1.0.0'); +//=> 'premajor' + +semverDiff('0.0.1', '0.1.0'); +//=> 'minor' + +semverDiff('0.0.1-foo', '0.1.0'); +//=> 'preminor' + +semverDiff('0.0.1-foo', '0.0.1-foo.bar'); +//=> 'prerelease' + +semverDiff('0.1.0', '0.1.0+foo'); +//=> 'build' + +semverDiff('0.0.1', '0.0.1'); +//=> undefined + +semverDiff('0.0.2', '0.0.1'); +//=> undefined +``` +*/ +declare function semverDiff( + versionA: string, + versionB: string +): semverDiff.Result | undefined; + +export = semverDiff; diff --git a/node_modules/semver-diff/index.js b/node_modules/semver-diff/index.js new file mode 100644 index 0000000..5521801 --- /dev/null +++ b/node_modules/semver-diff/index.js @@ -0,0 +1,13 @@ +'use strict'; +const semver = require('semver'); + +module.exports = (versionA, versionB) => { + versionA = semver.parse(versionA); + versionB = semver.parse(versionB); + + if (semver.compareBuild(versionA, versionB) >= 0) { + return; + } + + return semver.diff(versionA, versionB) || 'build'; +}; diff --git a/node_modules/semver-diff/license b/node_modules/semver-diff/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/semver-diff/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/semver-diff/node_modules/.bin/semver b/node_modules/semver-diff/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/semver-diff/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/semver-diff/node_modules/semver/CHANGELOG.md b/node_modules/semver-diff/node_modules/semver/CHANGELOG.md new file mode 100644 index 0000000..f567dd3 --- /dev/null +++ b/node_modules/semver-diff/node_modules/semver/CHANGELOG.md @@ -0,0 +1,70 @@ +# changes log + +## 6.2.0 + +* Coerce numbers to strings when passed to semver.coerce() +* Add `rtl` option to coerce from right to left + +## 6.1.3 + +* Handle X-ranges properly in includePrerelease mode + +## 6.1.2 + +* Do not throw when testing invalid version strings + +## 6.1.1 + +* Add options support for semver.coerce() +* Handle undefined version passed to Range.test + +## 6.1.0 + +* Add semver.compareBuild function +* Support `*` in semver.intersects + +## 6.0 + +* Fix `intersects` logic. + + This is technically a bug fix, but since it is also a change to behavior + that may require users updating their code, it is marked as a major + version increment. + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/node_modules/semver-diff/node_modules/semver/LICENSE b/node_modules/semver-diff/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/semver-diff/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver-diff/node_modules/semver/README.md b/node_modules/semver-diff/node_modules/semver/README.md new file mode 100644 index 0000000..2293a14 --- /dev/null +++ b/node_modules/semver-diff/node_modules/semver/README.md @@ -0,0 +1,443 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` diff --git a/node_modules/semver-diff/node_modules/semver/bin/semver.js b/node_modules/semver-diff/node_modules/semver/bin/semver.js new file mode 100755 index 0000000..666034a --- /dev/null +++ b/node_modules/semver-diff/node_modules/semver/bin/semver.js @@ -0,0 +1,174 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var rtl = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + '--rtl', + ' Coerce version strings right to left', + '', + '--ltr', + ' Coerce version strings left to right (default)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/node_modules/semver-diff/node_modules/semver/package.json b/node_modules/semver-diff/node_modules/semver/package.json new file mode 100644 index 0000000..e48c763 --- /dev/null +++ b/node_modules/semver-diff/node_modules/semver/package.json @@ -0,0 +1,63 @@ +{ + "_args": [ + [ + "semver@6.3.0", + "/home/other/discord_bot" + ] + ], + "_from": "semver@6.3.0", + "_id": "semver@6.3.0", + "_inBundle": false, + "_integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "_location": "/semver-diff/semver", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "semver@6.3.0", + "name": "semver", + "escapedName": "semver", + "rawSpec": "6.3.0", + "saveSpec": null, + "fetchSpec": "6.3.0" + }, + "_requiredBy": [ + "/semver-diff" + ], + "_resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "_spec": "6.3.0", + "_where": "/home/other/discord_bot", + "bin": { + "semver": "bin/semver.js" + }, + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "description": "The semantic version parser used by npm.", + "devDependencies": { + "tap": "^14.3.1" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "homepage": "https://github.com/npm/node-semver#readme", + "license": "ISC", + "main": "semver.js", + "name": "semver", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "scripts": { + "postpublish": "git push origin --follow-tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap" + }, + "tap": { + "check-coverage": true + }, + "version": "6.3.0" +} diff --git a/node_modules/semver-diff/node_modules/semver/range.bnf b/node_modules/semver-diff/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/semver-diff/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver-diff/node_modules/semver/semver.js b/node_modules/semver-diff/node_modules/semver/semver.js new file mode 100644 index 0000000..636fa43 --- /dev/null +++ b/node_modules/semver-diff/node_modules/semver/semver.js @@ -0,0 +1,1596 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var t = exports.tokens = {} +var R = 0 + +function tok (n) { + t[n] = R++ +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +tok('NUMERICIDENTIFIER') +src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*' +tok('NUMERICIDENTIFIERLOOSE') +src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +tok('NONNUMERICIDENTIFIER') +src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +tok('MAINVERSION') +src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIER] + ')' + +tok('MAINVERSIONLOOSE') +src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +tok('PRERELEASEIDENTIFIER') +src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +tok('PRERELEASEIDENTIFIERLOOSE') +src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + + '|' + src[t.NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +tok('PRERELEASE') +src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))' + +tok('PRERELEASELOOSE') +src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +tok('BUILDIDENTIFIER') +src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +tok('BUILD') +src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +tok('FULL') +tok('FULLPLAIN') +src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + + src[t.PRERELEASE] + '?' + + src[t.BUILD] + '?' + +src[t.FULL] = '^' + src[t.FULLPLAIN] + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +tok('LOOSEPLAIN') +src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + + src[t.PRERELEASELOOSE] + '?' + + src[t.BUILD] + '?' + +tok('LOOSE') +src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$' + +tok('GTLT') +src[t.GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +tok('XRANGEIDENTIFIERLOOSE') +src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +tok('XRANGEIDENTIFIER') +src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*' + +tok('XRANGEPLAIN') +src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + + '(?:' + src[t.PRERELEASE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGEPLAINLOOSE') +src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[t.PRERELEASELOOSE] + ')?' + + src[t.BUILD] + '?' + + ')?)?' + +tok('XRANGE') +src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$' +tok('XRANGELOOSE') +src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +tok('COERCE') +src[t.COERCE] = '(^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' +tok('COERCERTL') +re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g') + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +tok('LONETILDE') +src[t.LONETILDE] = '(?:~>?)' + +tok('TILDETRIM') +src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+' +re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +tok('TILDE') +src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$' +tok('TILDELOOSE') +src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +tok('LONECARET') +src[t.LONECARET] = '(?:\\^)' + +tok('CARETTRIM') +src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+' +re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +tok('CARET') +src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$' +tok('CARETLOOSE') +src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +tok('COMPARATORLOOSE') +src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$' +tok('COMPARATOR') +src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +tok('COMPARATORTRIM') +src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +tok('HYPHENRANGE') +src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAIN] + ')' + + '\\s*$' + +tok('HYPHENRANGELOOSE') +src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[t.XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +tok('STAR') +src[t.STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +SemVer.prototype.compareBuild = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + var i = 0 + do { + var a = this.build[i] + var b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.compareBuild = compareBuild +function compareBuild (a, b, loose) { + var versionA = new SemVer(a, loose) + var versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.compareBuild(b, a, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + if (this.value === '') { + return true + } + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[t.COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return ( + isSatisfiable(thisComparators, options) && + range.set.some(function (rangeComparators) { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every(function (thisComparator) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) +} + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +function isSatisfiable (comparators, options) { + var result = true + var remainingComparators = comparators.slice() + var testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every(function (otherComparator) { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + pr + } else if (xm) { + ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr + } else if (xp) { + ret = '>=' + M + '.' + m + '.0' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + pr + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version, options) { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + var match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + var next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(match[2] + + '.' + (match[3] || '0') + + '.' + (match[4] || '0'), options) +} diff --git a/node_modules/semver-diff/package.json b/node_modules/semver-diff/package.json new file mode 100644 index 0000000..5978808 --- /dev/null +++ b/node_modules/semver-diff/package.json @@ -0,0 +1,73 @@ +{ + "_args": [ + [ + "semver-diff@3.1.1", + "/home/other/discord_bot" + ] + ], + "_from": "semver-diff@3.1.1", + "_id": "semver-diff@3.1.1", + "_inBundle": false, + "_integrity": "sha512-GX0Ix/CJcHyB8c4ykpHGIAvLyOwOobtM/8d+TQkAd81/bEjgPHrfba41Vpesr7jX/t8Uh+R3EX9eAS5be+jQYg==", + "_location": "/semver-diff", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "semver-diff@3.1.1", + "name": "semver-diff", + "escapedName": "semver-diff", + "rawSpec": "3.1.1", + "saveSpec": null, + "fetchSpec": "3.1.1" + }, + "_requiredBy": [ + "/nodemon/update-notifier", + "/update-notifier" + ], + "_resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-3.1.1.tgz", + "_spec": "3.1.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/semver-diff/issues" + }, + "dependencies": { + "semver": "^6.3.0" + }, + "description": "Get the diff type of two semver versions: 0.0.1 0.0.2 → patch", + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.9.0", + "xo": "^0.25.3" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/semver-diff#readme", + "keywords": [ + "semver", + "version", + "semantic", + "diff", + "difference" + ], + "license": "MIT", + "name": "semver-diff", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/semver-diff.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "3.1.1" +} diff --git a/node_modules/semver-diff/readme.md b/node_modules/semver-diff/readme.md new file mode 100644 index 0000000..6e21aff --- /dev/null +++ b/node_modules/semver-diff/readme.md @@ -0,0 +1,77 @@ +# semver-diff [![Build Status](https://travis-ci.org/sindresorhus/semver-diff.svg?branch=master)](https://travis-ci.org/sindresorhus/semver-diff) + +> Get the diff type of two [semver](https://github.com/npm/node-semver) versions: `0.0.1 0.0.2` → `patch` + + +## Install + +``` +$ npm install semver-diff +``` + + +## Usage + +```js +const semverDiff = require('semver-diff'); + +semverDiff('1.1.1', '1.1.2'); +//=> 'patch' + +semverDiff('1.1.1-foo', '1.1.2'); +//=> 'prepatch' + +semverDiff('0.0.1', '1.0.0'); +//=> 'major' + +semverDiff('0.0.1-foo', '1.0.0'); +//=> 'premajor' + +semverDiff('0.0.1', '0.1.0'); +//=> 'minor' + +semverDiff('0.0.1-foo', '0.1.0'); +//=> 'preminor' + +semverDiff('0.0.1-foo', '0.0.1-foo.bar'); +//=> 'prerelease' + +semverDiff('0.1.0', '0.1.0+foo'); +//=> 'build' + +semverDiff('0.0.1', '0.0.1'); +//=> undefined + +semverDiff('0.0.2', '0.0.1'); +//=> undefined +``` + + +## API + +### semverDiff(versionA, versionB) + +Returns the difference type between two semver versions, or `undefined` if they're identical or the second one is lower than the first. + +Possible values: `'major'`, `'premajor'`, `'minor'`, `'preminor'`, `'patch'`, `'prepatch'`, `'prerelease'`, `'build'`, `undefined`. + + +## Related + +- [latest-semver](https://github.com/sindresorhus/latest-semver) - Get the latest stable semver version from an array of versions +- [to-semver](https://github.com/sindresorhus/to-semver) - Get an array of valid, sorted, and cleaned semver versions from an array of strings +- [semver-regex](https://github.com/sindresorhus/semver-regex) - Regular expression for matching semver versions +- [semver-truncate](https://github.com/sindresorhus/semver-truncate) - Truncate a semver version: `1.2.3` → `1.2.0` + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/semver/CHANGELOG.md b/node_modules/semver/CHANGELOG.md new file mode 100644 index 0000000..66304fd --- /dev/null +++ b/node_modules/semver/CHANGELOG.md @@ -0,0 +1,39 @@ +# changes log + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver/README.md b/node_modules/semver/README.md new file mode 100644 index 0000000..f8dfa5a --- /dev/null +++ b/node_modules/semver/README.md @@ -0,0 +1,412 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install --save semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/node_modules/semver/bin/semver b/node_modules/semver/bin/semver new file mode 100755 index 0000000..801e77f --- /dev/null +++ b/node_modules/semver/bin/semver @@ -0,0 +1,160 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json new file mode 100644 index 0000000..8b50069 --- /dev/null +++ b/node_modules/semver/package.json @@ -0,0 +1,64 @@ +{ + "_args": [ + [ + "semver@5.7.1", + "/home/other/discord_bot" + ] + ], + "_from": "semver@5.7.1", + "_id": "semver@5.7.1", + "_inBundle": false, + "_integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "_location": "/semver", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "semver@5.7.1", + "name": "semver", + "escapedName": "semver", + "rawSpec": "5.7.1", + "saveSpec": null, + "fetchSpec": "5.7.1" + }, + "_requiredBy": [ + "/jsonwebtoken", + "/nodemon" + ], + "_resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "_spec": "5.7.1", + "_where": "/home/other/discord_bot", + "bin": { + "semver": "bin/semver" + }, + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "description": "The semantic version parser used by npm.", + "devDependencies": { + "tap": "^13.0.0-rc.18" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "homepage": "https://github.com/npm/node-semver#readme", + "license": "ISC", + "main": "semver.js", + "name": "semver", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap" + }, + "tap": { + "check-coverage": true + }, + "version": "5.7.1" +} diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/semver.js b/node_modules/semver/semver.js new file mode 100644 index 0000000..d315d5d --- /dev/null +++ b/node_modules/semver/semver.js @@ -0,0 +1,1483 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' + +src[FULL] = '^' + FULLPLAIN + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' + +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' + +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' + +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' + +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' + +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY) { + return true + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(re[COERCE]) + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} diff --git a/node_modules/sequin/README.md b/node_modules/sequin/README.md new file mode 100644 index 0000000..03aa249 --- /dev/null +++ b/node_modules/sequin/README.md @@ -0,0 +1,62 @@ +# sequin [![Build status](https://secure.travis-ci.org/jcoglan/sequin.png)](https://travis-ci.org/jcoglan/sequin) + +Generates uniformly distributed ints in any base from a bit sequence, according +to the algorithm [described by Christian +Perfect](http://checkmyworking.com/2012/06/converting-a-stream-of-binary-digits-to-a-stream-of-base-n-digits/). + + +## Installation + +``` +$ npm install sequin +``` + + +## Usage + +Construct a stream using an array of `0`/`1` values, or using a `Buffer` with +the second argument set to `8`: + +```js +var Sequin = require('sequin'), + crypto = require('crypto'), + stream = new Sequin(crypto.randomBytes(10), 8); +``` + +The stream's `generate(k)` method returns an integer less than `k`, or `null` if +there are not enough bits left in the stream to generate an integer of the +required size. + +```js +var Sequin = require('sequin'), + stream = new Sequin([1,1,0,1,0,1,0,1,1,1,1,1,0,0,1]); + +stream.generate(5) // -> 3 +stream.generate(5) // -> 3 +stream.generate(5) // -> 1 +stream.generate(5) // -> null +``` + + +## License + +(The MIT License) + +Copyright (c) 2012-2017 James Coglan + +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/sequin/lib/sequin.js b/node_modules/sequin/lib/sequin.js new file mode 100644 index 0000000..0209543 --- /dev/null +++ b/node_modules/sequin/lib/sequin.js @@ -0,0 +1,63 @@ +'use strict'; + +var Stream = function(sequence, bits) { + bits = bits || (sequence instanceof Buffer ? 8 : 1); + var binary = '', b, i, n; + + for (i = 0, n = sequence.length; i < n; i++) { + b = this._get(sequence, i).toString(2); + while (b.length < bits) b = '0' + b; + binary = binary + b; + } + binary = binary.split('').map(function(b) { return parseInt(b, 2) }); + + this._bases = {'2': binary}; +}; + +Stream.prototype.generate = function(n, base, inner) { + base = base || 2; + + var value = n, + k = Math.ceil(Math.log(n) / Math.log(base)), + r = Math.pow(base, k) - n, + chunk; + + loop: while (value >= n) { + chunk = this._shift(base, k); + if (!chunk) return inner ? n : null; + + value = this._evaluate(chunk, base); + + if (value >= n) { + if (r === 1) continue loop; + this._push(r, value - n); + value = this.generate(n, r, true); + } + } + return value; +}; + +Stream.prototype._get = function(sequence, i) { + return sequence.readUInt8 ? sequence.readUInt8(i) : sequence[i]; +}; + +Stream.prototype._evaluate = function(chunk, base) { + var sum = 0, + i = chunk.length; + + while (i--) sum += chunk[i] * Math.pow(base, chunk.length - (i+1)); + return sum; +}; + +Stream.prototype._push = function(base, value) { + this._bases[base] = this._bases[base] || []; + this._bases[base].push(value); +}; + +Stream.prototype._shift = function(base, k) { + var list = this._bases[base]; + if (!list || list.length < k) return null; + else return list.splice(0,k); +}; + +module.exports = Stream; diff --git a/node_modules/sequin/package.json b/node_modules/sequin/package.json new file mode 100644 index 0000000..7cef7f6 --- /dev/null +++ b/node_modules/sequin/package.json @@ -0,0 +1,60 @@ +{ + "_args": [ + [ + "sequin@0.1.1", + "/home/other/discord_bot" + ] + ], + "_from": "sequin@0.1.1", + "_id": "sequin@0.1.1", + "_inBundle": false, + "_integrity": "sha1-XC04nWajg3NOqvvEXt6ywcsb5wE=", + "_location": "/sequin", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "sequin@0.1.1", + "name": "sequin", + "escapedName": "sequin", + "rawSpec": "0.1.1", + "saveSpec": null, + "fetchSpec": "0.1.1" + }, + "_requiredBy": [ + "/csprng" + ], + "_resolved": "https://registry.npmjs.org/sequin/-/sequin-0.1.1.tgz", + "_spec": "0.1.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "James Coglan", + "email": "jcoglan@gmail.com", + "url": "http://jcoglan.com/" + }, + "bugs": { + "url": "https://github.com/jcoglan/sequin/issues" + }, + "description": "Generate uniformly distributed ints in any base from a bit sequence", + "devDependencies": { + "jstest": "" + }, + "engines": { + "node": ">=0.4.0" + }, + "homepage": "https://github.com/jcoglan/sequin", + "keywords": [ + "math" + ], + "license": "MIT", + "main": "./lib/sequin", + "name": "sequin", + "repository": { + "type": "git", + "url": "git://github.com/jcoglan/sequin.git" + }, + "scripts": { + "test": "jstest spec/sequin_spec.js" + }, + "version": "0.1.1" +} diff --git a/node_modules/side-channel/.eslintignore b/node_modules/side-channel/.eslintignore new file mode 100644 index 0000000..404abb2 --- /dev/null +++ b/node_modules/side-channel/.eslintignore @@ -0,0 +1 @@ +coverage/ diff --git a/node_modules/side-channel/.eslintrc b/node_modules/side-channel/.eslintrc new file mode 100644 index 0000000..850ac1f --- /dev/null +++ b/node_modules/side-channel/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "max-params": 0, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel/.github/FUNDING.yml b/node_modules/side-channel/.github/FUNDING.yml new file mode 100644 index 0000000..2a94840 --- /dev/null +++ b/node_modules/side-channel/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel/.nycrc b/node_modules/side-channel/.nycrc new file mode 100644 index 0000000..1826526 --- /dev/null +++ b/node_modules/side-channel/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel/CHANGELOG.md b/node_modules/side-channel/CHANGELOG.md new file mode 100644 index 0000000..a3d161f --- /dev/null +++ b/node_modules/side-channel/CHANGELOG.md @@ -0,0 +1,65 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.4](https://github.com/ljharb/side-channel/compare/v1.0.3...v1.0.4) - 2020-12-29 + +### Commits + +- [Tests] migrate tests to Github Actions [`10909cb`](https://github.com/ljharb/side-channel/commit/10909cbf8ce9c0bf96f604cf13d7ffd5a22c2d40) +- [Refactor] Use a linked list rather than an array, and move accessed nodes to the beginning [`195613f`](https://github.com/ljharb/side-channel/commit/195613f28b5c1e6072ef0b61b5beebaf2b6a304e) +- [meta] do not publish github action workflow files [`290ec29`](https://github.com/ljharb/side-channel/commit/290ec29cd21a60585145b4a7237ec55228c52c27) +- [Tests] run `nyc` on all tests; use `tape` runner [`ea6d030`](https://github.com/ljharb/side-channel/commit/ea6d030ff3fe6be2eca39e859d644c51ecd88869) +- [actions] add "Allow Edits" workflow [`d464d8f`](https://github.com/ljharb/side-channel/commit/d464d8fe52b5eddf1504a0ed97f0941a90f32c15) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`02daca8`](https://github.com/ljharb/side-channel/commit/02daca87c6809821c97be468d1afa2f5ef447383) +- [Refactor] use `call-bind` and `get-intrinsic` instead of `es-abstract` [`e09d481`](https://github.com/ljharb/side-channel/commit/e09d481528452ebafa5cdeae1af665c35aa2deee) +- [Deps] update `object.assign` [`ee83aa8`](https://github.com/ljharb/side-channel/commit/ee83aa81df313b5e46319a63adb05cf0c179079a) +- [actions] update rebase action to use checkout v2 [`7726b0b`](https://github.com/ljharb/side-channel/commit/7726b0b058b632fccea709f58960871defaaa9d7) + +## [v1.0.3](https://github.com/ljharb/side-channel/compare/v1.0.2...v1.0.3) - 2020-08-23 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`1f10561`](https://github.com/ljharb/side-channel/commit/1f105611ef3acf32dec8032ae5c0baa5e56bb868) +- [Deps] update `es-abstract`, `object-inspect` [`bc20159`](https://github.com/ljharb/side-channel/commit/bc201597949a505e37cef9eaf24c7010831e6f03) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`b9b2b22`](https://github.com/ljharb/side-channel/commit/b9b2b225f9e0ea72a6ec2b89348f0bd690bc9ed1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7055ab4`](https://github.com/ljharb/side-channel/commit/7055ab4de0860606efd2003674a74f1fe6ebc07e) +- [Dev Deps] update `auto-changelog`; add `aud` [`d278c37`](https://github.com/ljharb/side-channel/commit/d278c37d08227be4f84aa769fcd919e73feeba40) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`3bcf982`](https://github.com/ljharb/side-channel/commit/3bcf982faa122745b39c33ce83d32fdf003741c6) +- [Tests] only audit prod deps [`18d01c4`](https://github.com/ljharb/side-channel/commit/18d01c4015b82a3d75044c4d5ba7917b2eac01ec) +- [Deps] update `es-abstract` [`6ab096d`](https://github.com/ljharb/side-channel/commit/6ab096d9de2b482cf5e0717e34e212f5b2b9bc9a) +- [Dev Deps] update `tape` [`9dc174c`](https://github.com/ljharb/side-channel/commit/9dc174cc651dfd300b4b72da936a0a7eda5f9452) +- [Deps] update `es-abstract` [`431d0f0`](https://github.com/ljharb/side-channel/commit/431d0f0ff11fbd2ae6f3115582a356d3a1cfce82) +- [Deps] update `es-abstract` [`49869fd`](https://github.com/ljharb/side-channel/commit/49869fd323bf4453f0ba515c0fb265cf5ab7b932) +- [meta] Add package.json to package's exports [`77d9cdc`](https://github.com/ljharb/side-channel/commit/77d9cdceb2a9e47700074f2ae0c0a202e7dac0d4) + +## [v1.0.2](https://github.com/ljharb/side-channel/compare/v1.0.1...v1.0.2) - 2019-12-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`4a526df`](https://github.com/ljharb/side-channel/commit/4a526df44e4701566ed001ec78546193f818b082) +- [Deps] update `es-abstract` [`d4f6e62`](https://github.com/ljharb/side-channel/commit/d4f6e629b6fb93a07415db7f30d3c90fd7f264fe) + +## [v1.0.1](https://github.com/ljharb/side-channel/compare/v1.0.0...v1.0.1) - 2019-12-01 + +### Commits + +- [Fix] add missing "exports" [`d212907`](https://github.com/ljharb/side-channel/commit/d2129073abf0701a5343bf28aa2145617604dc2e) + +## v1.0.0 - 2019-12-01 + +### Commits + +- Initial implementation [`dbebd3a`](https://github.com/ljharb/side-channel/commit/dbebd3a4b5ed64242f9a6810efe7c4214cd8cde4) +- Initial tests [`73bdefe`](https://github.com/ljharb/side-channel/commit/73bdefe568c9076cf8c0b8719bc2141aec0e19b8) +- Initial commit [`43c03e1`](https://github.com/ljharb/side-channel/commit/43c03e1c2849ec50a87b7a5cd76238a62b0b8770) +- npm init [`5c090a7`](https://github.com/ljharb/side-channel/commit/5c090a765d66a5527d9889b89aeff78dee91348c) +- [meta] add `auto-changelog` [`a5c4e56`](https://github.com/ljharb/side-channel/commit/a5c4e5675ec02d5eb4d84b4243aeea2a1d38fbec) +- [actions] add automatic rebasing / merge commit blocking [`bab1683`](https://github.com/ljharb/side-channel/commit/bab1683d8f9754b086e94397699fdc645e0d7077) +- [meta] add `funding` field; create FUNDING.yml [`63d7aea`](https://github.com/ljharb/side-channel/commit/63d7aeaf34f5650650ae97ca4b9fae685bd0937c) +- [Tests] add `npm run lint` [`46a5a81`](https://github.com/ljharb/side-channel/commit/46a5a81705cd2664f83df232c01dbbf2ee952885) +- Only apps should have lockfiles [`8b16b03`](https://github.com/ljharb/side-channel/commit/8b16b0305f00895d90c4e2e5773c854cfea0e448) +- [meta] add `safe-publish-latest` [`2f098ef`](https://github.com/ljharb/side-channel/commit/2f098ef092a39399cfe548b19a1fc03c2fd2f490) diff --git a/node_modules/side-channel/LICENSE b/node_modules/side-channel/LICENSE new file mode 100644 index 0000000..3900dd7 --- /dev/null +++ b/node_modules/side-channel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +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/side-channel/README.md b/node_modules/side-channel/README.md new file mode 100644 index 0000000..7fa4f06 --- /dev/null +++ b/node_modules/side-channel/README.md @@ -0,0 +1,2 @@ +# side-channel +Store information about any JS value in a side channel. Uses WeakMap if available. diff --git a/node_modules/side-channel/index.js b/node_modules/side-channel/index.js new file mode 100644 index 0000000..f1c4826 --- /dev/null +++ b/node_modules/side-channel/index.js @@ -0,0 +1,124 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bind/callBound'); +var inspect = require('object-inspect'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); +var $Map = GetIntrinsic('%Map%', true); + +var $weakMapGet = callBound('WeakMap.prototype.get', true); +var $weakMapSet = callBound('WeakMap.prototype.set', true); +var $weakMapHas = callBound('WeakMap.prototype.has', true); +var $mapGet = callBound('Map.prototype.get', true); +var $mapSet = callBound('Map.prototype.set', true); +var $mapHas = callBound('Map.prototype.has', true); + +/* + * This function traverses the list returning the node corresponding to the + * given key. + * + * That node is also moved to the head of the list, so that if it's accessed + * again we don't need to traverse the whole list. By doing so, all the recently + * used nodes can be accessed relatively quickly. + */ +var listGetNode = function (list, key) { // eslint-disable-line consistent-return + for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + curr.next = list.next; + list.next = curr; // eslint-disable-line no-param-reassign + return curr; + } + } +}; + +var listGet = function (objects, key) { + var node = listGetNode(objects, key); + return node && node.value; +}; +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = { // eslint-disable-line no-param-reassign + key: key, + next: objects.next, + value: value + }; + } +}; +var listHas = function (objects, key) { + return !!listGetNode(objects, key); +}; + +module.exports = function getSideChannel() { + var $wm; + var $m; + var $o; + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + get: function (key) { // eslint-disable-line consistent-return + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapGet($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listGet($o, key); + } + } + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } else if ($Map) { + if ($m) { + return $mapHas($m, key); + } + } else { + if ($o) { // eslint-disable-line no-lonely-if + return listHas($o, key); + } + } + return false; + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if ($Map) { + if (!$m) { + $m = new $Map(); + } + $mapSet($m, key, value); + } else { + if (!$o) { + /* + * Initialize the linked list as an empty node, so that we don't have + * to special-case handling of the first node: we can always refer to + * it as (previous node).next, instead of something like (list).head + */ + $o = { key: {}, next: null }; + } + listSet($o, key, value); + } + } + }; + return channel; +}; diff --git a/node_modules/side-channel/package.json b/node_modules/side-channel/package.json new file mode 100644 index 0000000..f55726e --- /dev/null +++ b/node_modules/side-channel/package.json @@ -0,0 +1,98 @@ +{ + "_args": [ + [ + "side-channel@1.0.4", + "/home/other/discord_bot" + ] + ], + "_from": "side-channel@1.0.4", + "_id": "side-channel@1.0.4", + "_inBundle": false, + "_integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "_location": "/side-channel", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "side-channel@1.0.4", + "name": "side-channel", + "escapedName": "side-channel", + "rawSpec": "1.0.4", + "saveSpec": null, + "fetchSpec": "1.0.4" + }, + "_requiredBy": [ + "/qs" + ], + "_resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "_spec": "1.0.4", + "_where": "/home/other/discord_bot", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "bugs": { + "url": "https://github.com/ljharb/side-channel/issues" + }, + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "devDependencies": { + "@ljharb/eslint-config": "^17.3.0", + "aud": "^1.1.3", + "auto-changelog": "^2.2.1", + "eslint": "^7.16.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.0.1" + }, + "exports": { + "./package.json": "./package.json", + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ] + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "homepage": "https://github.com/ljharb/side-channel#readme", + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "license": "MIT", + "main": "index.js", + "name": "side-channel", + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel.git" + }, + "scripts": { + "lint": "eslint .", + "posttest": "npx aud --production", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepublish": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "version": "auto-changelog && git add CHANGELOG.md" + }, + "version": "1.0.4" +} diff --git a/node_modules/side-channel/test/index.js b/node_modules/side-channel/test/index.js new file mode 100644 index 0000000..3b92ef7 --- /dev/null +++ b/node_modules/side-channel/test/index.js @@ -0,0 +1,78 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannel = require('../'); + +test('export', function (t) { + t.equal(typeof getSideChannel, 'function', 'is a function'); + t.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + t.ok(channel, 'is truthy'); + t.equal(typeof channel, 'object', 'is an object'); + + t.end(); +}); + +test('assert', function (t) { + var channel = getSideChannel(); + t['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + t.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + t.end(); +}); + +test('has', function (t) { + var channel = getSideChannel(); + var o = []; + + t.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + t.equal(channel.has(o), true, 'existent value yields true'); + + t.end(); +}); + +test('get', function (t) { + var channel = getSideChannel(); + var o = {}; + t.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + t.equal(channel.get(o), data, '"get" yields data set by "set"'); + + t.end(); +}); + +test('set', function (t) { + var channel = getSideChannel(); + var o = function () {}; + t.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + t.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + t.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + t.equal(channel.get(o), Infinity, 'o is not modified'); + t.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + t.equal(channel.get(o), 14, 'o is modified'); + t.equal(channel.get(o2), 17, 'o2 is not modified'); + + t.end(); +}); diff --git a/node_modules/signal-exit/CHANGELOG.md b/node_modules/signal-exit/CHANGELOG.md new file mode 100644 index 0000000..ed104f4 --- /dev/null +++ b/node_modules/signal-exit/CHANGELOG.md @@ -0,0 +1,35 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [3.0.3](https://github.com/tapjs/signal-exit/compare/v3.0.2...v3.0.3) (2020-03-26) + + +### Bug Fixes + +* patch `SIGHUP` to `SIGINT` when on Windows ([cfd1046](https://github.com/tapjs/signal-exit/commit/cfd1046079af4f0e44f93c69c237a09de8c23ef2)) +* **ci:** use Travis for Windows builds ([007add7](https://github.com/tapjs/signal-exit/commit/007add793d2b5ae3c382512103adbf321768a0b8)) + + +## [3.0.1](https://github.com/tapjs/signal-exit/compare/v3.0.0...v3.0.1) (2016-09-08) + + +### Bug Fixes + +* do not listen on SIGBUS, SIGFPE, SIGSEGV and SIGILL ([#40](https://github.com/tapjs/signal-exit/issues/40)) ([5b105fb](https://github.com/tapjs/signal-exit/commit/5b105fb)) + + + + +# [3.0.0](https://github.com/tapjs/signal-exit/compare/v2.1.2...v3.0.0) (2016-06-13) + + +### Bug Fixes + +* get our test suite running on Windows ([#23](https://github.com/tapjs/signal-exit/issues/23)) ([6f3eda8](https://github.com/tapjs/signal-exit/commit/6f3eda8)) +* hooking SIGPROF was interfering with profilers see [#21](https://github.com/tapjs/signal-exit/issues/21) ([#24](https://github.com/tapjs/signal-exit/issues/24)) ([1248a4c](https://github.com/tapjs/signal-exit/commit/1248a4c)) + + +### BREAKING CHANGES + +* signal-exit no longer wires into SIGPROF diff --git a/node_modules/signal-exit/LICENSE.txt b/node_modules/signal-exit/LICENSE.txt new file mode 100644 index 0000000..eead04a --- /dev/null +++ b/node_modules/signal-exit/LICENSE.txt @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/signal-exit/README.md b/node_modules/signal-exit/README.md new file mode 100644 index 0000000..9f8eb59 --- /dev/null +++ b/node_modules/signal-exit/README.md @@ -0,0 +1,39 @@ +# signal-exit + +[![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) +[![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) +[![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +When you want to fire an event no matter how a process exits: + +* reaching the end of execution. +* explicitly having `process.exit(code)` called. +* having `process.kill(pid, sig)` called. +* receiving a fatal signal from outside the process + +Use `signal-exit`. + +```js +var onExit = require('signal-exit') + +onExit(function (code, signal) { + console.log('process exited!') +}) +``` + +## API + +`var remove = onExit(function (code, signal) {}, options)` + +The return value of the function is a function that will remove the +handler. + +Note that the function *only* fires for signals if the signal would +cause the proces to exit. That is, there are no other listeners, and +it is a fatal signal. + +## Options + +* `alwaysLast`: Run this handler after any other signal or exit + handlers. This causes `process.emit` to be monkeypatched. diff --git a/node_modules/signal-exit/index.js b/node_modules/signal-exit/index.js new file mode 100644 index 0000000..6b6c43a --- /dev/null +++ b/node_modules/signal-exit/index.js @@ -0,0 +1,163 @@ +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +var assert = require('assert') +var signals = require('./signals.js') +var isWin = /^win/i.test(process.platform) + +var EE = require('events') +/* istanbul ignore if */ +if (typeof EE !== 'function') { + EE = EE.EventEmitter +} + +var emitter +if (process.__signal_exit_emitter__) { + emitter = process.__signal_exit_emitter__ +} else { + emitter = process.__signal_exit_emitter__ = new EE() + emitter.count = 0 + emitter.emitted = {} +} + +// Because this emitter is a global, we have to check to see if a +// previous version of this library failed to enable infinite listeners. +// I know what you're about to say. But literally everything about +// signal-exit is a compromise with evil. Get used to it. +if (!emitter.infinite) { + emitter.setMaxListeners(Infinity) + emitter.infinite = true +} + +module.exports = function (cb, opts) { + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') + + if (loaded === false) { + load() + } + + var ev = 'exit' + if (opts && opts.alwaysLast) { + ev = 'afterexit' + } + + var remove = function () { + emitter.removeListener(ev, cb) + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload() + } + } + emitter.on(ev, cb) + + return remove +} + +module.exports.unload = unload +function unload () { + if (!loaded) { + return + } + loaded = false + + signals.forEach(function (sig) { + try { + process.removeListener(sig, sigListeners[sig]) + } catch (er) {} + }) + process.emit = originalProcessEmit + process.reallyExit = originalProcessReallyExit + emitter.count -= 1 +} + +function emit (event, code, signal) { + if (emitter.emitted[event]) { + return + } + emitter.emitted[event] = true + emitter.emit(event, code, signal) +} + +// { : , ... } +var sigListeners = {} +signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process.listeners(sig) + if (listeners.length === emitter.count) { + unload() + emit('exit', null, sig) + /* istanbul ignore next */ + emit('afterexit', null, sig) + /* istanbul ignore next */ + if (isWin && sig === 'SIGHUP') { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + sig = 'SIGINT' + } + process.kill(process.pid, sig) + } + } +}) + +module.exports.signals = function () { + return signals +} + +module.exports.load = load + +var loaded = false + +function load () { + if (loaded) { + return + } + loaded = true + + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1 + + signals = signals.filter(function (sig) { + try { + process.on(sig, sigListeners[sig]) + return true + } catch (er) { + return false + } + }) + + process.emit = processEmit + process.reallyExit = processReallyExit +} + +var originalProcessReallyExit = process.reallyExit +function processReallyExit (code) { + process.exitCode = code || 0 + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + originalProcessReallyExit.call(process, process.exitCode) +} + +var originalProcessEmit = process.emit +function processEmit (ev, arg) { + if (ev === 'exit') { + if (arg !== undefined) { + process.exitCode = arg + } + var ret = originalProcessEmit.apply(this, arguments) + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } +} diff --git a/node_modules/signal-exit/package.json b/node_modules/signal-exit/package.json new file mode 100644 index 0000000..8cc65c6 --- /dev/null +++ b/node_modules/signal-exit/package.json @@ -0,0 +1,69 @@ +{ + "_args": [ + [ + "signal-exit@3.0.3", + "/home/other/discord_bot" + ] + ], + "_from": "signal-exit@3.0.3", + "_id": "signal-exit@3.0.3", + "_inBundle": false, + "_integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", + "_location": "/signal-exit", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "signal-exit@3.0.3", + "name": "signal-exit", + "escapedName": "signal-exit", + "rawSpec": "3.0.3", + "saveSpec": null, + "fetchSpec": "3.0.3" + }, + "_requiredBy": [ + "/write-file-atomic" + ], + "_resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "_spec": "3.0.3", + "_where": "/home/other/discord_bot", + "author": { + "name": "Ben Coe", + "email": "ben@npmjs.com" + }, + "bugs": { + "url": "https://github.com/tapjs/signal-exit/issues" + }, + "description": "when you want to fire an event no matter how a process exits.", + "devDependencies": { + "chai": "^3.5.0", + "coveralls": "^2.11.10", + "nyc": "^8.1.0", + "standard": "^8.1.0", + "standard-version": "^2.3.0", + "tap": "^8.0.1" + }, + "files": [ + "index.js", + "signals.js" + ], + "homepage": "https://github.com/tapjs/signal-exit", + "keywords": [ + "signal", + "exit" + ], + "license": "ISC", + "main": "index.js", + "name": "signal-exit", + "repository": { + "type": "git", + "url": "git+https://github.com/tapjs/signal-exit.git" + }, + "scripts": { + "coverage": "nyc report --reporter=text-lcov | coveralls", + "pretest": "standard", + "release": "standard-version", + "test": "tap --timeout=240 ./test/*.js --cov" + }, + "version": "3.0.3" +} diff --git a/node_modules/signal-exit/signals.js b/node_modules/signal-exit/signals.js new file mode 100644 index 0000000..3bd67a8 --- /dev/null +++ b/node_modules/signal-exit/signals.js @@ -0,0 +1,53 @@ +// This is not the set of all possible signals. +// +// It IS, however, the set of all signals that trigger +// an exit on either Linux or BSD systems. Linux is a +// superset of the signal names supported on BSD, and +// the unknown signals just fail to register, so we can +// catch that easily enough. +// +// Don't bother with SIGKILL. It's uncatchable, which +// means that we can't fire any callbacks anyway. +// +// If a user does happen to register a handler on a non- +// fatal signal like SIGWINCH or something, and then +// exit, it'll end up firing `process.emit('exit')`, so +// the handler will be fired anyway. +// +// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised +// artificially, inherently leave the process in a +// state from which it is not safe to try and enter JS +// listeners. +module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' +] + +if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ) +} + +if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ) +} diff --git a/node_modules/simple-update-notifier/LICENSE b/node_modules/simple-update-notifier/LICENSE new file mode 100644 index 0000000..1e0b0c1 --- /dev/null +++ b/node_modules/simple-update-notifier/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Alex Brazier + +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/simple-update-notifier/README.md b/node_modules/simple-update-notifier/README.md new file mode 100644 index 0000000..ec17794 --- /dev/null +++ b/node_modules/simple-update-notifier/README.md @@ -0,0 +1,82 @@ +# simple-update-notifier [![GitHub stars](https://img.shields.io/github/stars/alexbrazier/simple-update-notifier?label=Star%20Project&style=social)](https://github.com/alexbrazier/simple-update-notifier/stargazers) + +[![CI](https://github.com/alexbrazier/simple-update-notifier/workflows/Build%20and%20Deploy/badge.svg)](https://github.com/alexbrazier/simple-update-notifier/actions) +[![Dependencies](https://img.shields.io/librariesio/release/npm/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier?activeTab=dependencies) +[![npm](https://img.shields.io/npm/v/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier) +[![npm bundle size](https://img.shields.io/bundlephobia/min/simple-update-notifier)](https://bundlephobia.com/result?p=simple-update-notifier) +[![npm downloads](https://img.shields.io/npm/dw/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier) +[![License](https://img.shields.io/npm/l/simple-update-notifier)](./LICENSE) + +Simple update notifier to check for npm updates for cli applications. + +Demo in terminal showing an update is required + +Checks for updates for an npm module and outputs to the command line if there is one available. The result is cached for the specified time so it doesn't check every time the app runs. + +## Install + +```bash +npm install simple-update-notifier +OR +yarn add simple-update-notifier +``` + +## Usage + +```js +import updateNotifier from 'simple-update-notifier'; +import packageJson from './package.json' assert { type: 'json' }; + +updateNotifier({ pkg: packageJson }); +``` + +### Options + +#### pkg + +Type: `object` + +##### name + +_Required_\ +Type: `string` + +##### version + +_Required_\ +Type: `string` + +#### updateCheckInterval + +Type: `number`\ +Default: `1000 * 60 * 60 * 24` _(1 day)_ + +How often to check for updates. + +#### shouldNotifyInNpmScript + +Type: `boolean`\ +Default: `false` + +Allows notification to be shown when running as an npm script. + +#### distTag + +Type: `string`\ +Default: `'latest'` + +Which [dist-tag](https://docs.npmjs.com/adding-dist-tags-to-packages) to use to find the latest version. + +#### alwaysRun + +Type: `boolean`\ +Default: `false` + +When set, `updateCheckInterval` will not be respected and a check for an update will always be performed. + +#### debug + +Type: `boolean`\ +Default: `false` + +When set, logs explaining the decision will be output to `stderr` whenever the module opts to not print an update notification diff --git a/node_modules/simple-update-notifier/build/index.d.ts b/node_modules/simple-update-notifier/build/index.d.ts new file mode 100644 index 0000000..60f53e0 --- /dev/null +++ b/node_modules/simple-update-notifier/build/index.d.ts @@ -0,0 +1,13 @@ +interface IUpdate { + pkg: { + name: string; + version: string; + }; + updateCheckInterval?: number; + shouldNotifyInNpmScript?: boolean; + distTag?: string; + alwaysRun?: boolean; + debug?: boolean; +} +declare const simpleUpdateNotifier: (args: IUpdate) => Promise; +export { simpleUpdateNotifier as default }; diff --git a/node_modules/simple-update-notifier/build/index.js b/node_modules/simple-update-notifier/build/index.js new file mode 100644 index 0000000..3dd2076 --- /dev/null +++ b/node_modules/simple-update-notifier/build/index.js @@ -0,0 +1,217 @@ +'use strict'; + +var process$1 = require('process'); +var semver = require('semver'); +var os = require('os'); +var path = require('path'); +var fs = require('fs'); +var https = require('https'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var process__default = /*#__PURE__*/_interopDefaultLegacy(process$1); +var semver__default = /*#__PURE__*/_interopDefaultLegacy(semver); +var os__default = /*#__PURE__*/_interopDefaultLegacy(os); +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); +var https__default = /*#__PURE__*/_interopDefaultLegacy(https); + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +var packageJson = process__default["default"].env.npm_package_json; +var userAgent = process__default["default"].env.npm_config_user_agent; +var isNpm6 = Boolean(userAgent && userAgent.startsWith('npm')); +var isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json')); +var isNpm = isNpm6 || isNpm7; +var isYarn = Boolean(userAgent && userAgent.startsWith('yarn')); +var isNpmOrYarn = isNpm || isYarn; + +var homeDirectory = os__default["default"].homedir(); +var configDir = process.env.XDG_CONFIG_HOME || + path__default["default"].join(homeDirectory, '.config', 'simple-update-notifier'); +var getConfigFile = function (packageName) { + return path__default["default"].join(configDir, "".concat(packageName.replace('@', '').replace('/', '__'), ".json")); +}; +var createConfigDir = function () { + if (!fs__default["default"].existsSync(configDir)) { + fs__default["default"].mkdirSync(configDir, { recursive: true }); + } +}; +var getLastUpdate = function (packageName) { + var configFile = getConfigFile(packageName); + try { + if (!fs__default["default"].existsSync(configFile)) { + return undefined; + } + var file = JSON.parse(fs__default["default"].readFileSync(configFile, 'utf8')); + return file.lastUpdateCheck; + } + catch (_a) { + return undefined; + } +}; +var saveLastUpdate = function (packageName) { + var configFile = getConfigFile(packageName); + fs__default["default"].writeFileSync(configFile, JSON.stringify({ lastUpdateCheck: new Date().getTime() })); +}; + +var getDistVersion = function (packageName, distTag) { return __awaiter(void 0, void 0, void 0, function () { + var url; + return __generator(this, function (_a) { + url = "https://registry.npmjs.org/-/package/".concat(packageName, "/dist-tags"); + return [2 /*return*/, new Promise(function (resolve, reject) { + https__default["default"] + .get(url, function (res) { + var body = ''; + res.on('data', function (chunk) { return (body += chunk); }); + res.on('end', function () { + try { + var json = JSON.parse(body); + var version = json[distTag]; + if (!version) { + reject(new Error('Error getting version')); + } + resolve(version); + } + catch (_a) { + reject(new Error('Could not parse version response')); + } + }); + }) + .on('error', function (err) { return reject(err); }); + })]; + }); +}); }; + +var hasNewVersion = function (_a) { + var pkg = _a.pkg, _b = _a.updateCheckInterval, updateCheckInterval = _b === void 0 ? 1000 * 60 * 60 * 24 : _b, _c = _a.distTag, distTag = _c === void 0 ? 'latest' : _c, alwaysRun = _a.alwaysRun, debug = _a.debug; + return __awaiter(void 0, void 0, void 0, function () { + var lastUpdateCheck, latestVersion; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + createConfigDir(); + lastUpdateCheck = getLastUpdate(pkg.name); + if (!(alwaysRun || + !lastUpdateCheck || + lastUpdateCheck < new Date().getTime() - updateCheckInterval)) return [3 /*break*/, 2]; + return [4 /*yield*/, getDistVersion(pkg.name, distTag)]; + case 1: + latestVersion = _d.sent(); + saveLastUpdate(pkg.name); + if (semver__default["default"].gt(latestVersion, pkg.version)) { + return [2 /*return*/, latestVersion]; + } + else if (debug) { + console.error("Latest version (".concat(latestVersion, ") not newer than current version (").concat(pkg.version, ")")); + } + return [3 /*break*/, 3]; + case 2: + if (debug) { + console.error("Too recent to check for a new update. simpleUpdateNotifier() interval set to ".concat(updateCheckInterval, "ms but only ").concat(new Date().getTime() - lastUpdateCheck, "ms since last check.")); + } + _d.label = 3; + case 3: return [2 /*return*/, false]; + } + }); + }); +}; + +var borderedText = function (text) { + var lines = text.split('\n'); + var width = Math.max.apply(Math, lines.map(function (l) { return l.length; })); + var res = ["\u250C".concat('─'.repeat(width + 2), "\u2510")]; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + res.push("\u2502 ".concat(line.padEnd(width), " \u2502")); + } + res.push("\u2514".concat('─'.repeat(width + 2), "\u2518")); + return res.join('\n'); +}; + +var simpleUpdateNotifier = function (args) { return __awaiter(void 0, void 0, void 0, function () { + var latestVersion, err_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!args.alwaysRun && + (!process.stdout.isTTY || (isNpmOrYarn && !args.shouldNotifyInNpmScript))) { + if (args.debug) { + console.error('Opting out of running simpleUpdateNotifier()'); + } + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, hasNewVersion(args)]; + case 2: + latestVersion = _a.sent(); + if (latestVersion) { + console.error(borderedText("New version of ".concat(args.pkg.name, " available!\nCurrent Version: ").concat(args.pkg.version, "\nLatest Version: ").concat(latestVersion))); + } + return [3 /*break*/, 4]; + case 3: + err_1 = _a.sent(); + // Catch any network errors or cache writing errors so module doesn't cause a crash + if (args.debug && err_1 instanceof Error) { + console.error('Unexpected error in simpleUpdateNotifier():', err_1); + } + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); +}); }; + +module.exports = simpleUpdateNotifier; diff --git a/node_modules/simple-update-notifier/node_modules/.bin/semver b/node_modules/simple-update-notifier/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/simple-update-notifier/node_modules/semver/CHANGELOG.md b/node_modules/simple-update-notifier/node_modules/semver/CHANGELOG.md new file mode 100644 index 0000000..d366696 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/CHANGELOG.md @@ -0,0 +1,74 @@ +# changes log + +## 6.3.0 + +* Expose the token enum on the exports + +## 6.2.0 + +* Coerce numbers to strings when passed to semver.coerce() +* Add `rtl` option to coerce from right to left + +## 6.1.3 + +* Handle X-ranges properly in includePrerelease mode + +## 6.1.2 + +* Do not throw when testing invalid version strings + +## 6.1.1 + +* Add options support for semver.coerce() +* Handle undefined version passed to Range.test + +## 6.1.0 + +* Add semver.compareBuild function +* Support `*` in semver.intersects + +## 6.0 + +* Fix `intersects` logic. + + This is technically a bug fix, but since it is also a change to behavior + that may require users updating their code, it is marked as a major + version increment. + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/node_modules/simple-update-notifier/node_modules/semver/LICENSE b/node_modules/simple-update-notifier/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/simple-update-notifier/node_modules/semver/README.md b/node_modules/simple-update-notifier/node_modules/semver/README.md new file mode 100644 index 0000000..1546458 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/README.md @@ -0,0 +1,499 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need, if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` diff --git a/node_modules/simple-update-notifier/node_modules/semver/bin/semver.js b/node_modules/simple-update-notifier/node_modules/semver/bin/semver.js new file mode 100755 index 0000000..73fe295 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/bin/semver.js @@ -0,0 +1,173 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +const semver = require('../') + +let reverse = false + +const options = {} + +const main = () => { + if (!argv.length) return help() + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + const options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const success = () => { + const compare = reverse ? 'rcompare' : 'compare' + versions.sort((a, b) => { + return semver[compare](a, b, options) + }).map((v) => { + return semver.clean(v, options) + }).map((v) => { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach((v, i, _) => { console.log(v) }) +} + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/simple-update-notifier/node_modules/semver/classes/comparator.js b/node_modules/simple-update-notifier/node_modules/semver/classes/comparator.js new file mode 100644 index 0000000..3595792 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/classes/comparator.js @@ -0,0 +1,139 @@ +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + constructor (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + const sameSemVer = this.semver.version === comp.semver.version + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<') + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>') + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } +} + +module.exports = Comparator + +const {re, t} = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/simple-update-notifier/node_modules/semver/classes/index.js b/node_modules/simple-update-notifier/node_modules/semver/classes/index.js new file mode 100644 index 0000000..198b84d --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/classes/index.js @@ -0,0 +1,5 @@ +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js') +} diff --git a/node_modules/simple-update-notifier/node_modules/semver/classes/range.js b/node_modules/simple-update-notifier/node_modules/semver/classes/range.js new file mode 100644 index 0000000..90876c3 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/classes/range.js @@ -0,0 +1,448 @@ +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + this.format() + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim() + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + const loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[t.COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + return range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator(comp, this.options)) + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} +module.exports = Range + +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace +} = require('../internal/re') + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' ') + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' ') + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0` + } else { + ret = `>=${M}.${m}.0 <${+M + 1}.0.0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + } <${M}.${m}.${+p + 1}` + } else { + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0${pr}` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0${pr}` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +const hyphenReplace = ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0` + } else { + from = `>=${from}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else { + to = `<=${to}` + } + + return (`${from} ${to}`).trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/simple-update-notifier/node_modules/semver/classes/semver.js b/node_modules/simple-update-notifier/node_modules/semver/classes/semver.js new file mode 100644 index 0000000..73247ad --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/classes/semver.js @@ -0,0 +1,290 @@ +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { re, t } = require('../internal/re') + +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format() + this.raw = this.version + return this + } +} + +module.exports = SemVer diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/clean.js b/node_modules/simple-update-notifier/node_modules/semver/functions/clean.js new file mode 100644 index 0000000..811fe6b --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/clean.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/cmp.js b/node_modules/simple-update-notifier/node_modules/semver/functions/cmp.js new file mode 100644 index 0000000..3b89db7 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/cmp.js @@ -0,0 +1,48 @@ +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/coerce.js b/node_modules/simple-update-notifier/node_modules/semver/functions/coerce.js new file mode 100644 index 0000000..106ca71 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/coerce.js @@ -0,0 +1,51 @@ +const SemVer = require('../classes/semver') +const parse = require('./parse') +const {re, t} = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) +} +module.exports = coerce diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/compare-build.js b/node_modules/simple-update-notifier/node_modules/semver/functions/compare-build.js new file mode 100644 index 0000000..9eb881b --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/compare-build.js @@ -0,0 +1,7 @@ +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/compare-loose.js b/node_modules/simple-update-notifier/node_modules/semver/functions/compare-loose.js new file mode 100644 index 0000000..4881fbe --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/compare.js b/node_modules/simple-update-notifier/node_modules/semver/functions/compare.js new file mode 100644 index 0000000..748b7af --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/compare.js @@ -0,0 +1,5 @@ +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/diff.js b/node_modules/simple-update-notifier/node_modules/semver/functions/diff.js new file mode 100644 index 0000000..1493666 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/diff.js @@ -0,0 +1,25 @@ +const parse = require('./parse') +const eq = require('./eq') + +const diff = (version1, version2) => { + if (eq(version1, version2)) { + return null + } else { + const v1 = parse(version1) + const v2 = parse(version2) + let prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} +module.exports = diff diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/eq.js b/node_modules/simple-update-notifier/node_modules/semver/functions/eq.js new file mode 100644 index 0000000..271fed9 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/eq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/gt.js b/node_modules/simple-update-notifier/node_modules/semver/functions/gt.js new file mode 100644 index 0000000..d9b2156 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/gt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/gte.js b/node_modules/simple-update-notifier/node_modules/semver/functions/gte.js new file mode 100644 index 0000000..5aeaa63 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/gte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/inc.js b/node_modules/simple-update-notifier/node_modules/semver/functions/inc.js new file mode 100644 index 0000000..aa4d83a --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/inc.js @@ -0,0 +1,15 @@ +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options + options = undefined + } + + try { + return new SemVer(version, options).inc(release, identifier).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/lt.js b/node_modules/simple-update-notifier/node_modules/semver/functions/lt.js new file mode 100644 index 0000000..b440ab7 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/lt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/lte.js b/node_modules/simple-update-notifier/node_modules/semver/functions/lte.js new file mode 100644 index 0000000..6dcc956 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/lte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/major.js b/node_modules/simple-update-notifier/node_modules/semver/functions/major.js new file mode 100644 index 0000000..4283165 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/major.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/minor.js b/node_modules/simple-update-notifier/node_modules/semver/functions/minor.js new file mode 100644 index 0000000..57b3455 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/minor.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/neq.js b/node_modules/simple-update-notifier/node_modules/semver/functions/neq.js new file mode 100644 index 0000000..f944c01 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/neq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/parse.js b/node_modules/simple-update-notifier/node_modules/semver/functions/parse.js new file mode 100644 index 0000000..457fee0 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/parse.js @@ -0,0 +1,37 @@ +const {MAX_LENGTH} = require('../internal/constants') +const { re, t } = require('../internal/re') +const SemVer = require('../classes/semver') + +const parse = (version, options) => { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +module.exports = parse diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/patch.js b/node_modules/simple-update-notifier/node_modules/semver/functions/patch.js new file mode 100644 index 0000000..63afca2 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/patch.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/prerelease.js b/node_modules/simple-update-notifier/node_modules/semver/functions/prerelease.js new file mode 100644 index 0000000..06aa132 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/prerelease.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/rcompare.js b/node_modules/simple-update-notifier/node_modules/semver/functions/rcompare.js new file mode 100644 index 0000000..0ac509e --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/rcompare.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/rsort.js b/node_modules/simple-update-notifier/node_modules/semver/functions/rsort.js new file mode 100644 index 0000000..82404c5 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/rsort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/satisfies.js b/node_modules/simple-update-notifier/node_modules/semver/functions/satisfies.js new file mode 100644 index 0000000..50af1c1 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/satisfies.js @@ -0,0 +1,10 @@ +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/sort.js b/node_modules/simple-update-notifier/node_modules/semver/functions/sort.js new file mode 100644 index 0000000..4d10917 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/sort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/simple-update-notifier/node_modules/semver/functions/valid.js b/node_modules/simple-update-notifier/node_modules/semver/functions/valid.js new file mode 100644 index 0000000..f27bae1 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/functions/valid.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/simple-update-notifier/node_modules/semver/index.js b/node_modules/simple-update-notifier/node_modules/semver/index.js new file mode 100644 index 0000000..068f8b4 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/index.js @@ -0,0 +1,64 @@ +const lrCache = {} +const lazyRequire = (path, subkey) => { + const module = lrCache[path] || (lrCache[path] = require(path)) + return subkey ? module[subkey] : module +} + +const lazyExport = (key, path, subkey) => { + Object.defineProperty(exports, key, { + get: () => { + const res = lazyRequire(path, subkey) + Object.defineProperty(exports, key, { + value: res, + enumerable: true, + configurable: true + }) + return res + }, + configurable: true, + enumerable: true + }) +} + +lazyExport('re', './internal/re', 're') +lazyExport('src', './internal/re', 'src') +lazyExport('tokens', './internal/re', 't') +lazyExport('SEMVER_SPEC_VERSION', './internal/constants', 'SEMVER_SPEC_VERSION') +lazyExport('SemVer', './classes/semver') +lazyExport('compareIdentifiers', './internal/identifiers', 'compareIdentifiers') +lazyExport('rcompareIdentifiers', './internal/identifiers', 'rcompareIdentifiers') +lazyExport('parse', './functions/parse') +lazyExport('valid', './functions/valid') +lazyExport('clean', './functions/clean') +lazyExport('inc', './functions/inc') +lazyExport('diff', './functions/diff') +lazyExport('major', './functions/major') +lazyExport('minor', './functions/minor') +lazyExport('patch', './functions/patch') +lazyExport('prerelease', './functions/prerelease') +lazyExport('compare', './functions/compare') +lazyExport('rcompare', './functions/rcompare') +lazyExport('compareLoose', './functions/compare-loose') +lazyExport('compareBuild', './functions/compare-build') +lazyExport('sort', './functions/sort') +lazyExport('rsort', './functions/rsort') +lazyExport('gt', './functions/gt') +lazyExport('lt', './functions/lt') +lazyExport('eq', './functions/eq') +lazyExport('neq', './functions/neq') +lazyExport('gte', './functions/gte') +lazyExport('lte', './functions/lte') +lazyExport('cmp', './functions/cmp') +lazyExport('coerce', './functions/coerce') +lazyExport('Comparator', './classes/comparator') +lazyExport('Range', './classes/range') +lazyExport('satisfies', './functions/satisfies') +lazyExport('toComparators', './ranges/to-comparators') +lazyExport('maxSatisfying', './ranges/max-satisfying') +lazyExport('minSatisfying', './ranges/min-satisfying') +lazyExport('minVersion', './ranges/min-version') +lazyExport('validRange', './ranges/valid') +lazyExport('outside', './ranges/outside') +lazyExport('gtr', './ranges/gtr') +lazyExport('ltr', './ranges/ltr') +lazyExport('intersects', './ranges/intersects') diff --git a/node_modules/simple-update-notifier/node_modules/semver/internal/constants.js b/node_modules/simple-update-notifier/node_modules/semver/internal/constants.js new file mode 100644 index 0000000..49df215 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/internal/constants.js @@ -0,0 +1,17 @@ +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +module.exports = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH +} diff --git a/node_modules/simple-update-notifier/node_modules/semver/internal/debug.js b/node_modules/simple-update-notifier/node_modules/semver/internal/debug.js new file mode 100644 index 0000000..1c00e13 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/internal/debug.js @@ -0,0 +1,9 @@ +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/simple-update-notifier/node_modules/semver/internal/identifiers.js b/node_modules/simple-update-notifier/node_modules/semver/internal/identifiers.js new file mode 100644 index 0000000..ed13094 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/internal/identifiers.js @@ -0,0 +1,23 @@ +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers +} diff --git a/node_modules/simple-update-notifier/node_modules/semver/internal/re.js b/node_modules/simple-update-notifier/node_modules/semver/internal/re.js new file mode 100644 index 0000000..0e8fb52 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/internal/re.js @@ -0,0 +1,179 @@ +const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const createToken = (name, value, isGlobal) => { + const index = R++ + debug(index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') diff --git a/node_modules/simple-update-notifier/node_modules/semver/package.json b/node_modules/simple-update-notifier/node_modules/semver/package.json new file mode 100644 index 0000000..94dcfef --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/package.json @@ -0,0 +1,66 @@ +{ + "_from": "semver@~7.0.0", + "_id": "semver@7.0.0", + "_inBundle": false, + "_integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==", + "_location": "/simple-update-notifier/semver", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "semver@~7.0.0", + "name": "semver", + "escapedName": "semver", + "rawSpec": "~7.0.0", + "saveSpec": null, + "fetchSpec": "~7.0.0" + }, + "_requiredBy": [ + "/simple-update-notifier" + ], + "_resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz", + "_shasum": "5f3ca35761e47e05b206c6daff2cf814f0316b8e", + "_spec": "semver@~7.0.0", + "_where": "/home/other/discord_bot/node_modules/simple-update-notifier", + "bin": { + "semver": "bin/semver.js" + }, + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The semantic version parser used by npm.", + "devDependencies": { + "tap": "^14.10.1" + }, + "files": [ + "bin", + "range.bnf", + "classes", + "functions", + "internal", + "ranges", + "index.js" + ], + "homepage": "https://github.com/npm/node-semver#readme", + "license": "ISC", + "main": "index.js", + "name": "semver", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "scripts": { + "postpublish": "git push origin --follow-tags", + "postversion": "npm publish", + "preversion": "npm test", + "snap": "tap", + "test": "tap" + }, + "tap": { + "check-coverage": true, + "coverage-map": "map.js" + }, + "version": "7.0.0" +} diff --git a/node_modules/simple-update-notifier/node_modules/semver/range.bnf b/node_modules/simple-update-notifier/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/gtr.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/gtr.js new file mode 100644 index 0000000..db7e355 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/gtr.js @@ -0,0 +1,4 @@ +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/intersects.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/intersects.js new file mode 100644 index 0000000..3d1a6f3 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/intersects.js @@ -0,0 +1,7 @@ +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} +module.exports = intersects diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/ltr.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/ltr.js new file mode 100644 index 0000000..528a885 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/ltr.js @@ -0,0 +1,4 @@ +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/max-satisfying.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 0000000..6e3d993 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,25 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/min-satisfying.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 0000000..9b60974 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,24 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/min-version.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/min-version.js new file mode 100644 index 0000000..7118d23 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/min-version.js @@ -0,0 +1,57 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/outside.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/outside.js new file mode 100644 index 0000000..e35ed11 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/outside.js @@ -0,0 +1,80 @@ +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const {ANY} = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/to-comparators.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 0000000..6c8bc7e --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,8 @@ +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/simple-update-notifier/node_modules/semver/ranges/valid.js b/node_modules/simple-update-notifier/node_modules/semver/ranges/valid.js new file mode 100644 index 0000000..365f356 --- /dev/null +++ b/node_modules/simple-update-notifier/node_modules/semver/ranges/valid.js @@ -0,0 +1,11 @@ +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/simple-update-notifier/package.json b/node_modules/simple-update-notifier/package.json new file mode 100644 index 0000000..a4255bc --- /dev/null +++ b/node_modules/simple-update-notifier/package.json @@ -0,0 +1,127 @@ +{ + "_from": "simple-update-notifier@^1.0.7", + "_id": "simple-update-notifier@1.1.0", + "_inBundle": false, + "_integrity": "sha512-VpsrsJSUcJEseSbMHkrsrAVSdvVS5I96Qo1QAQ4FxQ9wXFcB+pjj7FB7/us9+GcgfW4ziHtYMc1J0PLczb55mg==", + "_location": "/simple-update-notifier", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "simple-update-notifier@^1.0.7", + "name": "simple-update-notifier", + "escapedName": "simple-update-notifier", + "rawSpec": "^1.0.7", + "saveSpec": null, + "fetchSpec": "^1.0.7" + }, + "_requiredBy": [ + "/nodemon" + ], + "_resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-1.1.0.tgz", + "_shasum": "67694c121de354af592b347cdba798463ed49c82", + "_spec": "simple-update-notifier@^1.0.7", + "_where": "/home/other/discord_bot/node_modules/nodemon", + "author": { + "name": "alexbrazier" + }, + "bugs": { + "url": "https://github.com/alexbrazier/simple-update-notifier/issues" + }, + "bundleDependencies": false, + "dependencies": { + "semver": "~7.0.0" + }, + "deprecated": false, + "description": "Simple update notifier to check for npm updates for cli applications", + "devDependencies": { + "@babel/preset-env": "^7.19.1", + "@babel/preset-typescript": "^7.17.12", + "@release-it/conventional-changelog": "^5.1.0", + "@types/jest": "^29.0.3", + "@types/node": "^18.7.18", + "@typescript-eslint/eslint-plugin": "^5.37.0", + "@typescript-eslint/parser": "^5.37.0", + "eslint": "^8.23.1", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-prettier": "^4.0.0", + "jest": "^29.0.3", + "prettier": "^2.7.1", + "release-it": "^15.4.2", + "rollup": "^2.79.0", + "rollup-plugin-ts": "^3.0.2", + "typescript": "^4.8.3" + }, + "engines": { + "node": ">=8.10.0" + }, + "eslintConfig": { + "plugins": [ + "@typescript-eslint", + "prettier" + ], + "extends": [ + "prettier", + "eslint:recommended", + "plugin:@typescript-eslint/recommended" + ], + "parser": "@typescript-eslint/parser", + "rules": { + "prettier/prettier": [ + "error", + { + "quoteProps": "consistent", + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "es5", + "useTabs": false + } + ] + } + }, + "files": [ + "build", + "src" + ], + "homepage": "https://github.com/alexbrazier/simple-update-notifier.git", + "license": "MIT", + "main": "build/index.js", + "name": "simple-update-notifier", + "publishConfig": { + "registry": "https://registry.npmjs.org/" + }, + "release-it": { + "git": { + "commitMessage": "chore: release ${version}", + "tagName": "v${version}" + }, + "npm": { + "publish": true + }, + "github": { + "release": true + }, + "plugins": { + "@release-it/conventional-changelog": { + "preset": "angular", + "infile": "CHANGELOG.md" + } + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/alexbrazier/simple-update-notifier.git" + }, + "scripts": { + "build": "rollup -c rollup.config.js", + "eslint": "eslint src/**/*.ts", + "lint": "yarn prettier:check && yarn eslint", + "prepare": "yarn lint && yarn build", + "prettier": "prettier --write src/**/*.ts", + "prettier:check": "prettier --check src/**/*.ts", + "release": "release-it", + "test": "jest src --noStackTrace" + }, + "types": "build/index.d.ts", + "version": "1.1.0" +} diff --git a/node_modules/simple-update-notifier/src/borderedText.ts b/node_modules/simple-update-notifier/src/borderedText.ts new file mode 100644 index 0000000..7145ac2 --- /dev/null +++ b/node_modules/simple-update-notifier/src/borderedText.ts @@ -0,0 +1,12 @@ +const borderedText = (text: string) => { + const lines = text.split('\n'); + const width = Math.max(...lines.map((l) => l.length)); + const res = [`┌${'─'.repeat(width + 2)}┐`]; + for (const line of lines) { + res.push(`│ ${line.padEnd(width)} │`); + } + res.push(`└${'─'.repeat(width + 2)}┘`); + return res.join('\n'); +}; + +export default borderedText; diff --git a/node_modules/simple-update-notifier/src/cache.spec.ts b/node_modules/simple-update-notifier/src/cache.spec.ts new file mode 100644 index 0000000..49e1cb2 --- /dev/null +++ b/node_modules/simple-update-notifier/src/cache.spec.ts @@ -0,0 +1,17 @@ +import { createConfigDir, getLastUpdate, saveLastUpdate } from './cache'; + +createConfigDir(); + +jest.useFakeTimers().setSystemTime(new Date('2022-01-01')); + +const fakeTime = new Date('2022-01-01').getTime(); + +test('can save update then get the update details', () => { + saveLastUpdate('test'); + expect(getLastUpdate('test')).toBe(fakeTime); +}); + +test('prefixed module can save update then get the update details', () => { + saveLastUpdate('@alexbrazier/test'); + expect(getLastUpdate('@alexbrazier/test')).toBe(fakeTime); +}); diff --git a/node_modules/simple-update-notifier/src/cache.ts b/node_modules/simple-update-notifier/src/cache.ts new file mode 100644 index 0000000..e11deba --- /dev/null +++ b/node_modules/simple-update-notifier/src/cache.ts @@ -0,0 +1,44 @@ +import os from 'os'; +import path from 'path'; +import fs from 'fs'; + +const homeDirectory = os.homedir(); +const configDir = + process.env.XDG_CONFIG_HOME || + path.join(homeDirectory, '.config', 'simple-update-notifier'); + +const getConfigFile = (packageName: string) => { + return path.join( + configDir, + `${packageName.replace('@', '').replace('/', '__')}.json` + ); +}; + +export const createConfigDir = () => { + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true }); + } +}; + +export const getLastUpdate = (packageName: string) => { + const configFile = getConfigFile(packageName); + + try { + if (!fs.existsSync(configFile)) { + return undefined; + } + const file = JSON.parse(fs.readFileSync(configFile, 'utf8')); + return file.lastUpdateCheck as number; + } catch { + return undefined; + } +}; + +export const saveLastUpdate = (packageName: string) => { + const configFile = getConfigFile(packageName); + + fs.writeFileSync( + configFile, + JSON.stringify({ lastUpdateCheck: new Date().getTime() }) + ); +}; diff --git a/node_modules/simple-update-notifier/src/getDistVersion.spec.ts b/node_modules/simple-update-notifier/src/getDistVersion.spec.ts new file mode 100644 index 0000000..b78a42e --- /dev/null +++ b/node_modules/simple-update-notifier/src/getDistVersion.spec.ts @@ -0,0 +1,35 @@ +import Stream from 'stream'; +import https from 'https'; +import getDistVersion from './getDistVersion'; + +jest.mock('https', () => ({ + get: jest.fn(), +})); + +test('Valid response returns version', async () => { + const st = new Stream(); + (https.get as jest.Mock).mockImplementation((url, cb) => { + cb(st); + + st.emit('data', '{"latest":"1.0.0"}'); + st.emit('end'); + }); + + const version = await getDistVersion('test', 'latest'); + + expect(version).toEqual('1.0.0'); +}); + +test('Invalid response throws error', async () => { + const st = new Stream(); + (https.get as jest.Mock).mockImplementation((url, cb) => { + cb(st); + + st.emit('data', 'some invalid json'); + st.emit('end'); + }); + + expect(getDistVersion('test', 'latest')).rejects.toThrow( + 'Could not parse version response' + ); +}); diff --git a/node_modules/simple-update-notifier/src/getDistVersion.ts b/node_modules/simple-update-notifier/src/getDistVersion.ts new file mode 100644 index 0000000..d474e1f --- /dev/null +++ b/node_modules/simple-update-notifier/src/getDistVersion.ts @@ -0,0 +1,29 @@ +import https from 'https'; + +const getDistVersion = async (packageName: string, distTag: string) => { + const url = `https://registry.npmjs.org/-/package/${packageName}/dist-tags`; + + return new Promise((resolve, reject) => { + https + .get(url, (res) => { + let body = ''; + + res.on('data', (chunk) => (body += chunk)); + res.on('end', () => { + try { + const json = JSON.parse(body); + const version = json[distTag]; + if (!version) { + reject(new Error('Error getting version')); + } + resolve(version); + } catch { + reject(new Error('Could not parse version response')); + } + }); + }) + .on('error', (err) => reject(err)); + }); +}; + +export default getDistVersion; diff --git a/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts b/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts new file mode 100644 index 0000000..af7ab22 --- /dev/null +++ b/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts @@ -0,0 +1,82 @@ +import hasNewVersion from './hasNewVersion'; +import { getLastUpdate } from './cache'; +import getDistVersion from './getDistVersion'; + +jest.mock('./getDistVersion', () => jest.fn().mockReturnValue('1.0.0')); +jest.mock('./cache', () => ({ + getLastUpdate: jest.fn().mockReturnValue(undefined), + createConfigDir: jest.fn(), + saveLastUpdate: jest.fn(), +})); + +const pkg = { name: 'test', version: '1.0.0' }; + +afterEach(() => jest.clearAllMocks()); + +const defaultArgs = { + pkg, + shouldNotifyInNpmScript: true, + alwaysRun: true, +}; + +test('it should not trigger update for same version', async () => { + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe(false); +}); + +test('it should trigger update for patch version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('1.0.1'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('1.0.1'); +}); + +test('it should trigger update for minor version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('1.1.0'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('1.1.0'); +}); + +test('it should trigger update for major version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('2.0.0'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('2.0.0'); +}); + +test('it should not trigger update if version is lower', async () => { + (getDistVersion as jest.Mock).mockReturnValue('0.0.9'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe(false); +}); + +it('should trigger update check if last update older than config', async () => { + const TWO_WEEKS = new Date().getTime() - 1000 * 60 * 60 * 24 * 14; + (getLastUpdate as jest.Mock).mockReturnValue(TWO_WEEKS); + const newVersion = await hasNewVersion({ + pkg, + shouldNotifyInNpmScript: true, + }); + + expect(newVersion).toBe(false); + expect(getDistVersion).toHaveBeenCalled(); +}); + +it('should not trigger update check if last update is too recent', async () => { + const TWELVE_HOURS = new Date().getTime() - 1000 * 60 * 60 * 12; + (getLastUpdate as jest.Mock).mockReturnValue(TWELVE_HOURS); + const newVersion = await hasNewVersion({ + pkg, + shouldNotifyInNpmScript: true, + }); + + expect(newVersion).toBe(false); + expect(getDistVersion).not.toHaveBeenCalled(); +}); diff --git a/node_modules/simple-update-notifier/src/hasNewVersion.ts b/node_modules/simple-update-notifier/src/hasNewVersion.ts new file mode 100644 index 0000000..31d5069 --- /dev/null +++ b/node_modules/simple-update-notifier/src/hasNewVersion.ts @@ -0,0 +1,40 @@ +import semver from 'semver'; +import { createConfigDir, getLastUpdate, saveLastUpdate } from './cache'; +import getDistVersion from './getDistVersion'; +import { IUpdate } from './types'; + +const hasNewVersion = async ({ + pkg, + updateCheckInterval = 1000 * 60 * 60 * 24, + distTag = 'latest', + alwaysRun, + debug, +}: IUpdate) => { + createConfigDir(); + const lastUpdateCheck = getLastUpdate(pkg.name); + if ( + alwaysRun || + !lastUpdateCheck || + lastUpdateCheck < new Date().getTime() - updateCheckInterval + ) { + const latestVersion = await getDistVersion(pkg.name, distTag); + saveLastUpdate(pkg.name); + if (semver.gt(latestVersion, pkg.version)) { + return latestVersion; + } else if (debug) { + console.error( + `Latest version (${latestVersion}) not newer than current version (${pkg.version})` + ); + } + } else if (debug) { + console.error( + `Too recent to check for a new update. simpleUpdateNotifier() interval set to ${updateCheckInterval}ms but only ${ + new Date().getTime() - lastUpdateCheck + }ms since last check.` + ); + } + + return false; +}; + +export default hasNewVersion; diff --git a/node_modules/simple-update-notifier/src/index.spec.ts b/node_modules/simple-update-notifier/src/index.spec.ts new file mode 100644 index 0000000..98ffb5a --- /dev/null +++ b/node_modules/simple-update-notifier/src/index.spec.ts @@ -0,0 +1,27 @@ +import simpleUpdateNotifier from '.'; +import hasNewVersion from './hasNewVersion'; + +const consoleSpy = jest.spyOn(console, 'error'); + +jest.mock('./hasNewVersion', () => jest.fn().mockResolvedValue('2.0.0')); + +beforeEach(jest.clearAllMocks); + +test('it logs message if update is available', async () => { + await simpleUpdateNotifier({ + pkg: { name: 'test', version: '1.0.0' }, + alwaysRun: true, + }); + + expect(consoleSpy).toHaveBeenCalledTimes(1); +}); + +test('it does not log message if update is not available', async () => { + (hasNewVersion as jest.Mock).mockResolvedValue(false); + await simpleUpdateNotifier({ + pkg: { name: 'test', version: '2.0.0' }, + alwaysRun: true, + }); + + expect(consoleSpy).toHaveBeenCalledTimes(0); +}); diff --git a/node_modules/simple-update-notifier/src/index.ts b/node_modules/simple-update-notifier/src/index.ts new file mode 100644 index 0000000..2b0d2cf --- /dev/null +++ b/node_modules/simple-update-notifier/src/index.ts @@ -0,0 +1,34 @@ +import isNpmOrYarn from './isNpmOrYarn'; +import hasNewVersion from './hasNewVersion'; +import { IUpdate } from './types'; +import borderedText from './borderedText'; + +const simpleUpdateNotifier = async (args: IUpdate) => { + if ( + !args.alwaysRun && + (!process.stdout.isTTY || (isNpmOrYarn && !args.shouldNotifyInNpmScript)) + ) { + if (args.debug) { + console.error('Opting out of running simpleUpdateNotifier()'); + } + return; + } + + try { + const latestVersion = await hasNewVersion(args); + if (latestVersion) { + console.error( + borderedText(`New version of ${args.pkg.name} available! +Current Version: ${args.pkg.version} +Latest Version: ${latestVersion}`) + ); + } + } catch (err) { + // Catch any network errors or cache writing errors so module doesn't cause a crash + if (args.debug && err instanceof Error) { + console.error('Unexpected error in simpleUpdateNotifier():', err); + } + } +}; + +export default simpleUpdateNotifier; diff --git a/node_modules/simple-update-notifier/src/isNpmOrYarn.ts b/node_modules/simple-update-notifier/src/isNpmOrYarn.ts new file mode 100644 index 0000000..ee4c837 --- /dev/null +++ b/node_modules/simple-update-notifier/src/isNpmOrYarn.ts @@ -0,0 +1,12 @@ +import process from 'process'; + +const packageJson = process.env.npm_package_json; +const userAgent = process.env.npm_config_user_agent; +const isNpm6 = Boolean(userAgent && userAgent.startsWith('npm')); +const isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json')); + +const isNpm = isNpm6 || isNpm7; +const isYarn = Boolean(userAgent && userAgent.startsWith('yarn')); +const isNpmOrYarn = isNpm || isYarn; + +export default isNpmOrYarn; diff --git a/node_modules/simple-update-notifier/src/types.ts b/node_modules/simple-update-notifier/src/types.ts new file mode 100644 index 0000000..c395eb0 --- /dev/null +++ b/node_modules/simple-update-notifier/src/types.ts @@ -0,0 +1,8 @@ +export interface IUpdate { + pkg: { name: string; version: string }; + updateCheckInterval?: number; + shouldNotifyInNpmScript?: boolean; + distTag?: string; + alwaysRun?: boolean; + debug?: boolean; +} diff --git a/node_modules/streamsearch/.eslintrc.js b/node_modules/streamsearch/.eslintrc.js new file mode 100644 index 0000000..be9311d --- /dev/null +++ b/node_modules/streamsearch/.eslintrc.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + extends: '@mscdex/eslint-config', +}; diff --git a/node_modules/streamsearch/.github/workflows/ci.yml b/node_modules/streamsearch/.github/workflows/ci.yml new file mode 100644 index 0000000..29d5178 --- /dev/null +++ b/node_modules/streamsearch/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +jobs: + tests-linux: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [10.x, 12.x, 14.x, 16.x] + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install module + run: npm install + - name: Run tests + run: npm test diff --git a/node_modules/streamsearch/.github/workflows/lint.yml b/node_modules/streamsearch/.github/workflows/lint.yml new file mode 100644 index 0000000..9f9e1f5 --- /dev/null +++ b/node_modules/streamsearch/.github/workflows/lint.yml @@ -0,0 +1,23 @@ +name: lint + +on: + pull_request: + push: + branches: [ master ] + +env: + NODE_VERSION: 16.x + +jobs: + lint-js: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ env.NODE_VERSION }} + uses: actions/setup-node@v1 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Install ESLint + ESLint configs/plugins + run: npm install --only=dev + - name: Lint files + run: npm run lint diff --git a/node_modules/streamsearch/LICENSE b/node_modules/streamsearch/LICENSE new file mode 100644 index 0000000..9ea90e0 --- /dev/null +++ b/node_modules/streamsearch/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +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/streamsearch/README.md b/node_modules/streamsearch/README.md new file mode 100644 index 0000000..c3934d1 --- /dev/null +++ b/node_modules/streamsearch/README.md @@ -0,0 +1,95 @@ +Description +=========== + +streamsearch is a module for [node.js](http://nodejs.org/) that allows searching a stream using the Boyer-Moore-Horspool algorithm. + +This module is based heavily on the Streaming Boyer-Moore-Horspool C++ implementation by Hongli Lai [here](https://github.com/FooBarWidget/boyer-moore-horspool). + + +Requirements +============ + +* [node.js](http://nodejs.org/) -- v10.0.0 or newer + + +Installation +============ + + npm install streamsearch + +Example +======= + +```js + const { inspect } = require('util'); + + const StreamSearch = require('streamsearch'); + + const needle = Buffer.from('\r\n'); + const ss = new StreamSearch(needle, (isMatch, data, start, end) => { + if (data) + console.log('data: ' + inspect(data.toString('latin1', start, end))); + if (isMatch) + console.log('match!'); + }); + + const chunks = [ + 'foo', + ' bar', + '\r', + '\n', + 'baz, hello\r', + '\n world.', + '\r\n Node.JS rules!!\r\n\r\n', + ]; + for (const chunk of chunks) + ss.push(Buffer.from(chunk)); + + // output: + // + // data: 'foo' + // data: ' bar' + // match! + // data: 'baz, hello' + // match! + // data: ' world.' + // match! + // data: ' Node.JS rules!!' + // match! + // data: '' + // match! +``` + + +API +=== + +Properties +---------- + +* **maxMatches** - < _integer_ > - The maximum number of matches. Defaults to `Infinity`. + +* **matches** - < _integer_ > - The current match count. + + +Functions +--------- + +* **(constructor)**(< _mixed_ >needle, < _function_ >callback) - Creates and returns a new instance for searching for a _Buffer_ or _string_ `needle`. `callback` is called any time there is non-matching data and/or there is a needle match. `callback` will be called with the following arguments: + + 1. `isMatch` - _boolean_ - Indicates whether a match has been found + + 2. `data` - _mixed_ - If set, this contains data that did not match the needle. + + 3. `start` - _integer_ - The index in `data` where the non-matching data begins (inclusive). + + 4. `end` - _integer_ - The index in `data` where the non-matching data ends (exclusive). + + 5. `isSafeData` - _boolean_ - Indicates if it is safe to store a reference to `data` (e.g. as-is or via `data.slice()`) or not, as in some cases `data` may point to a Buffer whose contents change over time. + +* **destroy**() - _(void)_ - Emits any last remaining unmatched data that may still be buffered and then resets internal state. + +* **push**(< _Buffer_ >chunk) - _integer_ - Processes `chunk`, searching for a match. The return value is the last processed index in `chunk` + 1. + +* **reset**() - _(void)_ - Resets internal state. Useful for when you wish to start searching a new/different stream for example. + diff --git a/node_modules/streamsearch/lib/sbmh.js b/node_modules/streamsearch/lib/sbmh.js new file mode 100644 index 0000000..510cae2 --- /dev/null +++ b/node_modules/streamsearch/lib/sbmh.js @@ -0,0 +1,267 @@ +'use strict'; +/* + Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool +*/ +function memcmp(buf1, pos1, buf2, pos2, num) { + for (let i = 0; i < num; ++i) { + if (buf1[pos1 + i] !== buf2[pos2 + i]) + return false; + } + return true; +} + +class SBMH { + constructor(needle, cb) { + if (typeof cb !== 'function') + throw new Error('Missing match callback'); + + if (typeof needle === 'string') + needle = Buffer.from(needle); + else if (!Buffer.isBuffer(needle)) + throw new Error(`Expected Buffer for needle, got ${typeof needle}`); + + const needleLen = needle.length; + + this.maxMatches = Infinity; + this.matches = 0; + + this._cb = cb; + this._lookbehindSize = 0; + this._needle = needle; + this._bufPos = 0; + + this._lookbehind = Buffer.allocUnsafe(needleLen); + + // Initialize occurrence table. + this._occ = [ + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen + ]; + + // Populate occurrence table with analysis of the needle, ignoring the last + // letter. + if (needleLen > 1) { + for (let i = 0; i < needleLen - 1; ++i) + this._occ[needle[i]] = needleLen - 1 - i; + } + } + + reset() { + this.matches = 0; + this._lookbehindSize = 0; + this._bufPos = 0; + } + + push(chunk, pos) { + let result; + if (!Buffer.isBuffer(chunk)) + chunk = Buffer.from(chunk, 'latin1'); + const chunkLen = chunk.length; + this._bufPos = pos || 0; + while (result !== chunkLen && this.matches < this.maxMatches) + result = feed(this, chunk); + return result; + } + + destroy() { + const lbSize = this._lookbehindSize; + if (lbSize) + this._cb(false, this._lookbehind, 0, lbSize, false); + this.reset(); + } +} + +function feed(self, data) { + const len = data.length; + const needle = self._needle; + const needleLen = needle.length; + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehindSize - 2] + let pos = -self._lookbehindSize; + const lastNeedleCharPos = needleLen - 1; + const lastNeedleChar = needle[lastNeedleCharPos]; + const end = len - needleLen; + const occ = self._occ; + const lookbehind = self._lookbehind; + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= end) { + const nextPos = pos + lastNeedleCharPos; + const ch = (nextPos < 0 + ? lookbehind[self._lookbehindSize + nextPos] + : data[nextPos]); + + if (ch === lastNeedleChar + && matchNeedle(self, data, pos, lastNeedleCharPos)) { + self._lookbehindSize = 0; + ++self.matches; + if (pos > -self._lookbehindSize) + self._cb(true, lookbehind, 0, self._lookbehindSize + pos, false); + else + self._cb(true, undefined, 0, 0, true); + + return (self._bufPos = pos + needleLen); + } + + pos += occ[ch]; + } + + // No match. + + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !matchNeedle(self, data, pos, len - pos)) + ++pos; + + if (pos < 0) { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = self._lookbehindSize + pos; + + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + self._cb(false, lookbehind, 0, bytesToCutOff, false); + } + + self._lookbehindSize -= bytesToCutOff; + lookbehind.copy(lookbehind, 0, bytesToCutOff, self._lookbehindSize); + lookbehind.set(data, self._lookbehindSize); + self._lookbehindSize += len; + + self._bufPos = len; + return len; + } + + // Discard lookbehind buffer. + self._cb(false, lookbehind, 0, self._lookbehindSize, false); + self._lookbehindSize = 0; + } + + pos += self._bufPos; + + const firstNeedleChar = needle[0]; + + // Lookbehind buffer is now empty. Perform Boyer-Moore-Horspool + // search with optimized character lookup code that only considers + // the current round's haystack data. + while (pos <= end) { + const ch = data[pos + lastNeedleCharPos]; + + if (ch === lastNeedleChar + && data[pos] === firstNeedleChar + && memcmp(needle, 0, data, pos, lastNeedleCharPos)) { + ++self.matches; + if (pos > 0) + self._cb(true, data, self._bufPos, pos, true); + else + self._cb(true, undefined, 0, 0, true); + + return (self._bufPos = pos + needleLen); + } + + pos += occ[ch]; + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while (pos < len) { + if (data[pos] !== firstNeedleChar + || !memcmp(data, pos, needle, 0, len - pos)) { + ++pos; + continue; + } + data.copy(lookbehind, 0, pos, len); + self._lookbehindSize = len - pos; + break; + } + + // Everything until `pos` is guaranteed not to contain needle data. + if (pos > 0) + self._cb(false, data, self._bufPos, pos < len ? pos : len, true); + + self._bufPos = len; + return len; +} + +function matchNeedle(self, data, pos, len) { + const lb = self._lookbehind; + const lbSize = self._lookbehindSize; + const needle = self._needle; + + for (let i = 0; i < len; ++i, ++pos) { + const ch = (pos < 0 ? lb[lbSize + pos] : data[pos]); + if (ch !== needle[i]) + return false; + } + return true; +} + +module.exports = SBMH; diff --git a/node_modules/streamsearch/package.json b/node_modules/streamsearch/package.json new file mode 100644 index 0000000..51df8f9 --- /dev/null +++ b/node_modules/streamsearch/package.json @@ -0,0 +1,34 @@ +{ + "name": "streamsearch", + "version": "1.1.0", + "author": "Brian White ", + "description": "Streaming Boyer-Moore-Horspool searching for node.js", + "main": "./lib/sbmh.js", + "engines": { + "node": ">=10.0.0" + }, + "devDependencies": { + "@mscdex/eslint-config": "^1.1.0", + "eslint": "^7.32.0" + }, + "scripts": { + "test": "node test/test.js", + "lint": "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js lib test", + "lint:fix": "npm run lint -- --fix" + }, + "keywords": [ + "stream", + "horspool", + "boyer-moore-horspool", + "boyer-moore", + "search" + ], + "licenses": [{ + "type": "MIT", + "url": "http://github.com/mscdex/streamsearch/raw/master/LICENSE" + }], + "repository": { + "type": "git", + "url": "http://github.com/mscdex/streamsearch.git" + } +} diff --git a/node_modules/streamsearch/test/test.js b/node_modules/streamsearch/test/test.js new file mode 100644 index 0000000..39a04d7 --- /dev/null +++ b/node_modules/streamsearch/test/test.js @@ -0,0 +1,70 @@ +'use strict'; + +const assert = require('assert'); + +const StreamSearch = require('../lib/sbmh.js'); + +[ + { + needle: '\r\n', + chunks: [ + 'foo', + ' bar', + '\r', + '\n', + 'baz, hello\r', + '\n world.', + '\r\n Node.JS rules!!\r\n\r\n', + ], + expect: [ + [false, 'foo'], + [false, ' bar'], + [ true, null], + [false, 'baz, hello'], + [ true, null], + [false, ' world.'], + [ true, null], + [ true, ' Node.JS rules!!'], + [ true, ''], + ], + }, + { + needle: '---foobarbaz', + chunks: [ + '---foobarbaz', + 'asdf', + '\r\n', + '---foobarba', + '---foobar', + 'ba', + '\r\n---foobarbaz--\r\n', + ], + expect: [ + [ true, null], + [false, 'asdf'], + [false, '\r\n'], + [false, '---foobarba'], + [false, '---foobarba'], + [ true, '\r\n'], + [false, '--\r\n'], + ], + }, +].forEach((test, i) => { + console.log(`Running test #${i + 1}`); + const { needle, chunks, expect } = test; + + const results = []; + const ss = new StreamSearch(Buffer.from(needle), + (isMatch, data, start, end) => { + if (data) + data = data.toString('latin1', start, end); + else + data = null; + results.push([isMatch, data]); + }); + + for (const chunk of chunks) + ss.push(Buffer.from(chunk)); + + assert.deepStrictEqual(results, expect); +}); diff --git a/node_modules/string-width/index.d.ts b/node_modules/string-width/index.d.ts new file mode 100644 index 0000000..12b5309 --- /dev/null +++ b/node_modules/string-width/index.d.ts @@ -0,0 +1,29 @@ +declare const stringWidth: { + /** + Get the visual width of a string - the number of columns required to display it. + + Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + + @example + ``` + import stringWidth = require('string-width'); + + stringWidth('a'); + //=> 1 + + stringWidth('古'); + //=> 2 + + stringWidth('\u001B[1m古\u001B[22m'); + //=> 2 + ``` + */ + (string: string): number; + + // TODO: remove this in the next major version, refactor the whole definition to: + // declare function stringWidth(string: string): number; + // export = stringWidth; + default: typeof stringWidth; +} + +export = stringWidth; diff --git a/node_modules/string-width/index.js b/node_modules/string-width/index.js new file mode 100644 index 0000000..f4d261a --- /dev/null +++ b/node_modules/string-width/index.js @@ -0,0 +1,47 @@ +'use strict'; +const stripAnsi = require('strip-ansi'); +const isFullwidthCodePoint = require('is-fullwidth-code-point'); +const emojiRegex = require('emoji-regex'); + +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint(code) ? 2 : 1; + } + + return width; +}; + +module.exports = stringWidth; +// TODO: remove this in the next major version +module.exports.default = stringWidth; diff --git a/node_modules/string-width/license b/node_modules/string-width/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/string-width/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/string-width/package.json b/node_modules/string-width/package.json new file mode 100644 index 0000000..4e4b3b3 --- /dev/null +++ b/node_modules/string-width/package.json @@ -0,0 +1,94 @@ +{ + "_args": [ + [ + "string-width@4.2.2", + "/home/other/discord_bot" + ] + ], + "_from": "string-width@4.2.2", + "_id": "string-width@4.2.2", + "_inBundle": false, + "_integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", + "_location": "/string-width", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "string-width@4.2.2", + "name": "string-width", + "escapedName": "string-width", + "rawSpec": "4.2.2", + "saveSpec": null, + "fetchSpec": "4.2.2" + }, + "_requiredBy": [ + "/boxen", + "/nodemon/boxen", + "/widest-line", + "/wrap-ansi" + ], + "_resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", + "_spec": "4.2.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/string-width/issues" + }, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "description": "Get the visual width of a string - the number of columns required to display it", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/string-width#readme", + "keywords": [ + "string", + "character", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "license": "MIT", + "name": "string-width", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/string-width.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "4.2.2" +} diff --git a/node_modules/string-width/readme.md b/node_modules/string-width/readme.md new file mode 100644 index 0000000..bdd3141 --- /dev/null +++ b/node_modules/string-width/readme.md @@ -0,0 +1,50 @@ +# string-width + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + + +## Install + +``` +$ npm install string-width +``` + + +## Usage + +```js +const stringWidth = require('string-width'); + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` + + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..778edb2 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000..5fd5831 --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000..2e89e63 --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000..b2bb141 --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000..907fccc --- /dev/null +++ b/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,17 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +declare function stripAnsi(string: string): string; + +export = stripAnsi; diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js new file mode 100644 index 0000000..9a593df --- /dev/null +++ b/node_modules/strip-ansi/index.js @@ -0,0 +1,4 @@ +'use strict'; +const ansiRegex = require('ansi-regex'); + +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/strip-ansi/package.json b/node_modules/strip-ansi/package.json new file mode 100644 index 0000000..8baa939 --- /dev/null +++ b/node_modules/strip-ansi/package.json @@ -0,0 +1,90 @@ +{ + "_args": [ + [ + "strip-ansi@6.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "strip-ansi@6.0.0", + "_id": "strip-ansi@6.0.0", + "_inBundle": false, + "_integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "_location": "/strip-ansi", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "strip-ansi@6.0.0", + "name": "strip-ansi", + "escapedName": "strip-ansi", + "rawSpec": "6.0.0", + "saveSpec": null, + "fetchSpec": "6.0.0" + }, + "_requiredBy": [ + "/string-width", + "/wrap-ansi" + ], + "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "_spec": "6.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/chalk/strip-ansi/issues" + }, + "dependencies": { + "ansi-regex": "^5.0.0" + }, + "description": "Strip ANSI escape codes from a string", + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.10.0", + "xo": "^0.25.3" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/chalk/strip-ansi#readme", + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "name": "strip-ansi", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/strip-ansi.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "6.0.0" +} diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000..7c4b56d --- /dev/null +++ b/node_modules/strip-ansi/readme.md @@ -0,0 +1,46 @@ +# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + + +## Install + +``` +$ npm install strip-ansi +``` + + +## Usage + +```js +const stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + + +## strip-ansi for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + diff --git a/node_modules/strip-json-comments/index.js b/node_modules/strip-json-comments/index.js new file mode 100644 index 0000000..4e6576e --- /dev/null +++ b/node_modules/strip-json-comments/index.js @@ -0,0 +1,70 @@ +'use strict'; +var singleComment = 1; +var multiComment = 2; + +function stripWithoutWhitespace() { + return ''; +} + +function stripWithWhitespace(str, start, end) { + return str.slice(start, end).replace(/\S/g, ' '); +} + +module.exports = function (str, opts) { + opts = opts || {}; + + var currentChar; + var nextChar; + var insideString = false; + var insideComment = false; + var offset = 0; + var ret = ''; + var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace; + + for (var i = 0; i < str.length; i++) { + currentChar = str[i]; + nextChar = str[i + 1]; + + if (!insideComment && currentChar === '"') { + var escaped = str[i - 1] === '\\' && str[i - 2] !== '\\'; + if (!escaped) { + insideString = !insideString; + } + } + + if (insideString) { + continue; + } + + if (!insideComment && currentChar + nextChar === '//') { + ret += str.slice(offset, i); + offset = i; + insideComment = singleComment; + i++; + } else if (insideComment === singleComment && currentChar + nextChar === '\r\n') { + i++; + insideComment = false; + ret += strip(str, offset, i); + offset = i; + continue; + } else if (insideComment === singleComment && currentChar === '\n') { + insideComment = false; + ret += strip(str, offset, i); + offset = i; + } else if (!insideComment && currentChar + nextChar === '/*') { + ret += str.slice(offset, i); + offset = i; + insideComment = multiComment; + i++; + continue; + } else if (insideComment === multiComment && currentChar + nextChar === '*/') { + i++; + insideComment = false; + ret += strip(str, offset, i + 1); + offset = i + 1; + continue; + } + } + + return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset)); +}; diff --git a/node_modules/strip-json-comments/license b/node_modules/strip-json-comments/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/strip-json-comments/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/strip-json-comments/package.json b/node_modules/strip-json-comments/package.json new file mode 100644 index 0000000..edf2a27 --- /dev/null +++ b/node_modules/strip-json-comments/package.json @@ -0,0 +1,77 @@ +{ + "_args": [ + [ + "strip-json-comments@2.0.1", + "/home/other/discord_bot" + ] + ], + "_from": "strip-json-comments@2.0.1", + "_id": "strip-json-comments@2.0.1", + "_inBundle": false, + "_integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "_location": "/strip-json-comments", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "strip-json-comments@2.0.1", + "name": "strip-json-comments", + "escapedName": "strip-json-comments", + "rawSpec": "2.0.1", + "saveSpec": null, + "fetchSpec": "2.0.1" + }, + "_requiredBy": [ + "/rc" + ], + "_resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "_spec": "2.0.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/strip-json-comments/issues" + }, + "description": "Strip comments from JSON. Lets you use comments in your JSON files!", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/strip-json-comments#readme", + "keywords": [ + "json", + "strip", + "remove", + "delete", + "trim", + "comments", + "multiline", + "parse", + "config", + "configuration", + "conf", + "settings", + "util", + "env", + "environment" + ], + "license": "MIT", + "name": "strip-json-comments", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/strip-json-comments.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.1" +} diff --git a/node_modules/strip-json-comments/readme.md b/node_modules/strip-json-comments/readme.md new file mode 100644 index 0000000..0ee58df --- /dev/null +++ b/node_modules/strip-json-comments/readme.md @@ -0,0 +1,64 @@ +# strip-json-comments [![Build Status](https://travis-ci.org/sindresorhus/strip-json-comments.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-json-comments) + +> Strip comments from JSON. Lets you use comments in your JSON files! + +This is now possible: + +```js +{ + // rainbows + "unicorn": /* ❤ */ "cake" +} +``` + +It will replace single-line comments `//` and multi-line comments `/**/` with whitespace. This allows JSON error positions to remain as close as possible to the original source. + +Also available as a [gulp](https://github.com/sindresorhus/gulp-strip-json-comments)/[grunt](https://github.com/sindresorhus/grunt-strip-json-comments)/[broccoli](https://github.com/sindresorhus/broccoli-strip-json-comments) plugin. + + +## Install + +``` +$ npm install --save strip-json-comments +``` + + +## Usage + +```js +const json = '{/*rainbows*/"unicorn":"cake"}'; + +JSON.parse(stripJsonComments(json)); +//=> {unicorn: 'cake'} +``` + + +## API + +### stripJsonComments(input, [options]) + +#### input + +Type: `string` + +Accepts a string with JSON and returns a string without comments. + +#### options + +##### whitespace + +Type: `boolean` +Default: `true` + +Replace comments with whitespace instead of stripping them entirely. + + +## Related + +- [strip-json-comments-cli](https://github.com/sindresorhus/strip-json-comments-cli) - CLI for this module +- [strip-css-comments](https://github.com/sindresorhus/strip-css-comments) - Strip comments from CSS + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/strtok3/LICENSE b/node_modules/strtok3/LICENSE new file mode 100644 index 0000000..c85ef2c --- /dev/null +++ b/node_modules/strtok3/LICENSE @@ -0,0 +1,15 @@ +Copyright (c) 2017, Borewit +All rights reserved. + +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/strtok3/README.md b/node_modules/strtok3/README.md new file mode 100644 index 0000000..72dd5fe --- /dev/null +++ b/node_modules/strtok3/README.md @@ -0,0 +1,306 @@ +![Node.js CI](https://github.com/Borewit/strtok3/workflows/Node.js%20CI/badge.svg) +[![NPM version](https://badge.fury.io/js/strtok3.svg)](https://npmjs.org/package/strtok3) +[![npm downloads](http://img.shields.io/npm/dm/strtok3.svg)](https://npmcharts.com/compare/strtok3,token-types?start=1200&interval=30) +[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/8526/branches/103329/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=8526&bid=103329) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/strtok3/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/strtok3?targetFile=package.json) +[![Total alerts](https://img.shields.io/lgtm/alerts/g/Borewit/strtok3.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/strtok3/alerts/) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/59dd6795e61949fb97066ca52e6097ef)](https://www.codacy.com/app/Borewit/strtok3?utm_source=github.com&utm_medium=referral&utm_content=Borewit/strtok3&utm_campaign=Badge_Grade) +[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Borewit/strtok3.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/strtok3/context:javascript) +# strtok3 + +A promise based streaming [*tokenizer*](#tokenizer) for [Node.js](http://nodejs.org) and browsers. +This node module is a successor of [strtok2](https://github.com/Borewit/strtok2). + +The `strtok3` contains a few methods to turn different input into a [*tokenizer*](#tokenizer). Designed to +* Support a streaming environment +* Decoding of binary data, strings and numbers in mind +* Read [predefined](https://github.com/Borewit/token-types) or custom tokens. +* Optimized [*tokenizers*](#tokenizer) for reading from [file](#method-strtok3fromfile), [stream](#method-strtok3fromstream) or [buffer](#method-strtok3frombuffer). + +It can read from: +* A file (taking a file path as an input) +* A Node.js [stream](https://nodejs.org/api/stream.html). +* A [Buffer](https://nodejs.org/api/buffer.html) or [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) +* HTTP chunked transfer provided by [@tokenizer/http](https://github.com/Borewit/tokenizer-http). +* Chunked [Amazon S3](https://aws.amazon.com/s3) access provided by [@tokenizer/s3](https://github.com/Borewit/tokenizer-s3). + +## Installation + +```sh +npm install strtok3 +``` + +### Compatibility + +Module: version 7 migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). +JavaScript is compliant with [ECMAScript 2019 (ES10)](https://en.wikipedia.org/wiki/ECMAScript#10th_Edition_%E2%80%93_ECMAScript_2019). +Requires Node.js ≥ 14.16 engine. + +## API + +Use one of the methods to instantiate an [*abstract tokenizer*](#tokenizer): +* [strtok3.fromFile](#method-strtok3fromfile) +* [strtok3.fromStream](#method-strtok3fromstream) +* [strtok3.fromBuffer](#method-strtok3fromBuffer) +* [strtok3.fromUint8Array](#method-strtok3fromUint8Array) + +### strtok3 methods + +All of the strtok3 methods return a [*tokenizer*](#tokenizer), either directly or via a promise. + +#### Method `strtok3.fromFile()` + +| Parameter | Type | Description | +|-----------|-----------------------|----------------------------| +| path | Path to file (string) | Path to file to read from | + +> __Note__: that [file-information](#file-information) is automatically added. + +Returns, via a promise, a [*tokenizer*](#tokenizer) which can be used to parse a file. + +```js +import * as strtok3 from 'strtok3'; +import * as Token from 'token-types'; + +(async () => { + + const tokenizer = await strtok3.fromFile("somefile.bin"); + try { + const myNumber = await tokenizer.readToken(Token.UINT8); + console.log(`My number: ${myNumber}`); + } finally { + tokenizer.close(); // Close the file + } +})(); + +``` + +#### Method `strtok3.fromStream()` + +Create [*tokenizer*](#tokenizer) from a node.js [readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +| Parameter | Optional | Type | Description | +|-----------|-----------|-----------------------------------------------------------------------------|--------------------------| +| stream | no | [Readable](https://nodejs.org/api/stream.html#stream_class_stream_readable) | Stream to read from | +| fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information | + +Returns a [*tokenizer*](#tokenizer), via a Promise, which can be used to parse a buffer. + +```js +import strtok3 from 'strtok3'; +import * as Token from 'token-types'; + +strtok3.fromStream(stream).then(tokenizer => { + return tokenizer.readToken(Token.UINT8).then(myUint8Number => { + console.log(`My number: ${myUint8Number}`); + }); +}); +``` + +#### Method `strtok3.fromBuffer()` + +| Parameter | Optional | Type | Description | +|------------|----------|--------------------------------------------------|----------------------------------------| +| uint8Array | no | [Uint8Array](https://nodejs.org/api/buffer.html) | Uint8Array or Buffer to read from | +| fileInfo | yes | [IFileInfo](#IFileInfo) | Provide file information | + +Returns a [*tokenizer*](#tokenizer) which can be used to parse the provided buffer. + +```js +import * as strtok3 from 'strtok3'; + +const tokenizer = strtok3.fromBuffer(buffer); + +tokenizer.readToken(Token.UINT8).then(myUint8Number => { + console.log(`My number: ${myUint8Number}`); +}); +``` + +## Tokenizer +The tokenizer allows us to *read* or *peek* from the *tokenizer-stream*. The *tokenizer-stream* is an abstraction of a [stream](https://nodejs.org/api/stream.html), file or [Buffer](https://nodejs.org/api/buffer.html). +It can also be translated in chunked reads, as done in [@tokenizer/http](https://github.com/Borewit/tokenizer-http); + +What is the difference with Nodejs.js stream? +* The *tokenizer-stream* supports jumping / seeking in a the *tokenizer-stream* using [`tokenizer.ignore()`](#method-tokenizerignore) +* In addition to *read* methods, it has *peek* methods, to read a ahead and check what is coming. + +The [tokenizer.position](#attribute-tokenizerposition) keeps tracks of the read position. + +### strtok3 attributes + +#### Attribute `tokenizer.fileInfo` +Optional attribute describing the file information, see [IFileInfo](#IFileInfo) + +#### Attribute `tokenizer.position` +Pointer to the current position in the [*tokenizer*](#tokenizer) stream. +If a *position* is provided to a *read* or *peek* method, is should be, at least, equal or greater than this value. + +### Tokenizer methods + +There are two kind of methods: +1. *read* methods: used to read a *token* of [Buffer](https://nodejs.org/api/buffer.html) from the [*tokenizer*](#tokenizer). The position of the *tokenizer-stream* will advance with the size of the token. +2. *peek* methods: same as the read, but it will *not* advance the pointer. It allows to read (peek) ahead. + +#### Method `tokenizer.readBuffer()` + +Read buffer from stream. +`readBuffer(buffer, options?)` + +| Parameter | Type | Description | +|------------|----------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| buffer | [Buffer](https://nodejs.org/api/buffer.html) | Uint8Array | Target buffer to write the data read to | +| options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read | + +Return value `Promise` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set. + +#### Method `tokenizer.peekBuffer()` + +Peek (read ahead) buffer from [*tokenizer*](#tokenizer) +`peekBuffer(buffer, options?)` + +| Parameter | Type | Description | +|------------|-----------------------------------------|-----------------------------------------------------| +| buffer | Buffer | Uint8Array | Target buffer to write the data read (peeked) to. | +| options | [IReadChunkOptions](#ireadchunkoptions) | An integer specifying the number of bytes to read. | | + +Return value `Promise` Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set. + +#### Method `tokenizer.readToken()` + +Read a *token* from the tokenizer-stream. +`readToken(token, position?)` + +| Parameter | Type | Description | +|------------|-------------------------|---------------------------------------------------------------------------------------------------------------------- | +| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. | +| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. | + +Return value `Promise`. Promise with number of bytes read. The number of bytes read maybe if less, *mayBeLess* flag was set. + +#### Method `tokenizer.peekToken()` + +Peek a *token* from the [*tokenizer*](#tokenizer). +`peekToken(token, position?)` + +| Parameter | Type | Description | +|------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------| +| token | [IGetToken](#IGetToken) | Token to read from the tokenizer-stream. | +| position? | number | Offset where to begin reading within the file. If position is null, data will be read from the current file position. | + +Return value `Promise` Promise with token value peeked from the [*tokenizer*](#tokenizer). + +#### Method `tokenizer.readNumber()` + +Peek a numeric [*token*](#token) from the [*tokenizer*](#tokenizer). +`readNumber(token)` + +| Parameter | Type | Description | +|------------|---------------------------------|----------------------------------------------------| +| token | [IGetToken](#IGetToken) | Numeric token to read from the tokenizer-stream. | + +Return value `Promise` Promise with number peeked from the *tokenizer-stream*. + +#### Method `tokenizer.ignore()` + +Advanse the offset pointer with the number of bytes provided. +`ignore(length)` + +| Parameter | Type | Description | +|------------|--------|----------------------------------------------------------------------| +| ignore | number | Numeric of bytes to ignore. Will advance the `tokenizer.position` | + +Return value `Promise` Promise with number peeked from the *tokenizer-stream*. + +#### Method `tokenizer.close()` +Clean up resources, such as closing a file pointer if applicable. + +### IReadChunkOptions + +Each attribute is optional: + +| Attribute | Type | Description | +|-----------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| offset | number | The offset in the buffer to start writing at; if not provided, start at 0 | +| length | number | Requested number of bytes to read. | +| position | number | Position where to peek from the file. If position is null, data will be read from the [current file position](#attribute-tokenizerposition). Position may not be less then [tokenizer.position](#attribute-tokenizerposition) | +| mayBeLess | boolean | If and only if set, will not throw an EOF error if less then the requested *mayBeLess* could be read. | + +Example: +```js + tokenizer.peekBuffer(buffer, {mayBeLess: true}); +``` + +## IFileInfo + +File information interface which describes the underlying file, each attribute is optional. + +| Attribute | Type | Description | +|-----------|---------|---------------------------------------------------------------------------------------------------| +| size | number | File size in bytes | +| mimeType | number | [MIME-type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of file. | +| path | number | File path | +| url | boolean | File URL | + +## Token + +The *token* is basically a description what to read form the [*tokenizer-stream*](#tokenizer). +A basic set of *token types* can be found here: [*token-types*](https://github.com/Borewit/token-types). + +A token is something which implements the following interface: +```ts +export interface IGetToken { + + /** + * Length in bytes of encoded value + */ + len: number; + + /** + * Decode value from buffer at offset + * @param buf Buffer to read the decoded value from + * @param off Decode offset + */ + get(buf: Buffer, off: number): T; +} +``` +The *tokenizer* reads `token.len` bytes from the *tokenizer-stream* into a Buffer. +The `token.get` will be called with the Buffer. `token.get` is responsible for conversion from the buffer to the desired output type. + +## Browser compatibility +To exclude fs based dependencies, you can use a submodule-import from 'strtok3/lib/core'. + +| function | 'strtok3' | 'strtok3/lib/core' | +| ----------------------| --------------------|---------------------| +| `parseBuffer` | ✓ | ✓ | +| `parseStream` | ✓ | ✓ | +| `fromFile` | ✓ | | + +### Working with Web-API readable stream +To convert a [Web-API readable stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader) into a [Node.js readable stream]((https://nodejs.org/api/stream.html#stream_readable_streams)), you can use [readable-web-to-node-stream](https://github.com/Borewit/readable-web-to-node-stream) to convert one in another. + +Example submodule-import: +```js +import * as strtok3core from 'strtok3/core'; // Submodule-import to prevent Node.js specific dependencies +import { ReadableWebToNodeStream } from 'readable-web-to-node-stream'; + +(async () => { + + const response = await fetch(url); + const readableWebStream = response.body; // Web-API readable stream + const nodeStream = new ReadableWebToNodeStream(readableWebStream); // convert to Node.js readable stream + + const tokenizer = strtok3core.fromStream(nodeStream); // And we now have tokenizer in a web environment +})(); +``` + +## Licence + +(The MIT License) + +Copyright (c) 2020 Borewit + +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/strtok3/lib/AbstractTokenizer.d.ts b/node_modules/strtok3/lib/AbstractTokenizer.d.ts new file mode 100644 index 0000000..d15b635 --- /dev/null +++ b/node_modules/strtok3/lib/AbstractTokenizer.d.ts @@ -0,0 +1,69 @@ +import { ITokenizer, IFileInfo, IReadChunkOptions } from './types.js'; +import { IGetToken, IToken } from '@tokenizer/token'; +interface INormalizedReadChunkOptions extends IReadChunkOptions { + offset: number; + length: number; + position: number; + mayBeLess?: boolean; +} +/** + * Core tokenizer + */ +export declare abstract class AbstractTokenizer implements ITokenizer { + fileInfo: IFileInfo; + protected constructor(fileInfo?: IFileInfo); + /** + * Tokenizer-stream position + */ + position: number; + private numBuffer; + /** + * Read buffer from tokenizer + * @param buffer - Target buffer to fill with data read from the tokenizer-stream + * @param options - Additional read options + * @returns Promise with number of bytes read + */ + abstract readBuffer(buffer: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array- Target buffer to fill with data peek from the tokenizer-stream + * @param options - Peek behaviour options + * @returns Promise with number of bytes read + */ + abstract peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + readToken(token: IGetToken, position?: number): Promise; + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + peekToken(token: IGetToken, position?: number): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + readNumber(token: IToken): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + peekNumber(token: IToken): Promise; + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + ignore(length: number): Promise; + close(): Promise; + protected normalizeOptions(uint8Array: Uint8Array, options?: IReadChunkOptions): INormalizedReadChunkOptions; +} +export {}; diff --git a/node_modules/strtok3/lib/AbstractTokenizer.js b/node_modules/strtok3/lib/AbstractTokenizer.js new file mode 100644 index 0000000..e266ef1 --- /dev/null +++ b/node_modules/strtok3/lib/AbstractTokenizer.js @@ -0,0 +1,101 @@ +import { EndOfStreamError } from 'peek-readable'; +import { Buffer } from 'node:buffer'; +/** + * Core tokenizer + */ +export class AbstractTokenizer { + constructor(fileInfo) { + /** + * Tokenizer-stream position + */ + this.position = 0; + this.numBuffer = new Uint8Array(8); + this.fileInfo = fileInfo ? fileInfo : {}; + } + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + async readToken(token, position = this.position) { + const uint8Array = Buffer.alloc(token.len); + const len = await this.readBuffer(uint8Array, { position }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + async peekToken(token, position = this.position) { + const uint8Array = Buffer.alloc(token.len); + const len = await this.peekBuffer(uint8Array, { position }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async readNumber(token) { + const len = await this.readBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async peekNumber(token) { + const len = await this.peekBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + async ignore(length) { + if (this.fileInfo.size !== undefined) { + const bytesLeft = this.fileInfo.size - this.position; + if (length > bytesLeft) { + this.position += bytesLeft; + return bytesLeft; + } + } + this.position += length; + return length; + } + async close() { + // empty + } + normalizeOptions(uint8Array, options) { + if (options && options.position !== undefined && options.position < this.position) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + if (options) { + return { + mayBeLess: options.mayBeLess === true, + offset: options.offset ? options.offset : 0, + length: options.length ? options.length : (uint8Array.length - (options.offset ? options.offset : 0)), + position: options.position ? options.position : this.position + }; + } + return { + mayBeLess: false, + offset: 0, + length: uint8Array.length, + position: this.position + }; + } +} diff --git a/node_modules/strtok3/lib/BufferTokenizer.d.ts b/node_modules/strtok3/lib/BufferTokenizer.d.ts new file mode 100644 index 0000000..d2ff0da --- /dev/null +++ b/node_modules/strtok3/lib/BufferTokenizer.d.ts @@ -0,0 +1,26 @@ +import { IFileInfo, IReadChunkOptions } from './types.js'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export declare class BufferTokenizer extends AbstractTokenizer { + private uint8Array; + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param fileInfo - Pass additional file information to the tokenizer + */ + constructor(uint8Array: Uint8Array, fileInfo?: IFileInfo); + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; +} diff --git a/node_modules/strtok3/lib/BufferTokenizer.js b/node_modules/strtok3/lib/BufferTokenizer.js new file mode 100644 index 0000000..3623df1 --- /dev/null +++ b/node_modules/strtok3/lib/BufferTokenizer.js @@ -0,0 +1,51 @@ +import { EndOfStreamError } from 'peek-readable'; +import { AbstractTokenizer } from './AbstractTokenizer.js'; +export class BufferTokenizer extends AbstractTokenizer { + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param fileInfo - Pass additional file information to the tokenizer + */ + constructor(uint8Array, fileInfo) { + super(fileInfo); + this.uint8Array = uint8Array; + this.fileInfo.size = this.fileInfo.size ? this.fileInfo.size : uint8Array.length; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + async readBuffer(uint8Array, options) { + if (options && options.position) { + if (options.position < this.position) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + this.position = options.position; + } + const bytesRead = await this.peekBuffer(uint8Array, options); + this.position += bytesRead; + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length); + if ((!normOptions.mayBeLess) && bytes2read < normOptions.length) { + throw new EndOfStreamError(); + } + else { + uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read), normOptions.offset); + return bytes2read; + } + } + async close() { + // empty + } +} diff --git a/node_modules/strtok3/lib/FileTokenizer.d.ts b/node_modules/strtok3/lib/FileTokenizer.d.ts new file mode 100644 index 0000000..af38163 --- /dev/null +++ b/node_modules/strtok3/lib/FileTokenizer.d.ts @@ -0,0 +1,22 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { IFileInfo, IReadChunkOptions } from './types.js'; +export declare class FileTokenizer extends AbstractTokenizer { + private fd; + constructor(fd: number, fileInfo: IFileInfo); + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + close(): Promise; +} +export declare function fromFile(sourceFilePath: string): Promise; diff --git a/node_modules/strtok3/lib/FileTokenizer.js b/node_modules/strtok3/lib/FileTokenizer.js new file mode 100644 index 0000000..f8c252e --- /dev/null +++ b/node_modules/strtok3/lib/FileTokenizer.js @@ -0,0 +1,50 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { EndOfStreamError } from 'peek-readable'; +import * as fs from './FsPromise.js'; +export class FileTokenizer extends AbstractTokenizer { + constructor(fd, fileInfo) { + super(fileInfo); + this.fd = fd; + } + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + this.position = normOptions.position; + const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position); + this.position += res.bytesRead; + if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) { + throw new EndOfStreamError(); + } + return res.bytesRead; + } + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position); + if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + return res.bytesRead; + } + async close() { + return fs.close(this.fd); + } +} +export async function fromFile(sourceFilePath) { + const stat = await fs.stat(sourceFilePath); + if (!stat.isFile) { + throw new Error(`File not a file: ${sourceFilePath}`); + } + const fd = await fs.open(sourceFilePath, 'r'); + return new FileTokenizer(fd, { path: sourceFilePath, size: stat.size }); +} diff --git a/node_modules/strtok3/lib/FsPromise.d.ts b/node_modules/strtok3/lib/FsPromise.d.ts new file mode 100644 index 0000000..4f711fb --- /dev/null +++ b/node_modules/strtok3/lib/FsPromise.d.ts @@ -0,0 +1,19 @@ +/** + * Module convert fs functions to promise based functions + */ +/// +/// +import fs from 'node:fs'; +export interface IReadResult { + bytesRead: number; + buffer: Uint8Array; +} +export declare const pathExists: typeof fs.existsSync; +export declare const createReadStream: typeof fs.createReadStream; +export declare function stat(path: fs.PathLike): Promise; +export declare function close(fd: number): Promise; +export declare function open(path: fs.PathLike, mode: fs.Mode): Promise; +export declare function read(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): Promise; +export declare function writeFile(path: fs.PathLike, data: Buffer | string): Promise; +export declare function writeFileSync(path: fs.PathLike, data: Buffer | string): void; +export declare function readFile(path: fs.PathLike): Promise; diff --git a/node_modules/strtok3/lib/FsPromise.js b/node_modules/strtok3/lib/FsPromise.js new file mode 100644 index 0000000..4cc61d3 --- /dev/null +++ b/node_modules/strtok3/lib/FsPromise.js @@ -0,0 +1,69 @@ +/** + * Module convert fs functions to promise based functions + */ +import fs from 'node:fs'; +export const pathExists = fs.existsSync; +export const createReadStream = fs.createReadStream; +export async function stat(path) { + return new Promise((resolve, reject) => { + fs.stat(path, (err, stats) => { + if (err) + reject(err); + else + resolve(stats); + }); + }); +} +export async function close(fd) { + return new Promise((resolve, reject) => { + fs.close(fd, err => { + if (err) + reject(err); + else + resolve(); + }); + }); +} +export async function open(path, mode) { + return new Promise((resolve, reject) => { + fs.open(path, mode, (err, fd) => { + if (err) + reject(err); + else + resolve(fd); + }); + }); +} +export async function read(fd, buffer, offset, length, position) { + return new Promise((resolve, reject) => { + fs.read(fd, buffer, offset, length, position, (err, bytesRead, _buffer) => { + if (err) + reject(err); + else + resolve({ bytesRead, buffer: _buffer }); + }); + }); +} +export async function writeFile(path, data) { + return new Promise((resolve, reject) => { + fs.writeFile(path, data, err => { + if (err) + reject(err); + else + resolve(); + }); + }); +} +export function writeFileSync(path, data) { + fs.writeFileSync(path, data); +} +export async function readFile(path) { + return new Promise((resolve, reject) => { + fs.readFile(path, (err, buffer) => { + if (err) + reject(err); + else + resolve(buffer); + }); + }); +} diff --git a/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts b/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts new file mode 100644 index 0000000..0dfa4b4 --- /dev/null +++ b/node_modules/strtok3/lib/ReadStreamTokenizer.d.ts @@ -0,0 +1,28 @@ +/// +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { Readable } from 'node:stream'; +import { IFileInfo, IReadChunkOptions } from './types.js'; +export declare class ReadStreamTokenizer extends AbstractTokenizer { + private streamReader; + constructor(stream: Readable, fileInfo?: IFileInfo); + /** + * Get file information, an HTTP-client may implement this doing a HEAD request + * @return Promise with file information + */ + getFileInfo(): Promise; + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + readBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + peekBuffer(uint8Array: Uint8Array, options?: IReadChunkOptions): Promise; + ignore(length: number): Promise; +} diff --git a/node_modules/strtok3/lib/ReadStreamTokenizer.js b/node_modules/strtok3/lib/ReadStreamTokenizer.js new file mode 100644 index 0000000..b454cfc --- /dev/null +++ b/node_modules/strtok3/lib/ReadStreamTokenizer.js @@ -0,0 +1,94 @@ +import { AbstractTokenizer } from './AbstractTokenizer.js'; +import { EndOfStreamError, StreamReader } from 'peek-readable'; +const maxBufferSize = 256000; +export class ReadStreamTokenizer extends AbstractTokenizer { + constructor(stream, fileInfo) { + super(fileInfo); + this.streamReader = new StreamReader(stream); + } + /** + * Get file information, an HTTP-client may implement this doing a HEAD request + * @return Promise with file information + */ + async getFileInfo() { + return this.fileInfo; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + await this.ignore(skipBytes); + return this.readBuffer(uint8Array, options); + } + else if (skipBytes < 0) { + throw new Error('`options.position` must be equal or greater than `tokenizer.position`'); + } + if (normOptions.length === 0) { + return 0; + } + const bytesRead = await this.streamReader.read(uint8Array, normOptions.offset, normOptions.length); + this.position += bytesRead; + if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + let bytesRead = 0; + if (normOptions.position) { + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + const skipBuffer = new Uint8Array(normOptions.length + skipBytes); + bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess }); + uint8Array.set(skipBuffer.subarray(skipBytes), normOptions.offset); + return bytesRead - skipBytes; + } + else if (skipBytes < 0) { + throw new Error('Cannot peek from a negative offset in a stream'); + } + } + if (normOptions.length > 0) { + try { + bytesRead = await this.streamReader.peek(uint8Array, normOptions.offset, normOptions.length); + } + catch (err) { + if (options && options.mayBeLess && err instanceof EndOfStreamError) { + return 0; + } + throw err; + } + if ((!normOptions.mayBeLess) && bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + } + return bytesRead; + } + async ignore(length) { + // debug(`ignore ${this.position}...${this.position + length - 1}`); + const bufSize = Math.min(maxBufferSize, length); + const buf = new Uint8Array(bufSize); + let totBytesRead = 0; + while (totBytesRead < length) { + const remaining = length - totBytesRead; + const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) }); + if (bytesRead < 0) { + return bytesRead; + } + totBytesRead += bytesRead; + } + return totBytesRead; + } +} diff --git a/node_modules/strtok3/lib/core.d.ts b/node_modules/strtok3/lib/core.d.ts new file mode 100644 index 0000000..cfddd23 --- /dev/null +++ b/node_modules/strtok3/lib/core.d.ts @@ -0,0 +1,23 @@ +/// +import { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import { Readable } from 'node:stream'; +import { BufferTokenizer } from './BufferTokenizer.js'; +import { IFileInfo } from './types.js'; +export { EndOfStreamError } from 'peek-readable'; +export { ITokenizer, IFileInfo } from './types.js'; +export { IToken, IGetToken } from '@tokenizer/token'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property/ + * @param stream - Read from Node.js Stream.Readable + * @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream. + * @returns ReadStreamTokenizer + */ +export declare function fromStream(stream: Readable, fileInfo?: IFileInfo): ReadStreamTokenizer; +/** + * Construct ReadStreamTokenizer from given Buffer. + * @param uint8Array - Uint8Array to tokenize + * @param fileInfo - Pass additional file information to the tokenizer + * @returns BufferTokenizer + */ +export declare function fromBuffer(uint8Array: Uint8Array, fileInfo?: IFileInfo): BufferTokenizer; diff --git a/node_modules/strtok3/lib/core.js b/node_modules/strtok3/lib/core.js new file mode 100644 index 0000000..3737f51 --- /dev/null +++ b/node_modules/strtok3/lib/core.js @@ -0,0 +1,23 @@ +import { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import { BufferTokenizer } from './BufferTokenizer.js'; +export { EndOfStreamError } from 'peek-readable'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property/ + * @param stream - Read from Node.js Stream.Readable + * @param fileInfo - Pass the file information, like size and MIME-type of the corresponding stream. + * @returns ReadStreamTokenizer + */ +export function fromStream(stream, fileInfo) { + fileInfo = fileInfo ? fileInfo : {}; + return new ReadStreamTokenizer(stream, fileInfo); +} +/** + * Construct ReadStreamTokenizer from given Buffer. + * @param uint8Array - Uint8Array to tokenize + * @param fileInfo - Pass additional file information to the tokenizer + * @returns BufferTokenizer + */ +export function fromBuffer(uint8Array, fileInfo) { + return new BufferTokenizer(uint8Array, fileInfo); +} diff --git a/node_modules/strtok3/lib/index.d.ts b/node_modules/strtok3/lib/index.d.ts new file mode 100644 index 0000000..ce119a5 --- /dev/null +++ b/node_modules/strtok3/lib/index.d.ts @@ -0,0 +1,15 @@ +/// +import { Readable } from 'node:stream'; +import { ReadStreamTokenizer } from './ReadStreamTokenizer.js'; +import * as core from './core.js'; +export { fromFile } from './FileTokenizer.js'; +export { ITokenizer, EndOfStreamError, fromBuffer, IFileInfo } from './core.js'; +export { IToken, IGetToken } from '@tokenizer/token'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property. + * @param stream - Node.js Stream.Readable + * @param fileInfo - Pass additional file information to the tokenizer + * @returns Tokenizer + */ +export declare function fromStream(stream: Readable, fileInfo?: core.IFileInfo): Promise; diff --git a/node_modules/strtok3/lib/index.js b/node_modules/strtok3/lib/index.js new file mode 100644 index 0000000..c62c50e --- /dev/null +++ b/node_modules/strtok3/lib/index.js @@ -0,0 +1,20 @@ +import * as fs from './FsPromise.js'; +import * as core from './core.js'; +export { fromFile } from './FileTokenizer.js'; +export { EndOfStreamError, fromBuffer } from './core.js'; +/** + * Construct ReadStreamTokenizer from given Stream. + * Will set fileSize, if provided given Stream has set the .path property. + * @param stream - Node.js Stream.Readable + * @param fileInfo - Pass additional file information to the tokenizer + * @returns Tokenizer + */ +export async function fromStream(stream, fileInfo) { + fileInfo = fileInfo ? fileInfo : {}; + if (stream.path) { + const stat = await fs.stat(stream.path); + fileInfo.path = stream.path; + fileInfo.size = stat.size; + } + return core.fromStream(stream, fileInfo); +} diff --git a/node_modules/strtok3/lib/types.d.ts b/node_modules/strtok3/lib/types.d.ts new file mode 100644 index 0000000..d38e57a --- /dev/null +++ b/node_modules/strtok3/lib/types.d.ts @@ -0,0 +1,103 @@ +/// +import { IGetToken } from '@tokenizer/token'; +export interface IFileInfo { + /** + * File size in bytes + */ + size?: number; + /** + * MIME-type of file + */ + mimeType?: string; + /** + * File path + */ + path?: string; + /** + * File URL + */ + url?: string; +} +export interface IReadChunkOptions { + /** + * The offset in the buffer to start writing at; default is 0 + */ + offset?: number; + /** + * Number of bytes to read. + */ + length?: number; + /** + * Position where to begin reading from the file. + * Default it is `tokenizer.position`. + * Position may not be less then `tokenizer.position`. + */ + position?: number; + /** + * If set, will not throw an EOF error if not all of the requested data could be read + */ + mayBeLess?: boolean; +} +/** + * The tokenizer allows us to read or peek from the tokenizer-stream. + * The tokenizer-stream is an abstraction of a stream, file or Buffer. + */ +export interface ITokenizer { + /** + * Provide access to information of the underlying information stream or file. + */ + fileInfo: IFileInfo; + /** + * Offset in bytes (= number of bytes read) since beginning of file or stream + */ + position: number; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer - Target buffer to fill with data peek from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + peekBuffer(buffer: Buffer, options?: IReadChunkOptions): Promise; + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer - Target buffer to fill with data peeked from the tokenizer-stream + * @param options - Additional read options + * @returns Promise with number of bytes read + */ + readBuffer(buffer: Buffer, options?: IReadChunkOptions): Promise; + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @param maybeless - If set, will not throw an EOF error if the less then the requested length could be read. + */ + peekToken(token: IGetToken, position?: number | null, maybeless?: boolean): Promise; + /** + * Read a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + */ + readToken(token: IGetToken, position?: number): Promise; + /** + * Peek a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + peekNumber(token: IGetToken): Promise; + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + readNumber(token: IGetToken): Promise; + /** + * Ignore given number of bytes + * @param length - Number of bytes ignored + */ + ignore(length: number): Promise; + /** + * Clean up resources. + * It does not close the stream for StreamReader, but is does close the file-descriptor. + */ + close(): Promise; +} diff --git a/node_modules/strtok3/lib/types.js b/node_modules/strtok3/lib/types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/strtok3/lib/types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/strtok3/package.json b/node_modules/strtok3/package.json new file mode 100644 index 0000000..0e7605f --- /dev/null +++ b/node_modules/strtok3/package.json @@ -0,0 +1,94 @@ +{ + "name": "strtok3", + "version": "7.0.0", + "description": "A promise based streaming tokenizer", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "scripts": { + "clean": "del-cli lib/**/*.js lib/**/*.js.map lib/**/*.d.ts test/**/*.js test/**/*.js.map", + "compile-src": "tsc -p lib", + "compile-test": "tsc -p test", + "compile": "npm run compile-src && npm run compile-test", + "build": "npm run clean && npm run compile", + "eslint": "eslint lib test --ext .ts --ignore-pattern *.d.ts", + "lint-md": "remark -u preset-lint-recommended .", + "lint": "npm run lint-md && npm run eslint", + "fix": "eslint lib test --ext .ts --ignore-pattern *.d.ts --fix", + "test": "mocha", + "test-coverage": "c8 npm run test", + "send-codacy": "c8 report --reporter=text-lcov | codacy-coverage", + "start": "npm run compile && npm run lint && npm run cover-test" + }, + "engines": { + "node": ">=14.16" + }, + "repository": { + "type": "git", + "url": "https://github.com/Borewit/strtok3.git" + }, + "license": "MIT", + "type": "module", + "exports": { + ".": { + "node": "./lib/index.js", + "default": "./lib/core.js" + }, + "./core": "./lib/core.js" + }, + "types": "lib/index.d.ts", + "files": [ + "lib/**/*.js", + "lib/**/*.d.ts" + ], + "bugs": { + "url": "https://github.com/Borewit/strtok3/issues" + }, + "devDependencies": { + "@types/chai": "^4.3.1", + "@types/debug": "^4.1.7", + "@types/mocha": "^9.1.0", + "@types/node": "^18.6.3", + "@typescript-eslint/eslint-plugin": "^5.32.0", + "@typescript-eslint/parser": "^5.32.0", + "c8": "^7.12.0", + "chai": "^4.3.6", + "del-cli": "^5.0.0", + "eslint": "^8.21.0", + "eslint-config-prettier": "^8.5.0", + "eslint-import-resolver-typescript": "^3.4.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-jsdoc": "^39.3.4", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-unicorn": "^43.0.2", + "mocha": "^10.0.0", + "remark-cli": "^11.0.0", + "remark-preset-lint-recommended": "^6.1.2", + "token-types": "^5.0.0", + "ts-node": "^10.9.1", + "typescript": "^4.7.4" + }, + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^5.0.0" + }, + "keywords": [ + "tokenizer", + "reader", + "token", + "async", + "promise", + "parser", + "decoder", + "binary", + "endian", + "uint", + "stream", + "streaming" + ] +} diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js new file mode 100644 index 0000000..62afa3a --- /dev/null +++ b/node_modules/supports-color/browser.js @@ -0,0 +1,5 @@ +'use strict'; +module.exports = { + stdout: false, + stderr: false +}; diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js new file mode 100644 index 0000000..1704131 --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,131 @@ +'use strict'; +const os = require('os'); +const hasFlag = require('has-flag'); + +const env = process.env; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; diff --git a/node_modules/supports-color/license b/node_modules/supports-color/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/supports-color/package.json b/node_modules/supports-color/package.json new file mode 100644 index 0000000..6199904 --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,88 @@ +{ + "_args": [ + [ + "supports-color@5.5.0", + "/home/other/discord_bot" + ] + ], + "_from": "supports-color@5.5.0", + "_id": "supports-color@5.5.0", + "_inBundle": false, + "_integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "_location": "/supports-color", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "supports-color@5.5.0", + "name": "supports-color", + "escapedName": "supports-color", + "rawSpec": "5.5.0", + "saveSpec": null, + "fetchSpec": "5.5.0" + }, + "_requiredBy": [ + "/nodemon" + ], + "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "_spec": "5.5.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/chalk/supports-color/issues" + }, + "dependencies": { + "has-flag": "^3.0.0" + }, + "description": "Detect whether a terminal supports color", + "devDependencies": { + "ava": "^0.25.0", + "import-fresh": "^2.0.0", + "xo": "^0.20.0" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js", + "browser.js" + ], + "homepage": "https://github.com/chalk/supports-color#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "license": "MIT", + "name": "supports-color", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/supports-color.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "5.5.0" +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 0000000..f6e4019 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,66 @@ +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install supports-color +``` + + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +## License + +MIT diff --git a/node_modules/to-readable-stream/index.js b/node_modules/to-readable-stream/index.js new file mode 100644 index 0000000..554bfa5 --- /dev/null +++ b/node_modules/to-readable-stream/index.js @@ -0,0 +1,11 @@ +'use strict'; +const {Readable} = require('stream'); + +module.exports = input => ( + new Readable({ + read() { + this.push(input); + this.push(null); + } + }) +); diff --git a/node_modules/to-readable-stream/license b/node_modules/to-readable-stream/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/to-readable-stream/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/to-readable-stream/package.json b/node_modules/to-readable-stream/package.json new file mode 100644 index 0000000..90a1734 --- /dev/null +++ b/node_modules/to-readable-stream/package.json @@ -0,0 +1,75 @@ +{ + "_args": [ + [ + "to-readable-stream@1.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "to-readable-stream@1.0.0", + "_id": "to-readable-stream@1.0.0", + "_inBundle": false, + "_integrity": "sha512-Iq25XBt6zD5npPhlLVXGFN3/gyR2/qODcKNNyTMd4vbm39HUaOiAM4PMq0eMVC/Tkxz+Zjdsc55g9yyz+Yq00Q==", + "_location": "/to-readable-stream", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "to-readable-stream@1.0.0", + "name": "to-readable-stream", + "escapedName": "to-readable-stream", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/to-readable-stream/-/to-readable-stream-1.0.0.tgz", + "_spec": "1.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/to-readable-stream/issues" + }, + "description": "Convert a string/Buffer/Uint8Array to a readable stream", + "devDependencies": { + "ava": "*", + "get-stream": "^3.0.0", + "xo": "*" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/to-readable-stream#readme", + "keywords": [ + "stream", + "readablestream", + "string", + "buffer", + "uint8array", + "from", + "into", + "to", + "transform", + "convert", + "readable", + "pull" + ], + "license": "MIT", + "name": "to-readable-stream", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/to-readable-stream.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "1.0.0" +} diff --git a/node_modules/to-readable-stream/readme.md b/node_modules/to-readable-stream/readme.md new file mode 100644 index 0000000..fc207c5 --- /dev/null +++ b/node_modules/to-readable-stream/readme.md @@ -0,0 +1,42 @@ +# to-readable-stream [![Build Status](https://travis-ci.org/sindresorhus/to-readable-stream.svg?branch=master)](https://travis-ci.org/sindresorhus/to-readable-stream) + +> Convert a string/Buffer/Uint8Array to a [readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) + + +## Install + +``` +$ npm install to-readable-stream +``` + + +## Usage + +```js +const toReadableStream = require('to-readable-stream'); + +toReadableStream('🦄🌈').pipe(process.stdout); +``` + + +## API + +### toReadableStream(input) + +Returns a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams). + +#### input + +Type: `string` `Buffer` `Uint8Array` + +Value to convert to a stream. + + +## Related + +- [into-stream](https://github.com/sindresorhus/into-stream) - More advanced version of this module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/to-regex-range/LICENSE b/node_modules/to-regex-range/LICENSE new file mode 100644 index 0000000..7cccaf9 --- /dev/null +++ b/node_modules/to-regex-range/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-present, Jon Schlinkert. + +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/to-regex-range/README.md b/node_modules/to-regex-range/README.md new file mode 100644 index 0000000..38887da --- /dev/null +++ b/node_modules/to-regex-range/README.md @@ -0,0 +1,305 @@ +# to-regex-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) + +> Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save to-regex-range +``` + +
+What does this do? + +
+ +This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. + +**Example** + +```js +const toRegexRange = require('to-regex-range'); +const regex = new RegExp(toRegexRange('15', '95')); +``` + +A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). + +
+ +
+ +
+Why use this library? + +
+ +### Convenience + +Creating regular expressions for matching numbers gets deceptively complicated pretty fast. + +For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: + +* regex for matching `1` => `/1/` (easy enough) +* regex for matching `1` through `5` => `/[1-5]/` (not bad...) +* regex for matching `1` or `5` => `/(1|5)/` (still easy...) +* regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) +* regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) +* regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) +* regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) + +The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. + +**Learn more** + +If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. + +### Heavily tested + +As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. + +Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. + +### Optimized + +Generated regular expressions are optimized: + +* duplicate sequences and character classes are reduced using quantifiers +* smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative +* uses fragment caching to avoid processing the same exact string more than once + +
+ +
+ +## Usage + +Add this library to your javascript application with the following line of code + +```js +const toRegexRange = require('to-regex-range'); +``` + +The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). + +```js +const source = toRegexRange('15', '95'); +//=> 1[5-9]|[2-8][0-9]|9[0-5] + +const regex = new RegExp(`^${source}$`); +console.log(regex.test('14')); //=> false +console.log(regex.test('50')); //=> true +console.log(regex.test('94')); //=> true +console.log(regex.test('96')); //=> false +``` + +## Options + +### options.capture + +**Type**: `boolean` + +**Deafault**: `undefined` + +Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. + +```js +console.log(toRegexRange('-10', '10')); +//=> -[1-9]|-?10|[0-9] + +console.log(toRegexRange('-10', '10', { capture: true })); +//=> (-[1-9]|-?10|[0-9]) +``` + +### options.shorthand + +**Type**: `boolean` + +**Deafault**: `undefined` + +Use the regex shorthand for `[0-9]`: + +```js +console.log(toRegexRange('0', '999999')); +//=> [0-9]|[1-9][0-9]{1,5} + +console.log(toRegexRange('0', '999999', { shorthand: true })); +//=> \d|[1-9]\d{1,5} +``` + +### options.relaxZeros + +**Type**: `boolean` + +**Default**: `true` + +This option relaxes matching for leading zeros when when ranges are zero-padded. + +```js +const source = toRegexRange('-0010', '0010'); +const regex = new RegExp(`^${source}$`); +console.log(regex.test('-10')); //=> true +console.log(regex.test('-010')); //=> true +console.log(regex.test('-0010')); //=> true +console.log(regex.test('10')); //=> true +console.log(regex.test('010')); //=> true +console.log(regex.test('0010')); //=> true +``` + +When `relaxZeros` is false, matching is strict: + +```js +const source = toRegexRange('-0010', '0010', { relaxZeros: false }); +const regex = new RegExp(`^${source}$`); +console.log(regex.test('-10')); //=> false +console.log(regex.test('-010')); //=> false +console.log(regex.test('-0010')); //=> true +console.log(regex.test('10')); //=> false +console.log(regex.test('010')); //=> false +console.log(regex.test('0010')); //=> true +``` + +## Examples + +| **Range** | **Result** | **Compile time** | +| --- | --- | --- | +| `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | +| `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | +| `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | +| `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | +| `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | +| `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | +| `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | +| `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | +| `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | +| `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | +| `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | +| `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | +| `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | +| `toRegexRange(5, 5)` | `5` | _8μs_ | +| `toRegexRange(5, 6)` | `5\|6` | _11μs_ | +| `toRegexRange(1, 2)` | `1\|2` | _6μs_ | +| `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | +| `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | +| `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | +| `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | +| `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | +| `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | +| `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | +| `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | + +## Heads up! + +**Order of arguments** + +When the `min` is larger than the `max`, values will be flipped to create a valid range: + +```js +toRegexRange('51', '29'); +``` + +Is effectively flipped to: + +```js +toRegexRange('29', '51'); +//=> 29|[3-4][0-9]|5[0-1] +``` + +**Steps / increments** + +This library does not support steps (increments). A pr to add support would be welcome. + +## History + +### v2.0.0 - 2017-04-21 + +**New features** + +Adds support for zero-padding! + +### v1.0.0 + +**Optimizations** + +Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. + +## Attribution + +Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") +* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") +* [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") +* [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 63 | [jonschlinkert](https://github.com/jonschlinkert) | +| 3 | [doowb](https://github.com/doowb) | +| 2 | [realityking](https://github.com/realityking) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! + + + + + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._ \ No newline at end of file diff --git a/node_modules/to-regex-range/index.js b/node_modules/to-regex-range/index.js new file mode 100644 index 0000000..77fbace --- /dev/null +++ b/node_modules/to-regex-range/index.js @@ -0,0 +1,288 @@ +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +'use strict'; + +const isNumber = require('is-number'); + +const toRegexRange = (min, max, options) => { + if (isNumber(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives, opts); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; + let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; + let intersected = filterPatterns(neg, pos, '-?', true, options) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit, options); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange.cache = {}; +toRegexRange.clearCache = () => (toRegexRange.cache = {}); + +/** + * Expose `toRegexRange` + */ + +module.exports = toRegexRange; diff --git a/node_modules/to-regex-range/package.json b/node_modules/to-regex-range/package.json new file mode 100644 index 0000000..7900717 --- /dev/null +++ b/node_modules/to-regex-range/package.json @@ -0,0 +1,128 @@ +{ + "_args": [ + [ + "to-regex-range@5.0.1", + "/home/other/discord_bot" + ] + ], + "_from": "to-regex-range@5.0.1", + "_id": "to-regex-range@5.0.1", + "_inBundle": false, + "_integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "_location": "/to-regex-range", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "to-regex-range@5.0.1", + "name": "to-regex-range", + "escapedName": "to-regex-range", + "rawSpec": "5.0.1", + "saveSpec": null, + "fetchSpec": "5.0.1" + }, + "_requiredBy": [ + "/fill-range" + ], + "_resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "_spec": "5.0.1", + "_where": "/home/other/discord_bot", + "author": { + "name": "Jon Schlinkert", + "url": "https://github.com/jonschlinkert" + }, + "bugs": { + "url": "https://github.com/micromatch/to-regex-range/issues" + }, + "contributors": [ + { + "name": "Jon Schlinkert", + "url": "http://twitter.com/jonschlinkert" + }, + { + "name": "Rouven Weßling", + "url": "www.rouvenwessling.de" + } + ], + "dependencies": { + "is-number": "^7.0.0" + }, + "description": "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.", + "devDependencies": { + "fill-range": "^6.0.0", + "gulp-format-md": "^2.0.0", + "mocha": "^6.0.2", + "text-table": "^0.2.0", + "time-diff": "^0.3.1" + }, + "engines": { + "node": ">=8.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/micromatch/to-regex-range", + "keywords": [ + "bash", + "date", + "expand", + "expansion", + "expression", + "glob", + "match", + "match date", + "match number", + "match numbers", + "match year", + "matches", + "matching", + "number", + "numbers", + "numerical", + "range", + "ranges", + "regex", + "regexp", + "regular", + "regular expression", + "sequence" + ], + "license": "MIT", + "main": "index.js", + "name": "to-regex-range", + "repository": { + "type": "git", + "url": "git+https://github.com/micromatch/to-regex-range.git" + }, + "scripts": { + "test": "mocha" + }, + "verb": { + "layout": "default", + "toc": false, + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "lint": { + "reflinks": true + }, + "helpers": { + "examples": { + "displayName": "examples" + } + }, + "related": { + "list": [ + "expand-range", + "fill-range", + "micromatch", + "repeat-element", + "repeat-string" + ] + } + }, + "version": "5.0.1" +} diff --git a/node_modules/token-types/LICENSE b/node_modules/token-types/LICENSE new file mode 100644 index 0000000..ffcebb7 --- /dev/null +++ b/node_modules/token-types/LICENSE @@ -0,0 +1,7 @@ +Copyright 2017 Borewit + +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/token-types/README.md b/node_modules/token-types/README.md new file mode 100644 index 0000000..b943f6a --- /dev/null +++ b/node_modules/token-types/README.md @@ -0,0 +1,120 @@ +![Node.js CI](https://github.com/Borewit/token-types/workflows/Node.js%20CI/badge.svg) +[![NPM version](https://badge.fury.io/js/token-types.svg)](https://npmjs.org/package/token-types) +[![npm downloads](http://img.shields.io/npm/dm/token-types.svg)](https://npmcharts.com/compare/token-types,strtok3?start=1200&interval=30) +[![coveralls](https://coveralls.io/repos/github/Borewit/token-types/badge.svg?branch=master)](https://coveralls.io/github/Borewit/token-types?branch=master) +[![Codacy Badge](https://api.codacy.com/project/badge/Grade/4723ce4613fc49cda8db5eed29f18834)](https://www.codacy.com/app/Borewit/token-types?utm_source=github.com&utm_medium=referral&utm_content=Borewit/token-types&utm_campaign=Badge_Grade) +[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/Borewit/token-types.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/token-types/context:javascript) +[![Total alerts](https://img.shields.io/lgtm/alerts/g/Borewit/token-types.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/Borewit/token-types/alerts/) +[![DeepScan grade](https://deepscan.io/api/teams/5165/projects/6940/branches/61852/badge/grade.svg)](https://deepscan.io/dashboard#view=project&tid=5165&pid=6940&bid=61852) +[![Known Vulnerabilities](https://snyk.io/test/github/Borewit/token-types/badge.svg?targetFile=package.json)](https://snyk.io/test/github/Borewit/token-types?targetFile=package.json) + +# token-types + +A primitive token library used to read and write from a node `Buffer`. +Although it is possible to use this module directly, it is primary designed to be used with [strtok3 tokenizer](https://github.com/Borewit/strtok3). + +## Compatibility + +Module: version 5 migrated from [CommonJS](https://en.wikipedia.org/wiki/CommonJS) to [pure ECMAScript Module (ESM)](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). +JavaScript is compliant with [ECMAScript 2019 (ES10)](https://en.wikipedia.org/wiki/ECMAScript#10th_Edition_%E2%80%93_ECMAScript_2019). + +## Installation + +```sh +npm install --save token-types +``` +Usually in combination with [strtok3](https://github.com/Borewit/strtok3): +```sh +npm install --save strtok3 +``` + +Using TypeScript you should also install [@tokenizer/token](https://github.com/Borewit/tokenizer-token) as a development +dependency: + +```shell +npm install --save-dev @tokenizer/token +``` + + +## Example + +```js +import * as strtok3 from 'strtok3'; +import * as token from 'token-types'; + +(async () => { + + const tokenizer = await strtok3.fromFile("somefile.bin"); + try { + const myNumber = await tokenizer.readToken(token.Float32_BE); + console.log(`My number: ${myNumber}`); + } finally { + tokenizer.close(); // Close the file + } +})(); +``` + +## Tokens + +### Numeric tokens + +`node-strtok` supports a wide variety of numerical tokens out of the box: + +| Token | Number | Bits | Endianness | +|---------------|------------------|------|----------------| +| `UINT8` | Unsigned integer | 8 | n/a | +| `UINT16_BE` | Unsigned integer | 16 | big endian | +| `UINT16_LE` | Unsigned integer | 16 | little endian | +| `UINT24_BE` | Unsigned integer | 24 | big endian | +| `UINT24_LE` | Unsigned integer | 24 | little endian | +| `UINT32_BE` | Unsigned integer | 32 | big endian | +| `UINT32_LE` | Unsigned integer | 32 | little endian | +| `UINT64_BE` | Unsigned integer | 64 | big endian | +| `UINT64_LE`* | Unsigned integer | 64 | little endian | +| `INT8` | Signed integer | 8 | n/a | +| `INT16_BE` | Signed integer | 16 | big endian | +| `INT16_LE` | Signed integer | 16 | little endian | +| `INT24_BE` | Signed integer | 24 | big endian | +| `INT24_LE` | Signed integer | 24 | little endian | +| `INT32_BE` | Signed integer | 32 | big endian | +| `INT32_LE` | Signed integer | 32 | little endian | +| `INT64_BE` | Signed integer | 64 | big endian | +| `INT64_LE`* | Signed integer | 64 | little endian | +| `Float16_BE` | IEEE 754 float | 16 | big endian | +| `Float16_LE` | IEEE 754 float | 16 | little endian | +| `Float32_BE` | IEEE 754 float | 32 | big endian | +| `Float32_LE` | IEEE 754 float | 32 | little endian | +| `Float64_BE` | IEEE 754 float | 64 | big endian | +| `Float64_LE` | IEEE 754 float | 64 | little endian | +| `Float80_BE`* | IEEE 754 float | 80 | big endian | +| `Float80_LE`* | IEEE 754 float | 80 | little endian | + +### Other tokens + +String types: +* Windows-1252 +* ISO-8859-1 + +*) The tokens exceed the JavaScript IEEE 754 64-bit Floating Point precision, decoding and encoding is best effort based. + +### Custom token + +Complex tokens can be added, which makes very suitable for reading binary files or network messages: +```js + ExtendedHeader = { + len: 10, + + get: (buf, off) => { + return { + // Extended header size + size: Token.UINT32_BE.get(buf, off), + // Extended Flags + extendedFlags: Token.UINT16_BE.get(buf, off + 4), + // Size of padding + sizeOfPadding: Token.UINT32_BE.get(buf, off + 6), + // CRC data present + crcDataPresent: common.strtokBITSET.get(buf, off + 4, 31) + }; + } + }; +``` diff --git a/node_modules/token-types/lib/index.d.ts b/node_modules/token-types/lib/index.d.ts new file mode 100644 index 0000000..bfb5b08 --- /dev/null +++ b/node_modules/token-types/lib/index.d.ts @@ -0,0 +1,151 @@ +/// +import { IToken, IGetToken } from '@tokenizer/token'; +import { Buffer } from 'node:buffer'; +/** + * 8-bit unsigned integer + */ +export declare const UINT8: IToken; +/** + * 16-bit unsigned integer, Little Endian byte order + */ +export declare const UINT16_LE: IToken; +/** + * 16-bit unsigned integer, Big Endian byte order + */ +export declare const UINT16_BE: IToken; +/** + * 24-bit unsigned integer, Little Endian byte order + */ +export declare const UINT24_LE: IToken; +/** + * 24-bit unsigned integer, Big Endian byte order + */ +export declare const UINT24_BE: IToken; +/** + * 32-bit unsigned integer, Little Endian byte order + */ +export declare const UINT32_LE: IToken; +/** + * 32-bit unsigned integer, Big Endian byte order + */ +export declare const UINT32_BE: IToken; +/** + * 8-bit signed integer + */ +export declare const INT8: IToken; +/** + * 16-bit signed integer, Big Endian byte order + */ +export declare const INT16_BE: IToken; +/** + * 16-bit signed integer, Little Endian byte order + */ +export declare const INT16_LE: IToken; +/** + * 24-bit signed integer, Little Endian byte order + */ +export declare const INT24_LE: IToken; +/** + * 24-bit signed integer, Big Endian byte order + */ +export declare const INT24_BE: IToken; +/** + * 32-bit signed integer, Big Endian byte order + */ +export declare const INT32_BE: IToken; +/** + * 32-bit signed integer, Big Endian byte order + */ +export declare const INT32_LE: IToken; +/** + * 64-bit unsigned integer, Little Endian byte order + */ +export declare const UINT64_LE: IToken; +/** + * 64-bit signed integer, Little Endian byte order + */ +export declare const INT64_LE: IToken; +/** + * 64-bit unsigned integer, Big Endian byte order + */ +export declare const UINT64_BE: IToken; +/** + * 64-bit signed integer, Big Endian byte order + */ +export declare const INT64_BE: IToken; +/** + * IEEE 754 16-bit (half precision) float, big endian + */ +export declare const Float16_BE: IToken; +/** + * IEEE 754 16-bit (half precision) float, little endian + */ +export declare const Float16_LE: IToken; +/** + * IEEE 754 32-bit (single precision) float, big endian + */ +export declare const Float32_BE: IToken; +/** + * IEEE 754 32-bit (single precision) float, little endian + */ +export declare const Float32_LE: IToken; +/** + * IEEE 754 64-bit (double precision) float, big endian + */ +export declare const Float64_BE: IToken; +/** + * IEEE 754 64-bit (double precision) float, little endian + */ +export declare const Float64_LE: IToken; +/** + * IEEE 754 80-bit (extended precision) float, big endian + */ +export declare const Float80_BE: IToken; +/** + * IEEE 754 80-bit (extended precision) float, little endian + */ +export declare const Float80_LE: IToken; +/** + * Ignore a given number of bytes + */ +export declare class IgnoreType implements IGetToken { + len: number; + /** + * @param len number of bytes to ignore + */ + constructor(len: number); + get(array: Uint8Array, off: number): void; +} +export declare class Uint8ArrayType implements IGetToken { + len: number; + constructor(len: number); + get(array: Uint8Array, offset: number): Uint8Array; +} +export declare class BufferType implements IGetToken { + len: number; + constructor(len: number); + get(uint8Array: Uint8Array, off: number): Buffer; +} +/** + * Consume a fixed number of bytes from the stream and return a string with a specified encoding. + */ +export declare class StringType implements IGetToken { + len: number; + encoding: BufferEncoding; + constructor(len: number, encoding: BufferEncoding); + get(uint8Array: Uint8Array, offset: number): string; +} +/** + * ANSI Latin 1 String + * Using windows-1252 / ISO 8859-1 decoding + */ +export declare class AnsiStringType implements IGetToken { + len: number; + private static windows1252; + private static decode; + private static inRange; + private static codePointToString; + private static singleByteDecoder; + constructor(len: number); + get(buffer: Buffer, offset?: number): string; +} diff --git a/node_modules/token-types/lib/index.js b/node_modules/token-types/lib/index.js new file mode 100644 index 0000000..f78de83 --- /dev/null +++ b/node_modules/token-types/lib/index.js @@ -0,0 +1,449 @@ +import * as ieee754 from 'ieee754'; +import { Buffer } from 'node:buffer'; +// Primitive types +function dv(array) { + return new DataView(array.buffer, array.byteOffset); +} +/** + * 8-bit unsigned integer + */ +export const UINT8 = { + len: 1, + get(array, offset) { + return dv(array).getUint8(offset); + }, + put(array, offset, value) { + dv(array).setUint8(offset, value); + return offset + 1; + } +}; +/** + * 16-bit unsigned integer, Little Endian byte order + */ +export const UINT16_LE = { + len: 2, + get(array, offset) { + return dv(array).getUint16(offset, true); + }, + put(array, offset, value) { + dv(array).setUint16(offset, value, true); + return offset + 2; + } +}; +/** + * 16-bit unsigned integer, Big Endian byte order + */ +export const UINT16_BE = { + len: 2, + get(array, offset) { + return dv(array).getUint16(offset); + }, + put(array, offset, value) { + dv(array).setUint16(offset, value); + return offset + 2; + } +}; +/** + * 24-bit unsigned integer, Little Endian byte order + */ +export const UINT24_LE = { + len: 3, + get(array, offset) { + const dataView = dv(array); + return dataView.getUint8(offset) + (dataView.getUint16(offset + 1, true) << 8); + }, + put(array, offset, value) { + const dataView = dv(array); + dataView.setUint8(offset, value & 0xff); + dataView.setUint16(offset + 1, value >> 8, true); + return offset + 3; + } +}; +/** + * 24-bit unsigned integer, Big Endian byte order + */ +export const UINT24_BE = { + len: 3, + get(array, offset) { + const dataView = dv(array); + return (dataView.getUint16(offset) << 8) + dataView.getUint8(offset + 2); + }, + put(array, offset, value) { + const dataView = dv(array); + dataView.setUint16(offset, value >> 8); + dataView.setUint8(offset + 2, value & 0xff); + return offset + 3; + } +}; +/** + * 32-bit unsigned integer, Little Endian byte order + */ +export const UINT32_LE = { + len: 4, + get(array, offset) { + return dv(array).getUint32(offset, true); + }, + put(array, offset, value) { + dv(array).setUint32(offset, value, true); + return offset + 4; + } +}; +/** + * 32-bit unsigned integer, Big Endian byte order + */ +export const UINT32_BE = { + len: 4, + get(array, offset) { + return dv(array).getUint32(offset); + }, + put(array, offset, value) { + dv(array).setUint32(offset, value); + return offset + 4; + } +}; +/** + * 8-bit signed integer + */ +export const INT8 = { + len: 1, + get(array, offset) { + return dv(array).getInt8(offset); + }, + put(array, offset, value) { + dv(array).setInt8(offset, value); + return offset + 1; + } +}; +/** + * 16-bit signed integer, Big Endian byte order + */ +export const INT16_BE = { + len: 2, + get(array, offset) { + return dv(array).getInt16(offset); + }, + put(array, offset, value) { + dv(array).setInt16(offset, value); + return offset + 2; + } +}; +/** + * 16-bit signed integer, Little Endian byte order + */ +export const INT16_LE = { + len: 2, + get(array, offset) { + return dv(array).getInt16(offset, true); + }, + put(array, offset, value) { + dv(array).setInt16(offset, value, true); + return offset + 2; + } +}; +/** + * 24-bit signed integer, Little Endian byte order + */ +export const INT24_LE = { + len: 3, + get(array, offset) { + const unsigned = UINT24_LE.get(array, offset); + return unsigned > 0x7fffff ? unsigned - 0x1000000 : unsigned; + }, + put(array, offset, value) { + const dataView = dv(array); + dataView.setUint8(offset, value & 0xff); + dataView.setUint16(offset + 1, value >> 8, true); + return offset + 3; + } +}; +/** + * 24-bit signed integer, Big Endian byte order + */ +export const INT24_BE = { + len: 3, + get(array, offset) { + const unsigned = UINT24_BE.get(array, offset); + return unsigned > 0x7fffff ? unsigned - 0x1000000 : unsigned; + }, + put(array, offset, value) { + const dataView = dv(array); + dataView.setUint16(offset, value >> 8); + dataView.setUint8(offset + 2, value & 0xff); + return offset + 3; + } +}; +/** + * 32-bit signed integer, Big Endian byte order + */ +export const INT32_BE = { + len: 4, + get(array, offset) { + return dv(array).getInt32(offset); + }, + put(array, offset, value) { + dv(array).setInt32(offset, value); + return offset + 4; + } +}; +/** + * 32-bit signed integer, Big Endian byte order + */ +export const INT32_LE = { + len: 4, + get(array, offset) { + return dv(array).getInt32(offset, true); + }, + put(array, offset, value) { + dv(array).setInt32(offset, value, true); + return offset + 4; + } +}; +/** + * 64-bit unsigned integer, Little Endian byte order + */ +export const UINT64_LE = { + len: 8, + get(array, offset) { + return dv(array).getBigUint64(offset, true); + }, + put(array, offset, value) { + dv(array).setBigUint64(offset, value, true); + return offset + 8; + } +}; +/** + * 64-bit signed integer, Little Endian byte order + */ +export const INT64_LE = { + len: 8, + get(array, offset) { + return dv(array).getBigInt64(offset, true); + }, + put(array, offset, value) { + dv(array).setBigInt64(offset, value, true); + return offset + 8; + } +}; +/** + * 64-bit unsigned integer, Big Endian byte order + */ +export const UINT64_BE = { + len: 8, + get(array, offset) { + return dv(array).getBigUint64(offset); + }, + put(array, offset, value) { + dv(array).setBigUint64(offset, value); + return offset + 8; + } +}; +/** + * 64-bit signed integer, Big Endian byte order + */ +export const INT64_BE = { + len: 8, + get(array, offset) { + return dv(array).getBigInt64(offset); + }, + put(array, offset, value) { + dv(array).setBigInt64(offset, value); + return offset + 8; + } +}; +/** + * IEEE 754 16-bit (half precision) float, big endian + */ +export const Float16_BE = { + len: 2, + get(dataView, offset) { + return ieee754.read(dataView, offset, false, 10, this.len); + }, + put(dataView, offset, value) { + ieee754.write(dataView, value, offset, false, 10, this.len); + return offset + this.len; + } +}; +/** + * IEEE 754 16-bit (half precision) float, little endian + */ +export const Float16_LE = { + len: 2, + get(array, offset) { + return ieee754.read(array, offset, true, 10, this.len); + }, + put(array, offset, value) { + ieee754.write(array, value, offset, true, 10, this.len); + return offset + this.len; + } +}; +/** + * IEEE 754 32-bit (single precision) float, big endian + */ +export const Float32_BE = { + len: 4, + get(array, offset) { + return dv(array).getFloat32(offset); + }, + put(array, offset, value) { + dv(array).setFloat32(offset, value); + return offset + 4; + } +}; +/** + * IEEE 754 32-bit (single precision) float, little endian + */ +export const Float32_LE = { + len: 4, + get(array, offset) { + return dv(array).getFloat32(offset, true); + }, + put(array, offset, value) { + dv(array).setFloat32(offset, value, true); + return offset + 4; + } +}; +/** + * IEEE 754 64-bit (double precision) float, big endian + */ +export const Float64_BE = { + len: 8, + get(array, offset) { + return dv(array).getFloat64(offset); + }, + put(array, offset, value) { + dv(array).setFloat64(offset, value); + return offset + 8; + } +}; +/** + * IEEE 754 64-bit (double precision) float, little endian + */ +export const Float64_LE = { + len: 8, + get(array, offset) { + return dv(array).getFloat64(offset, true); + }, + put(array, offset, value) { + dv(array).setFloat64(offset, value, true); + return offset + 8; + } +}; +/** + * IEEE 754 80-bit (extended precision) float, big endian + */ +export const Float80_BE = { + len: 10, + get(array, offset) { + return ieee754.read(array, offset, false, 63, this.len); + }, + put(array, offset, value) { + ieee754.write(array, value, offset, false, 63, this.len); + return offset + this.len; + } +}; +/** + * IEEE 754 80-bit (extended precision) float, little endian + */ +export const Float80_LE = { + len: 10, + get(array, offset) { + return ieee754.read(array, offset, true, 63, this.len); + }, + put(array, offset, value) { + ieee754.write(array, value, offset, true, 63, this.len); + return offset + this.len; + } +}; +/** + * Ignore a given number of bytes + */ +export class IgnoreType { + /** + * @param len number of bytes to ignore + */ + constructor(len) { + this.len = len; + } + // ToDo: don't read, but skip data + // eslint-disable-next-line @typescript-eslint/no-empty-function + get(array, off) { + } +} +export class Uint8ArrayType { + constructor(len) { + this.len = len; + } + get(array, offset) { + return array.subarray(offset, offset + this.len); + } +} +export class BufferType { + constructor(len) { + this.len = len; + } + get(uint8Array, off) { + return Buffer.from(uint8Array.subarray(off, off + this.len)); + } +} +/** + * Consume a fixed number of bytes from the stream and return a string with a specified encoding. + */ +export class StringType { + constructor(len, encoding) { + this.len = len; + this.encoding = encoding; + } + get(uint8Array, offset) { + return Buffer.from(uint8Array).toString(this.encoding, offset, offset + this.len); + } +} +/** + * ANSI Latin 1 String + * Using windows-1252 / ISO 8859-1 decoding + */ +export class AnsiStringType { + constructor(len) { + this.len = len; + } + static decode(buffer, offset, until) { + let str = ''; + for (let i = offset; i < until; ++i) { + str += AnsiStringType.codePointToString(AnsiStringType.singleByteDecoder(buffer[i])); + } + return str; + } + static inRange(a, min, max) { + return min <= a && a <= max; + } + static codePointToString(cp) { + if (cp <= 0xFFFF) { + return String.fromCharCode(cp); + } + else { + cp -= 0x10000; + return String.fromCharCode((cp >> 10) + 0xD800, (cp & 0x3FF) + 0xDC00); + } + } + static singleByteDecoder(bite) { + if (AnsiStringType.inRange(bite, 0x00, 0x7F)) { + return bite; + } + const codePoint = AnsiStringType.windows1252[bite - 0x80]; + if (codePoint === null) { + throw Error('invaliding encoding'); + } + return codePoint; + } + get(buffer, offset = 0) { + return AnsiStringType.decode(buffer, offset, offset + this.len); + } +} +AnsiStringType.windows1252 = [8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, + 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, + 8482, 353, 8250, 339, 157, 382, 376, 160, 161, 162, 163, 164, 165, 166, 167, 168, + 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, + 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, + 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, + 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, + 248, 249, 250, 251, 252, 253, 254, 255]; diff --git a/node_modules/token-types/package.json b/node_modules/token-types/package.json new file mode 100644 index 0000000..50cb74b --- /dev/null +++ b/node_modules/token-types/package.json @@ -0,0 +1,87 @@ +{ + "name": "token-types", + "version": "5.0.1", + "description": "Common token types for decoding and encoding numeric and string values", + "author": { + "name": "Borewit", + "url": "https://github.com/Borewit" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + "scripts": { + "clean": "del-cli lib/**/*.js lib/***.js.map *.d.ts test/**/*.d.ts test/**/*.js test/**/*.js.map .nyc_output", + "build": "npm run compile", + "compile-src": "tsc --p lib", + "compile-test": "tsc --p test", + "compile": "npm run compile-src && npm run compile-test", + "eslint": "eslint lib test --ext .ts --ignore-pattern *.d.ts", + "lint-ts": "tslint lib/index.ts --exclude '*.d.ts' 'test/**/*.ts' --exclude 'test/**/*.d.ts'", + "lint-md": "remark -u preset-lint-recommended .", + "lint": "npm run lint-md && npm run eslint", + "test": "mocha", + "test-coverage": "c8 npm run test", + "send-codacy": "c8 report --reports-dir=./.coverage --reporter=text-lcov | codacy-coverage" + }, + "engines": { + "node": ">=14.16" + }, + "repository": { + "type": "git", + "url": "https://github.com/Borewit/token-types" + }, + "files": [ + "lib/index.js", + "lib/index.d.ts" + ], + "license": "MIT", + "type": "module", + "exports": "./lib/index.js", + "types": "lib/index.d.ts", + "bugs": { + "url": "https://github.com/Borewit/token-types/issues" + }, + "devDependencies": { + "@types/chai": "^4.3.1", + "@types/mocha": "^9.1.0", + "@types/node": "^18.6.3", + "@typescript-eslint/eslint-plugin": "^5.32.0", + "@typescript-eslint/parser": "^5.32.0", + "c8": "^7.12.0", + "chai": "^4.3.6", + "del-cli": "^5.0.0", + "eslint": "^8.9.0", + "eslint-config-prettier": "^8.5.0", + "eslint-import-resolver-typescript": "^3.4.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-jsdoc": "^39.3.4", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-unicorn": "^43.0.2", + "mocha": "^10.0.0", + "remark-cli": "^11.0.0", + "remark-preset-lint-recommended": "^6.1.2", + "source-map-support": "^0.5.21", + "ts-node": "^10.9.1", + "typescript": "^4.7.4" + }, + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "remarkConfig": { + "plugins": [ + "preset-lint-recommended" + ] + }, + "keywords": [ + "token", + "integer", + "unsigned", + "numeric", + "float", + "IEEE", + "754", + "strtok3" + ] +} diff --git a/node_modules/touch/LICENSE b/node_modules/touch/LICENSE new file mode 100644 index 0000000..05eeeb8 --- /dev/null +++ b/node_modules/touch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/touch/README.md b/node_modules/touch/README.md new file mode 100644 index 0000000..b5a361e --- /dev/null +++ b/node_modules/touch/README.md @@ -0,0 +1,52 @@ +# node-touch + +For all your node touching needs. + +## Installing + +```bash +npm install touch +``` + +## CLI Usage: + +See `man touch` + +This package exports a binary called `nodetouch` that works mostly +like the unix builtin `touch(1)`. + +## API Usage: + +```javascript +var touch = require("touch") +``` + +Gives you the following functions: + +* `touch(filename, options, cb)` +* `touch.sync(filename, options)` +* `touch.ftouch(fd, options, cb)` +* `touch.ftouchSync(fd, options)` + +All the `options` objects are optional. + +All the async functions return a Promise. If a callback function is +provided, then it's attached to the Promise. + +## Options + +* `force` like `touch -f` Boolean +* `time` like `touch -t ` Can be a Date object, or any parseable + Date string, or epoch ms number. +* `atime` like `touch -a` Can be either a Boolean, or a Date. +* `mtime` like `touch -m` Can be either a Boolean, or a Date. +* `ref` like `touch -r ` Must be path to a file. +* `nocreate` like `touch -c` Boolean + +If neither `atime` nor `mtime` are set, then both values are set. If +one of them is set, then the other is not. + +## cli + +This package creates a `nodetouch` command line executable that works +very much like the unix builtin `touch(1)` diff --git a/node_modules/touch/bin/nodetouch.js b/node_modules/touch/bin/nodetouch.js new file mode 100755 index 0000000..f78f082 --- /dev/null +++ b/node_modules/touch/bin/nodetouch.js @@ -0,0 +1,112 @@ +#!/usr/bin/env node +const touch = require("../index.js") + +const usage = code => { + console[code ? 'error' : 'log']( + 'usage:\n' + + 'touch [-acfm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ...' + ) + process.exit(code) +} + +const singleFlags = { + a: 'atime', + m: 'mtime', + c: 'nocreate', + f: 'force' +} + +const singleOpts = { + r: 'ref', + t: 'time' +} + +const files = [] +const args = process.argv.slice(2) +const options = {} +for (let i = 0; i < args.length; i++) { + const arg = args[i] + if (!arg.match(/^-/)) { + files.push(arg) + continue + } + + // expand shorthands + if (arg.charAt(1) !== '-') { + const expand = [] + for (let f = 1; f < arg.length; f++) { + const fc = arg.charAt(f) + const sf = singleFlags[fc] + const so = singleOpts[fc] + if (sf) + expand.push('--' + sf) + else if (so) { + const soslice = arg.slice(f + 1) + const soval = soslice.charAt(0) === '=' ? soslice : '=' + soslice + expand.push('--' + so + soval) + f = arg.length + } else if (arg !== '-' + fc) + expand.push('-' + fc) + } + if (expand.length) { + args.splice.apply(args, [i, 1].concat(expand)) + i-- + continue + } + } + + const argsplit = arg.split('=') + const key = argsplit.shift().replace(/^\-\-/, '') + const val = argsplit.length ? argsplit.join('=') : null + + switch (key) { + case 'time': + const timestr = val || args[++i] + // [-t [[CC]YY]MMDDhhmm[.SS]] + const parsedtime = timestr.match( + /^(([0-9]{2})?([0-9]{2}))?([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})(\.([0-9]{2}))?$/ + ) + if (!parsedtime) { + console.error('touch: out of range or illegal ' + + 'time specification: ' + + '[[CC]YY]MMDDhhmm[.SS]') + process.exit(1) + } else { + const y = +parsedtime[1] + const year = parsedtime[2] ? y + : y <= 68 ? 2000 + y + : 1900 + y + + const MM = +parsedtime[4] - 1 + const dd = +parsedtime[5] + const hh = +parsedtime[6] + const mm = +parsedtime[7] + const ss = +parsedtime[8] + + options.time = new Date(Date.UTC(year, MM, dd, hh, mm, ss)) + } + continue + + case 'ref': + options.ref = val || args[++i] + continue + + case 'mtime': + case 'nocreate': + case 'atime': + case 'force': + options[key] = true + continue + + default: + console.error('touch: illegal option -- ' + arg) + usage(1) + } +} + +if (!files.length) + usage() + +process.exitCode = 0 +Promise.all(files.map(f => touch(f, options))) + .catch(er => process.exitCode = 1) diff --git a/node_modules/touch/index.js b/node_modules/touch/index.js new file mode 100644 index 0000000..f942e42 --- /dev/null +++ b/node_modules/touch/index.js @@ -0,0 +1,224 @@ +'use strict' + +const EE = require('events').EventEmitter +const cons = require('constants') +const fs = require('fs') + +module.exports = (f, options, cb) => { + if (typeof options === 'function') + cb = options, options = {} + + const p = new Promise((res, rej) => { + new Touch(validOpts(options, f, null)) + .on('done', res).on('error', rej) + }) + + return cb ? p.then(res => cb(null, res), cb) : p +} + +module.exports.sync = module.exports.touchSync = (f, options) => + (new TouchSync(validOpts(options, f, null)), undefined) + +module.exports.ftouch = (fd, options, cb) => { + if (typeof options === 'function') + cb = options, options = {} + + const p = new Promise((res, rej) => { + new Touch(validOpts(options, null, fd)) + .on('done', res).on('error', rej) + }) + + return cb ? p.then(res => cb(null, res), cb) : p +} + +module.exports.ftouchSync = (fd, opt) => + (new TouchSync(validOpts(opt, null, fd)), undefined) + +const validOpts = (options, path, fd) => { + options = Object.create(options || {}) + options.fd = fd + options.path = path + + // {mtime: true}, {ctime: true} + // If set to something else, then treat as epoch ms value + const now = parseInt(new Date(options.time || Date.now()).getTime() / 1000) + if (!options.atime && !options.mtime) + options.atime = options.mtime = now + else { + if (true === options.atime) + options.atime = now + + if (true === options.mtime) + options.mtime = now + } + + let oflags = 0 + if (!options.force) + oflags = oflags | cons.O_RDWR + + if (!options.nocreate) + oflags = oflags | cons.O_CREAT + + options.oflags = oflags + return options +} + +class Touch extends EE { + constructor (options) { + super(options) + this.fd = options.fd + this.path = options.path + this.atime = options.atime + this.mtime = options.mtime + this.ref = options.ref + this.nocreate = !!options.nocreate + this.force = !!options.force + this.closeAfter = options.closeAfter + this.oflags = options.oflags + this.options = options + + if (typeof this.fd !== 'number') { + this.closeAfter = true + this.open() + } else + this.onopen(null, this.fd) + } + + emit (ev, data) { + // we only emit when either done or erroring + // in both cases, need to close + this.close() + return super.emit(ev, data) + } + + close () { + if (typeof this.fd === 'number' && this.closeAfter) + fs.close(this.fd, () => {}) + } + + open () { + fs.open(this.path, this.oflags, (er, fd) => this.onopen(er, fd)) + } + + onopen (er, fd) { + if (er) { + if (er.code === 'EISDIR') + this.onopen(null, null) + else if (er.code === 'ENOENT' && this.nocreate) + this.emit('done') + else + this.emit('error', er) + } else { + this.fd = fd + if (this.ref) + this.statref() + else if (!this.atime || !this.mtime) + this.fstat() + else + this.futimes() + } + } + + statref () { + fs.stat(this.ref, (er, st) => { + if (er) + this.emit('error', er) + else + this.onstatref(st) + }) + } + + onstatref (st) { + this.atime = this.atime && parseInt(st.atime.getTime()/1000, 10) + this.mtime = this.mtime && parseInt(st.mtime.getTime()/1000, 10) + if (!this.atime || !this.mtime) + this.fstat() + else + this.futimes() + } + + fstat () { + const stat = this.fd ? 'fstat' : 'stat' + const target = this.fd || this.path + fs[stat](target, (er, st) => { + if (er) + this.emit('error', er) + else + this.onfstat(st) + }) + } + + onfstat (st) { + if (typeof this.atime !== 'number') + this.atime = parseInt(st.atime.getTime()/1000, 10) + + if (typeof this.mtime !== 'number') + this.mtime = parseInt(st.mtime.getTime()/1000, 10) + + this.futimes() + } + + futimes () { + const utimes = this.fd ? 'futimes' : 'utimes' + const target = this.fd || this.path + fs[utimes](target, ''+this.atime, ''+this.mtime, er => { + if (er) + this.emit('error', er) + else + this.emit('done') + }) + } +} + +class TouchSync extends Touch { + open () { + try { + this.onopen(null, fs.openSync(this.path, this.oflags)) + } catch (er) { + this.onopen(er) + } + } + + statref () { + let threw = true + try { + this.onstatref(fs.statSync(this.ref)) + threw = false + } finally { + if (threw) + this.close() + } + } + + fstat () { + let threw = true + const stat = this.fd ? 'fstatSync' : 'statSync' + const target = this.fd || this.path + try { + this.onfstat(fs[stat](target)) + threw = false + } finally { + if (threw) + this.close() + } + } + + futimes () { + let threw = true + const utimes = this.fd ? 'futimesSync' : 'utimesSync' + const target = this.fd || this.path + try { + fs[utimes](target, this.atime, this.mtime) + threw = false + } finally { + if (threw) + this.close() + } + this.emit('done') + } + + close () { + if (typeof this.fd === 'number' && this.closeAfter) + try { fs.closeSync(this.fd) } catch (er) {} + } +} diff --git a/node_modules/touch/package.json b/node_modules/touch/package.json new file mode 100644 index 0000000..9d5bddf --- /dev/null +++ b/node_modules/touch/package.json @@ -0,0 +1,67 @@ +{ + "_args": [ + [ + "touch@3.1.0", + "/home/other/discord_bot" + ] + ], + "_from": "touch@3.1.0", + "_id": "touch@3.1.0", + "_inBundle": false, + "_integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==", + "_location": "/touch", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "touch@3.1.0", + "name": "touch", + "escapedName": "touch", + "rawSpec": "3.1.0", + "saveSpec": null, + "fetchSpec": "3.1.0" + }, + "_requiredBy": [ + "/nodemon" + ], + "_resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz", + "_spec": "3.1.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bin": { + "nodetouch": "bin/nodetouch.js" + }, + "bugs": { + "url": "https://github.com/isaacs/node-touch/issues" + }, + "dependencies": { + "nopt": "~1.0.10" + }, + "description": "like touch(1) in node", + "devDependencies": { + "mutate-fs": "^1.1.0", + "tap": "^10.7.0" + }, + "files": [ + "index.js", + "bin/nodetouch.js" + ], + "homepage": "https://github.com/isaacs/node-touch#readme", + "license": "ISC", + "name": "touch", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-touch.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap test/*.js --100 -J" + }, + "version": "3.1.0" +} diff --git a/node_modules/tough-cookie/LICENSE b/node_modules/tough-cookie/LICENSE new file mode 100644 index 0000000..22204e8 --- /dev/null +++ b/node_modules/tough-cookie/LICENSE @@ -0,0 +1,12 @@ +Copyright (c) 2015, Salesforce.com, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/tough-cookie/README.md b/node_modules/tough-cookie/README.md new file mode 100644 index 0000000..2dc9496 --- /dev/null +++ b/node_modules/tough-cookie/README.md @@ -0,0 +1,582 @@ +[RFC6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js + +[![npm package](https://nodei.co/npm/tough-cookie.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/tough-cookie/) + +[![Build Status](https://travis-ci.org/salesforce/tough-cookie.svg?branch=master)](https://travis-ci.org/salesforce/tough-cookie) + +# Synopsis + +``` javascript +var tough = require('tough-cookie'); +var Cookie = tough.Cookie; +var cookie = Cookie.parse(header); +cookie.value = 'somethingdifferent'; +header = cookie.toString(); + +var cookiejar = new tough.CookieJar(); +cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); +// ... +cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) { + res.headers['cookie'] = cookies.join('; '); +}); +``` + +# Installation + +It's _so_ easy! + +`npm install tough-cookie` + +Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken. + +## Version Support + +Support for versions of node.js will follow that of the [request](https://www.npmjs.com/package/request) module. + +# API + +## tough + +Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound". + +**Note**: prior to 1.0.x, several of these functions took a `strict` parameter. This has since been removed from the API as it was no longer necessary. + +### `parseDate(string)` + +Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. + +### `formatDate(date)` + +Format a Date into a RFC1123 string (the RFC6265-recommended format). + +### `canonicalDomain(str)` + +Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects). + +### `domainMatch(str,domStr[,canonicalize=true])` + +Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". + +The `canonicalize` parameter will run the other two parameters through `canonicalDomain` or not. + +### `defaultPath(path)` + +Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC. + +The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output. + +### `pathMatch(reqPath,cookiePath)` + +Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean. + +This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`. + +### `parse(cookieString[, options])` + +alias for `Cookie.parse(cookieString[, options])` + +### `fromJSON(string)` + +alias for `Cookie.fromJSON(string)` + +### `getPublicSuffix(hostname)` + +Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it. + +For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. + +For further information, see http://publicsuffix.org/. This module derives its list from that site. This call is currently a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [get() method](https://www.npmjs.com/package/psl#pslgetdomain). + +### `cookieCompare(a,b)` + +For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). The sort algorithm is, in order of precedence: + +* Longest `.path` +* oldest `.creation` (which has a 1ms precision, same as `Date`) +* lowest `.creationIndex` (to get beyond the 1ms precision) + +``` javascript +var cookies = [ /* unsorted array of Cookie objects */ ]; +cookies = cookies.sort(cookieCompare); +``` + +**Note**: Since JavaScript's `Date` is limited to a 1ms precision, cookies within the same milisecond are entirely possible. This is especially true when using the `now` option to `.setCookie()`. The `.creationIndex` property is a per-process global counter, assigned during construction with `new Cookie()`. This preserves the spirit of the RFC sorting: older cookies go first. This works great for `MemoryCookieStore`, since `Set-Cookie` headers are parsed in order, but may not be so great for distributed systems. Sophisticated `Store`s may wish to set this to some other _logical clock_ such that if cookies A and B are created in the same millisecond, but cookie A is created before cookie B, then `A.creationIndex < B.creationIndex`. If you want to alter the global counter, which you probably _shouldn't_ do, it's stored in `Cookie.cookiesCreated`. + +### `permuteDomain(domain)` + +Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores. + +### `permutePath(path)` + +Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores. + + +## Cookie + +Exported via `tough.Cookie`. + +### `Cookie.parse(cookieString[, options])` + +Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. + +The options parameter is not required and currently has only one property: + + * _loose_ - boolean - if `true` enable parsing of key-less cookies like `=abc` and `=`, which are not RFC-compliant. + +If options is not an object, it is ignored, which means you can use `Array#map` with it. + +Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: + +``` javascript +if (res.headers['set-cookie'] instanceof Array) + cookies = res.headers['set-cookie'].map(Cookie.parse); +else + cookies = [Cookie.parse(res.headers['set-cookie'])]; +``` + +_Note:_ in version 2.3.3, tough-cookie limited the number of spaces before the `=` to 256 characters. This limitation has since been removed. +See [Issue 92](https://github.com/salesforce/tough-cookie/issues/92) + +### Properties + +Cookie object properties: + + * _key_ - string - the name or key of the cookie (default "") + * _value_ - string - the value of the cookie (default "") + * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()` + * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()` + * _domain_ - string - the `Domain=` attribute of the cookie + * _path_ - string - the `Path=` of the cookie + * _secure_ - boolean - the `Secure` cookie flag + * _httpOnly_ - boolean - the `HttpOnly` cookie flag + * _sameSite_ - string - the `SameSite` cookie attribute (from [RFC6265bis]); must be one of `none`, `lax`, or `strict` + * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside) + * _creation_ - `Date` - when this cookie was constructed + * _creationIndex_ - number - set at construction, used to provide greater sort precision (please see `cookieCompare(a,b)` for a full explanation) + +After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes: + + * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied) + * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one. + * _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar + * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute. + +### `Cookie([{properties}])` + +Receives an options object that can contain any of the above Cookie properties, uses the default for unspecified properties. + +### `.toString()` + +encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`. + +### `.cookieString()` + +encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '='). + +### `.setExpires(String)` + +sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set. + +### `.setMaxAge(number)` + +sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly. + +### `.expiryTime([now=Date.now()])` + +### `.expiryDate([now=Date.now()])` + +expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. + +Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` parameter -- is used to offset the `.maxAge` attribute. + +If Expires (`.expires`) is set, that's returned. + +Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents). + +### `.TTL([now=Date.now()])` + +compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply. + +The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. + +### `.canonicalizedDomain()` + +### `.cdomain()` + +return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters. + +### `.toJSON()` + +For convenience in using `JSON.serialize(cookie)`. Returns a plain-old `Object` that can be JSON-serialized. + +Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`). + +**NOTE**: Custom `Cookie` properties will be discarded. In tough-cookie 1.x, since there was no `.toJSON` method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. + +### `Cookie.fromJSON(strOrObj)` + +Does the reverse of `cookie.toJSON()`. If passed a string, will `JSON.parse()` that first. + +Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are parsed via `Date.parse()`, not the tough-cookie `parseDate`, since it's JavaScript/JSON-y timestamps being handled at this layer. + +Returns `null` upon JSON parsing error. + +### `.clone()` + +Does a deep clone of this cookie, exactly implemented as `Cookie.fromJSON(cookie.toJSON())`. + +### `.validate()` + +Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive. + +validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct: + +``` javascript +if (cookie.validate() === true) { + // it's tasty +} else { + // yuck! +} +``` + + +## CookieJar + +Exported via `tough.CookieJar`. + +### `CookieJar([store],[options])` + +Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used. + +The `options` object can be omitted and can have the following properties: + + * _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk" + * _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name. + * _prefixSecurity_ - string - default `silent` - set to `'unsafe-disabled'`, `'silent'`, or `'strict'`. See [Cookie Prefixes] below. + * _allowSpecialUseDomain_ - boolean - default `false` - accepts special-use domain suffixes, such as `local`. Useful for testing purposes. + This is not in the standard, but is used sometimes on the web and is accepted by (most) browsers. + +Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods. + +### `.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))` + +Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.creation`, `.lastAccessed` and `.hostOnly` properties. + +The `options` object can be omitted and can have the following properties: + + * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. + * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. + * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies + * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option. + * _sameSiteContext_ - string - default unset - set to `'none'`, `'lax'`, or `'strict'` See [SameSite Cookies] below. + +As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual). + +### `.setCookieSync(cookieOrString, currentUrl, [{options}])` + +Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +### `.getCookies(currentUrl, [{options},] cb(err,cookies))` + +Retrieve the list of cookies that can be sent in a Cookie header for the current url. + +If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given. + +The `options` object can be omitted and can have the following properties: + + * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. + * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. + * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies + * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially). + * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the underlying store (the default `MemoryCookieStore` supports it). + * _sameSiteContext_ - string - default unset - Set this to `'none'`, `'lax'` or `'strict'` to enforce SameSite cookies upon retrival. See [SameSite Cookies] below. + +The `.lastAccessed` property of the returned cookies will have been updated. + +### `.getCookiesSync(currentUrl, [{options}])` + +Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +### `.getCookieString(...)` + +Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`. + +### `.getCookieStringSync(...)` + +Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +### `.getSetCookieStrings(...)` + +Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`. + +### `.getSetCookieStringsSync(...)` + +Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). + +### `.serialize(cb(err,serializedObject))` + +Serialize the Jar if the underlying store supports `.getAllCookies`. + +**NOTE**: Custom `Cookie` properties will be discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. + +See [Serialization Format]. + +### `.serializeSync()` + +Sync version of .serialize + +### `.toJSON()` + +Alias of .serializeSync() for the convenience of `JSON.stringify(cookiejar)`. + +### `CookieJar.deserialize(serialized, [store], cb(err,object))` + +A new Jar is created and the serialized Cookies are added to the underlying store. Each `Cookie` is added via `store.putCookie` in the order in which they appear in the serialization. + +The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. + +As a convenience, if `serialized` is a string, it is passed through `JSON.parse` first. If that throws an error, this is passed to the callback. + +### `CookieJar.deserializeSync(serialized, [store])` + +Sync version of `.deserialize`. _Note_ that the `store` must be synchronous for this to work. + +### `CookieJar.fromJSON(string)` + +Alias of `.deserializeSync` to provide consistency with `Cookie.fromJSON()`. + +### `.clone([store,]cb(err,newJar))` + +Produces a deep clone of this jar. Modifications to the original won't affect the clone, and vice versa. + +The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. Transferring between store types is supported so long as the source implements `.getAllCookies()` and the destination implements `.putCookie()`. + +### `.cloneSync([store])` + +Synchronous version of `.clone`, returning a new `CookieJar` instance. + +The `store` argument is optional, but must be a _synchronous_ `Store` instance if specified. If not passed, a new instance of `MemoryCookieStore` is used. + +The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls. + +### `.removeAllCookies(cb(err))` + +Removes all cookies from the jar. + +This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned. + +### `.removeAllCookiesSync()` + +Sync version of `.removeAllCookies()` + +## Store + +Base class for CookieJar stores. Available as `tough.Store`. + +## Store API + +The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores. + +Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. + +Stores are asynchronous by default, but if `store.synchronous` is set to `true`, then the `*Sync` methods on the of the containing `CookieJar` can be used (however, the continuation-passing style + +All `domain` parameters will have been normalized before calling. + +The Cookie store must have all of the following methods. + +### `store.findCookie(domain, path, key, cb(err,cookie))` + +Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned. + +Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error). + +### `store.findCookies(domain, path, cb(err,cookies))` + +Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above. + +If no cookies are found, the callback MUST be passed an empty array. + +The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done. + +As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only). + +### `store.putCookie(cookie, cb(err))` + +Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur. + +The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties. + +Pass an error if the cookie cannot be stored. + +### `store.updateCookie(oldCookie, newCookie, cb(err))` + +Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store. + +The `.lastAccessed` property will always be different between the two objects (to the precision possible via JavaScript's clock). Both `.creation` and `.creationIndex` are guaranteed to be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are selected for automatic deletion (e.g., least-recently-used, which is up to the store to implement). + +Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object. + +The `newCookie` and `oldCookie` objects MUST NOT be modified. + +Pass an error if the newCookie cannot be stored. + +### `store.removeCookie(domain, path, key, cb(err))` + +Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint). + +The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie. + +### `store.removeCookies(domain, path, cb(err))` + +Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed. + +Pass an error ONLY if removing any existing cookies failed. + +### `store.removeAllCookies(cb(err))` + +_Optional_. Removes all cookies from the store. + +Pass an error if one or more cookies can't be removed. + +**Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this. + +### `store.getAllCookies(cb(err, cookies))` + +_Optional_. Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure. + +Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail. + +Pass an error if retrieval fails. + +**Note**: not all Stores can implement this due to technical limitations, so it is optional. + +## MemoryCookieStore + +Inherits from `Store`. + +A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API. Supports serialization, `getAllCookies`, and `removeAllCookies`. + +## Community Cookie Stores + +These are some Store implementations authored and maintained by the community. They aren't official and we don't vouch for them but you may be interested to have a look: + +- [`db-cookie-store`](https://github.com/JSBizon/db-cookie-store): SQL including SQLite-based databases +- [`file-cookie-store`](https://github.com/JSBizon/file-cookie-store): Netscape cookie file format on disk +- [`redis-cookie-store`](https://github.com/benkroeger/redis-cookie-store): Redis +- [`tough-cookie-filestore`](https://github.com/mitsuru/tough-cookie-filestore): JSON on disk +- [`tough-cookie-web-storage-store`](https://github.com/exponentjs/tough-cookie-web-storage-store): DOM localStorage and sessionStorage + + +# Serialization Format + +**NOTE**: if you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`. + +```js + { + // The version of tough-cookie that serialized this jar. + version: 'tough-cookie@1.x.y', + + // add the store type, to make humans happy: + storeType: 'MemoryCookieStore', + + // CookieJar configuration: + rejectPublicSuffixes: true, + // ... future items go here + + // Gets filled from jar.store.getAllCookies(): + cookies: [ + { + key: 'string', + value: 'string', + // ... + /* other Cookie.serializableProperties go here */ + } + ] + } +``` + +# RFC6265bis + +Support for RFC6265bis revision 02 is being developed. Since this is a bit of an omnibus revision to the RFC6252, support is broken up into the functional areas. + +## Leave Secure Cookies Alone + +Not yet supported. + +This change makes it so that if a cookie is sent from the server to the client with a `Secure` attribute, the channel must also be secure or the cookie is ignored. + +## SameSite Cookies + +Supported. + +This change makes it possible for servers, and supporting clients, to mitigate certain types of CSRF attacks by disallowing `SameSite` cookies from being sent cross-origin. + +On the Cookie object itself, you can get/set the `.sameSite` attribute, which will be serialized into the `SameSite=` cookie attribute. When unset or `undefined`, no `SameSite=` attribute will be serialized. The valid values of this attribute are `'none'`, `'lax'`, or `'strict'`. Other values will be serialized as-is. + +When parsing cookies with a `SameSite` cookie attribute, values other than `'lax'` or `'strict'` are parsed as `'none'`. For example, `SomeCookie=SomeValue; SameSite=garbage` will parse so that `cookie.sameSite === 'none'`. + +In order to support SameSite cookies, you must provide a `sameSiteContext` option to _both_ `setCookie` and `getCookies`. Valid values for this option are just like for the Cookie object, but have particular meanings: +1. `'strict'` mode - If the request is on the same "site for cookies" (see the RFC draft for what this means), pass this option to add a layer of defense against CSRF. +2. `'lax'` mode - If the request is from another site, _but_ is directly because of navigation by the user, e.g., `` or ``, pass `sameSiteContext: 'lax'`. +3. `'none'` - Otherwise, pass `sameSiteContext: 'none'` (this indicates a cross-origin request). +4. unset/`undefined` - SameSite **will not** be enforced! This can be a valid use-case for when CSRF isn't in the threat model of the system being built. + +It is highly recommended that you read RFC 6265bis for fine details on SameSite cookies. In particular [Section 8.8](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-02#section-8.8) discusses security considerations and defense in depth. + +## Cookie Prefixes + +Supported. + +Cookie prefixes are a way to indicate that a given cookie was set with a set of attributes simply by inspecting the first few characters of the cookie's name. + +Cookie prefixes are defined in [Section 4.1.3 of 6265bis](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.3). Two prefixes are defined: + +1. `"__Secure-" Prefix`: If a cookie's name begins with a case-sensitive match for the string "__Secure-", then the cookie will have been set with a "Secure" attribute. +2. `"__Host-" Prefix`: If a cookie's name begins with a case-sensitive match for the string "__Host-", then the cookie will have been set with a "Secure" attribute, a "Path" attribute with a value of "/", and no "Domain" attribute. + +If `prefixSecurity` is enabled for `CookieJar`, then cookies that match the prefixes defined above but do not obey the attribute restrictions will not be added. + +You can define this functionality by passing in `prefixSecurity` option to `CookieJar`. It can be one of 3 values: + +1. `silent`: Enable cookie prefix checking but silently fail to add the cookie if conditions not met. Default. +2. `strict`: Enable cookie prefix checking and error out if conditions not met. +3. `unsafe-disabled`: Disable cookie prefix checking. + +Note that if `ignoreError` is passed in as `true` then the error will be silent regardless of `prefixSecurity` option (assuming it's enabled). + + +# Copyright and License + +BSD-3-Clause: + +```text + Copyright (c) 2015, Salesforce.com, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of Salesforce.com nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +``` diff --git a/node_modules/tough-cookie/lib/cookie.js b/node_modules/tough-cookie/lib/cookie.js new file mode 100644 index 0000000..a042893 --- /dev/null +++ b/node_modules/tough-cookie/lib/cookie.js @@ -0,0 +1,1671 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +"use strict"; +const punycode = require("punycode"); +const urlParse = require("url").parse; +const util = require("util"); +const pubsuffix = require("./pubsuffix-psl"); +const Store = require("./store").Store; +const MemoryCookieStore = require("./memstore").MemoryCookieStore; +const pathMatch = require("./pathMatch").pathMatch; +const VERSION = require("./version"); +const { fromCallback } = require("universalify"); + +// From RFC6265 S4.1.1 +// note that it excludes \x3B ";" +const COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; + +const CONTROL_CHARS = /[\x00-\x1F]/; + +// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in +// the "relaxed" mode, see: +// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 +const TERMINATORS = ["\n", "\r", "\0"]; + +// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' +// Note ';' is \x3B +const PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; + +// date-time parsing constants (RFC6265 S5.1.1) + +const DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; + +const MONTH_TO_NUM = { + jan: 0, + feb: 1, + mar: 2, + apr: 3, + may: 4, + jun: 5, + jul: 6, + aug: 7, + sep: 8, + oct: 9, + nov: 10, + dec: 11 +}; + +const MAX_TIME = 2147483647000; // 31-bit max +const MIN_TIME = 0; // 31-bit min +const SAME_SITE_CONTEXT_VAL_ERR = + 'Invalid sameSiteContext option for getCookies(); expected one of "strict", "lax", or "none"'; + +function checkSameSiteContext(value) { + const context = String(value).toLowerCase(); + if (context === "none" || context === "lax" || context === "strict") { + return context; + } else { + return null; + } +} + +const PrefixSecurityEnum = Object.freeze({ + SILENT: "silent", + STRICT: "strict", + DISABLED: "unsafe-disabled" +}); + +// Dumped from ip-regex@4.0.0, with the following changes: +// * all capturing groups converted to non-capturing -- "(?:)" +// * support for IPv6 Scoped Literal ("%eth1") removed +// * lowercase hexadecimal only +var IP_REGEX_LOWERCASE =/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9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|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/; + +/* + * Parses a Natural number (i.e., non-negative integer) with either the + * *DIGIT ( non-digit *OCTET ) + * or + * *DIGIT + * grammar (RFC6265 S5.1.1). + * + * The "trailingOK" boolean controls if the grammar accepts a + * "( non-digit *OCTET )" trailer. + */ +function parseDigits(token, minDigits, maxDigits, trailingOK) { + let count = 0; + while (count < token.length) { + const c = token.charCodeAt(count); + // "non-digit = %x00-2F / %x3A-FF" + if (c <= 0x2f || c >= 0x3a) { + break; + } + count++; + } + + // constrain to a minimum and maximum number of digits. + if (count < minDigits || count > maxDigits) { + return null; + } + + if (!trailingOK && count != token.length) { + return null; + } + + return parseInt(token.substr(0, count), 10); +} + +function parseTime(token) { + const parts = token.split(":"); + const result = [0, 0, 0]; + + /* RF6256 S5.1.1: + * time = hms-time ( non-digit *OCTET ) + * hms-time = time-field ":" time-field ":" time-field + * time-field = 1*2DIGIT + */ + + if (parts.length !== 3) { + return null; + } + + for (let i = 0; i < 3; i++) { + // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be + // followed by "( non-digit *OCTET )" so therefore the last time-field can + // have a trailer + const trailingOK = i == 2; + const num = parseDigits(parts[i], 1, 2, trailingOK); + if (num === null) { + return null; + } + result[i] = num; + } + + return result; +} + +function parseMonth(token) { + token = String(token) + .substr(0, 3) + .toLowerCase(); + const num = MONTH_TO_NUM[token]; + return num >= 0 ? num : null; +} + +/* + * RFC6265 S5.1.1 date parser (see RFC for full grammar) + */ +function parseDate(str) { + if (!str) { + return; + } + + /* RFC6265 S5.1.1: + * 2. Process each date-token sequentially in the order the date-tokens + * appear in the cookie-date + */ + const tokens = str.split(DATE_DELIM); + if (!tokens) { + return; + } + + let hour = null; + let minute = null; + let second = null; + let dayOfMonth = null; + let month = null; + let year = null; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i].trim(); + if (!token.length) { + continue; + } + + let result; + + /* 2.1. If the found-time flag is not set and the token matches the time + * production, set the found-time flag and set the hour- value, + * minute-value, and second-value to the numbers denoted by the digits in + * the date-token, respectively. Skip the remaining sub-steps and continue + * to the next date-token. + */ + if (second === null) { + result = parseTime(token); + if (result) { + hour = result[0]; + minute = result[1]; + second = result[2]; + continue; + } + } + + /* 2.2. If the found-day-of-month flag is not set and the date-token matches + * the day-of-month production, set the found-day-of- month flag and set + * the day-of-month-value to the number denoted by the date-token. Skip + * the remaining sub-steps and continue to the next date-token. + */ + if (dayOfMonth === null) { + // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" + result = parseDigits(token, 1, 2, true); + if (result !== null) { + dayOfMonth = result; + continue; + } + } + + /* 2.3. If the found-month flag is not set and the date-token matches the + * month production, set the found-month flag and set the month-value to + * the month denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (month === null) { + result = parseMonth(token); + if (result !== null) { + month = result; + continue; + } + } + + /* 2.4. If the found-year flag is not set and the date-token matches the + * year production, set the found-year flag and set the year-value to the + * number denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (year === null) { + // "year = 2*4DIGIT ( non-digit *OCTET )" + result = parseDigits(token, 2, 4, true); + if (result !== null) { + year = result; + /* From S5.1.1: + * 3. If the year-value is greater than or equal to 70 and less + * than or equal to 99, increment the year-value by 1900. + * 4. If the year-value is greater than or equal to 0 and less + * than or equal to 69, increment the year-value by 2000. + */ + if (year >= 70 && year <= 99) { + year += 1900; + } else if (year >= 0 && year <= 69) { + year += 2000; + } + } + } + } + + /* RFC 6265 S5.1.1 + * "5. Abort these steps and fail to parse the cookie-date if: + * * at least one of the found-day-of-month, found-month, found- + * year, or found-time flags is not set, + * * the day-of-month-value is less than 1 or greater than 31, + * * the year-value is less than 1601, + * * the hour-value is greater than 23, + * * the minute-value is greater than 59, or + * * the second-value is greater than 59. + * (Note that leap seconds cannot be represented in this syntax.)" + * + * So, in order as above: + */ + if ( + dayOfMonth === null || + month === null || + year === null || + second === null || + dayOfMonth < 1 || + dayOfMonth > 31 || + year < 1601 || + hour > 23 || + minute > 59 || + second > 59 + ) { + return; + } + + return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); +} + +function formatDate(date) { + return date.toUTCString(); +} + +// S5.1.2 Canonicalized Host Names +function canonicalDomain(str) { + if (str == null) { + return null; + } + str = str.trim().replace(/^\./, ""); // S4.1.2.3 & S5.2.3: ignore leading . + + // convert to IDN if any non-ASCII characters + if (punycode && /[^\u0001-\u007f]/.test(str)) { + str = punycode.toASCII(str); + } + + return str.toLowerCase(); +} + +// S5.1.3 Domain Matching +function domainMatch(str, domStr, canonicalize) { + if (str == null || domStr == null) { + return null; + } + if (canonicalize !== false) { + str = canonicalDomain(str); + domStr = canonicalDomain(domStr); + } + + /* + * S5.1.3: + * "A string domain-matches a given domain string if at least one of the + * following conditions hold:" + * + * " o The domain string and the string are identical. (Note that both the + * domain string and the string will have been canonicalized to lower case at + * this point)" + */ + if (str == domStr) { + return true; + } + + /* " o All of the following [three] conditions hold:" */ + + /* "* The domain string is a suffix of the string" */ + const idx = str.indexOf(domStr); + if (idx <= 0) { + return false; // it's a non-match (-1) or prefix (0) + } + + // next, check it's a proper suffix + // e.g., "a.b.c".indexOf("b.c") === 2 + // 5 === 3+2 + if (str.length !== domStr.length + idx) { + return false; // it's not a suffix + } + + /* " * The last character of the string that is not included in the + * domain string is a %x2E (".") character." */ + if (str.substr(idx-1,1) !== '.') { + return false; // doesn't align on "." + } + + /* " * The string is a host name (i.e., not an IP address)." */ + if (IP_REGEX_LOWERCASE.test(str)) { + return false; // it's an IP address + } + + return true; +} + +// RFC6265 S5.1.4 Paths and Path-Match + +/* + * "The user agent MUST use an algorithm equivalent to the following algorithm + * to compute the default-path of a cookie:" + * + * Assumption: the path (and not query part or absolute uri) is passed in. + */ +function defaultPath(path) { + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (!path || path.substr(0, 1) !== "/") { + return "/"; + } + + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if (path === "/") { + return path; + } + + const rightSlash = path.lastIndexOf("/"); + if (rightSlash === 0) { + return "/"; + } + + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return path.slice(0, rightSlash); +} + +function trimTerminator(str) { + for (let t = 0; t < TERMINATORS.length; t++) { + const terminatorIdx = str.indexOf(TERMINATORS[t]); + if (terminatorIdx !== -1) { + str = str.substr(0, terminatorIdx); + } + } + + return str; +} + +function parseCookiePair(cookiePair, looseMode) { + cookiePair = trimTerminator(cookiePair); + + let firstEq = cookiePair.indexOf("="); + if (looseMode) { + if (firstEq === 0) { + // '=' is immediately at start + cookiePair = cookiePair.substr(1); + firstEq = cookiePair.indexOf("="); // might still need to split on '=' + } + } else { + // non-loose mode + if (firstEq <= 0) { + // no '=' or is at start + return; // needs to have non-empty "cookie-name" + } + } + + let cookieName, cookieValue; + if (firstEq <= 0) { + cookieName = ""; + cookieValue = cookiePair.trim(); + } else { + cookieName = cookiePair.substr(0, firstEq).trim(); + cookieValue = cookiePair.substr(firstEq + 1).trim(); + } + + if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { + return; + } + + const c = new Cookie(); + c.key = cookieName; + c.value = cookieValue; + return c; +} + +function parse(str, options) { + if (!options || typeof options !== "object") { + options = {}; + } + str = str.trim(); + + // We use a regex to parse the "name-value-pair" part of S5.2 + const firstSemi = str.indexOf(";"); // S5.2 step 1 + const cookiePair = firstSemi === -1 ? str : str.substr(0, firstSemi); + const c = parseCookiePair(cookiePair, !!options.loose); + if (!c) { + return; + } + + if (firstSemi === -1) { + return c; + } + + // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question)." plus later on in the same section + // "discard the first ";" and trim". + const unparsed = str.slice(firstSemi + 1).trim(); + + // "If the unparsed-attributes string is empty, skip the rest of these + // steps." + if (unparsed.length === 0) { + return c; + } + + /* + * S5.2 says that when looping over the items "[p]rocess the attribute-name + * and attribute-value according to the requirements in the following + * subsections" for every item. Plus, for many of the individual attributes + * in S5.3 it says to use the "attribute-value of the last attribute in the + * cookie-attribute-list". Therefore, in this implementation, we overwrite + * the previous value. + */ + const cookie_avs = unparsed.split(";"); + while (cookie_avs.length) { + const av = cookie_avs.shift().trim(); + if (av.length === 0) { + // happens if ";;" appears + continue; + } + const av_sep = av.indexOf("="); + let av_key, av_value; + + if (av_sep === -1) { + av_key = av; + av_value = null; + } else { + av_key = av.substr(0, av_sep); + av_value = av.substr(av_sep + 1); + } + + av_key = av_key.trim().toLowerCase(); + + if (av_value) { + av_value = av_value.trim(); + } + + switch (av_key) { + case "expires": // S5.2.1 + if (av_value) { + const exp = parseDate(av_value); + // "If the attribute-value failed to parse as a cookie date, ignore the + // cookie-av." + if (exp) { + // over and underflow not realistically a concern: V8's getTime() seems to + // store something larger than a 32-bit time_t (even with 32-bit node) + c.expires = exp; + } + } + break; + + case "max-age": // S5.2.2 + if (av_value) { + // "If the first character of the attribute-value is not a DIGIT or a "-" + // character ...[or]... If the remainder of attribute-value contains a + // non-DIGIT character, ignore the cookie-av." + if (/^-?[0-9]+$/.test(av_value)) { + const delta = parseInt(av_value, 10); + // "If delta-seconds is less than or equal to zero (0), let expiry-time + // be the earliest representable date and time." + c.setMaxAge(delta); + } + } + break; + + case "domain": // S5.2.3 + // "If the attribute-value is empty, the behavior is undefined. However, + // the user agent SHOULD ignore the cookie-av entirely." + if (av_value) { + // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E + // (".") character." + const domain = av_value.trim().replace(/^\./, ""); + if (domain) { + // "Convert the cookie-domain to lower case." + c.domain = domain.toLowerCase(); + } + } + break; + + case "path": // S5.2.4 + /* + * "If the attribute-value is empty or if the first character of the + * attribute-value is not %x2F ("/"): + * Let cookie-path be the default-path. + * Otherwise: + * Let cookie-path be the attribute-value." + * + * We'll represent the default-path as null since it depends on the + * context of the parsing. + */ + c.path = av_value && av_value[0] === "/" ? av_value : null; + break; + + case "secure": // S5.2.5 + /* + * "If the attribute-name case-insensitively matches the string "Secure", + * the user agent MUST append an attribute to the cookie-attribute-list + * with an attribute-name of Secure and an empty attribute-value." + */ + c.secure = true; + break; + + case "httponly": // S5.2.6 -- effectively the same as 'secure' + c.httpOnly = true; + break; + + case "samesite": // RFC6265bis-02 S5.3.7 + const enforcement = av_value ? av_value.toLowerCase() : ""; + switch (enforcement) { + case "strict": + c.sameSite = "strict"; + break; + case "lax": + c.sameSite = "lax"; + break; + default: + // RFC6265bis-02 S5.3.7 step 1: + // "If cookie-av's attribute-value is not a case-insensitive match + // for "Strict" or "Lax", ignore the "cookie-av"." + // This effectively sets it to 'none' from the prototype. + break; + } + break; + + default: + c.extensions = c.extensions || []; + c.extensions.push(av); + break; + } + } + + return c; +} + +/** + * If the cookie-name begins with a case-sensitive match for the + * string "__Secure-", abort these steps and ignore the cookie + * entirely unless the cookie's secure-only-flag is true. + * @param cookie + * @returns boolean + */ +function isSecurePrefixConditionMet(cookie) { + return !cookie.key.startsWith("__Secure-") || cookie.secure; +} + +/** + * If the cookie-name begins with a case-sensitive match for the + * string "__Host-", abort these steps and ignore the cookie + * entirely unless the cookie meets all the following criteria: + * 1. The cookie's secure-only-flag is true. + * 2. The cookie's host-only-flag is true. + * 3. The cookie-attribute-list contains an attribute with an + * attribute-name of "Path", and the cookie's path is "/". + * @param cookie + * @returns boolean + */ +function isHostPrefixConditionMet(cookie) { + return ( + !cookie.key.startsWith("__Host-") || + (cookie.secure && + cookie.hostOnly && + cookie.path != null && + cookie.path === "/") + ); +} + +// avoid the V8 deoptimization monster! +function jsonParse(str) { + let obj; + try { + obj = JSON.parse(str); + } catch (e) { + return e; + } + return obj; +} + +function fromJSON(str) { + if (!str) { + return null; + } + + let obj; + if (typeof str === "string") { + obj = jsonParse(str); + if (obj instanceof Error) { + return null; + } + } else { + // assume it's an Object + obj = str; + } + + const c = new Cookie(); + for (let i = 0; i < Cookie.serializableProperties.length; i++) { + const prop = Cookie.serializableProperties[i]; + if (obj[prop] === undefined || obj[prop] === cookieDefaults[prop]) { + continue; // leave as prototype default + } + + if (prop === "expires" || prop === "creation" || prop === "lastAccessed") { + if (obj[prop] === null) { + c[prop] = null; + } else { + c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); + } + } else { + c[prop] = obj[prop]; + } + } + + return c; +} + +/* Section 5.4 part 2: + * "* Cookies with longer paths are listed before cookies with + * shorter paths. + * + * * Among cookies that have equal-length path fields, cookies with + * earlier creation-times are listed before cookies with later + * creation-times." + */ + +function cookieCompare(a, b) { + let cmp = 0; + + // descending for length: b CMP a + const aPathLen = a.path ? a.path.length : 0; + const bPathLen = b.path ? b.path.length : 0; + cmp = bPathLen - aPathLen; + if (cmp !== 0) { + return cmp; + } + + // ascending for time: a CMP b + const aTime = a.creation ? a.creation.getTime() : MAX_TIME; + const bTime = b.creation ? b.creation.getTime() : MAX_TIME; + cmp = aTime - bTime; + if (cmp !== 0) { + return cmp; + } + + // break ties for the same millisecond (precision of JavaScript's clock) + cmp = a.creationIndex - b.creationIndex; + + return cmp; +} + +// Gives the permutation of all possible pathMatch()es of a given path. The +// array is in longest-to-shortest order. Handy for indexing. +function permutePath(path) { + if (path === "/") { + return ["/"]; + } + const permutations = [path]; + while (path.length > 1) { + const lindex = path.lastIndexOf("/"); + if (lindex === 0) { + break; + } + path = path.substr(0, lindex); + permutations.push(path); + } + permutations.push("/"); + return permutations; +} + +function getCookieContext(url) { + if (url instanceof Object) { + return url; + } + // NOTE: decodeURI will throw on malformed URIs (see GH-32). + // Therefore, we will just skip decoding for such URIs. + try { + url = decodeURI(url); + } catch (err) { + // Silently swallow error + } + + return urlParse(url); +} + +const cookieDefaults = { + // the order in which the RFC has them: + key: "", + value: "", + expires: "Infinity", + maxAge: null, + domain: null, + path: null, + secure: false, + httpOnly: false, + extensions: null, + // set by the CookieJar: + hostOnly: null, + pathIsDefault: null, + creation: null, + lastAccessed: null, + sameSite: "none" +}; + +class Cookie { + constructor(options = {}) { + if (util.inspect.custom) { + this[util.inspect.custom] = this.inspect; + } + + Object.assign(this, cookieDefaults, options); + this.creation = this.creation || new Date(); + + // used to break creation ties in cookieCompare(): + Object.defineProperty(this, "creationIndex", { + configurable: false, + enumerable: false, // important for assert.deepEqual checks + writable: true, + value: ++Cookie.cookiesCreated + }); + } + + inspect() { + const now = Date.now(); + const hostOnly = this.hostOnly != null ? this.hostOnly : "?"; + const createAge = this.creation + ? `${now - this.creation.getTime()}ms` + : "?"; + const accessAge = this.lastAccessed + ? `${now - this.lastAccessed.getTime()}ms` + : "?"; + return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`; + } + + toJSON() { + const obj = {}; + + for (const prop of Cookie.serializableProperties) { + if (this[prop] === cookieDefaults[prop]) { + continue; // leave as prototype default + } + + if ( + prop === "expires" || + prop === "creation" || + prop === "lastAccessed" + ) { + if (this[prop] === null) { + obj[prop] = null; + } else { + obj[prop] = + this[prop] == "Infinity" // intentionally not === + ? "Infinity" + : this[prop].toISOString(); + } + } else if (prop === "maxAge") { + if (this[prop] !== null) { + // again, intentionally not === + obj[prop] = + this[prop] == Infinity || this[prop] == -Infinity + ? this[prop].toString() + : this[prop]; + } + } else { + if (this[prop] !== cookieDefaults[prop]) { + obj[prop] = this[prop]; + } + } + } + + return obj; + } + + clone() { + return fromJSON(this.toJSON()); + } + + validate() { + if (!COOKIE_OCTETS.test(this.value)) { + return false; + } + if ( + this.expires != Infinity && + !(this.expires instanceof Date) && + !parseDate(this.expires) + ) { + return false; + } + if (this.maxAge != null && this.maxAge <= 0) { + return false; // "Max-Age=" non-zero-digit *DIGIT + } + if (this.path != null && !PATH_VALUE.test(this.path)) { + return false; + } + + const cdomain = this.cdomain(); + if (cdomain) { + if (cdomain.match(/\.$/)) { + return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this + } + const suffix = pubsuffix.getPublicSuffix(cdomain); + if (suffix == null) { + // it's a public suffix + return false; + } + } + return true; + } + + setExpires(exp) { + if (exp instanceof Date) { + this.expires = exp; + } else { + this.expires = parseDate(exp) || "Infinity"; + } + } + + setMaxAge(age) { + if (age === Infinity || age === -Infinity) { + this.maxAge = age.toString(); // so JSON.stringify() works + } else { + this.maxAge = age; + } + } + + cookieString() { + let val = this.value; + if (val == null) { + val = ""; + } + if (this.key === "") { + return val; + } + return `${this.key}=${val}`; + } + + // gives Set-Cookie header format + toString() { + let str = this.cookieString(); + + if (this.expires != Infinity) { + if (this.expires instanceof Date) { + str += `; Expires=${formatDate(this.expires)}`; + } else { + str += `; Expires=${this.expires}`; + } + } + + if (this.maxAge != null && this.maxAge != Infinity) { + str += `; Max-Age=${this.maxAge}`; + } + + if (this.domain && !this.hostOnly) { + str += `; Domain=${this.domain}`; + } + if (this.path) { + str += `; Path=${this.path}`; + } + + if (this.secure) { + str += "; Secure"; + } + if (this.httpOnly) { + str += "; HttpOnly"; + } + if (this.sameSite && this.sameSite !== "none") { + const ssCanon = Cookie.sameSiteCanonical[this.sameSite.toLowerCase()]; + str += `; SameSite=${ssCanon ? ssCanon : this.sameSite}`; + } + if (this.extensions) { + this.extensions.forEach(ext => { + str += `; ${ext}`; + }); + } + + return str; + } + + // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere) + // S5.3 says to give the "latest representable date" for which we use Infinity + // For "expired" we use 0 + TTL(now) { + /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires + * attribute, the Max-Age attribute has precedence and controls the + * expiration date of the cookie. + * (Concurs with S5.3 step 3) + */ + if (this.maxAge != null) { + return this.maxAge <= 0 ? 0 : this.maxAge * 1000; + } + + let expires = this.expires; + if (expires != Infinity) { + if (!(expires instanceof Date)) { + expires = parseDate(expires) || Infinity; + } + + if (expires == Infinity) { + return Infinity; + } + + return expires.getTime() - (now || Date.now()); + } + + return Infinity; + } + + // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere) + expiryTime(now) { + if (this.maxAge != null) { + const relativeTo = now || this.creation || new Date(); + const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000; + return relativeTo.getTime() + age; + } + + if (this.expires == Infinity) { + return Infinity; + } + return this.expires.getTime(); + } + + // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere), except it returns a Date + expiryDate(now) { + const millisec = this.expiryTime(now); + if (millisec == Infinity) { + return new Date(MAX_TIME); + } else if (millisec == -Infinity) { + return new Date(MIN_TIME); + } else { + return new Date(millisec); + } + } + + // This replaces the "persistent-flag" parts of S5.3 step 3 + isPersistent() { + return this.maxAge != null || this.expires != Infinity; + } + + // Mostly S5.1.2 and S5.2.3: + canonicalizedDomain() { + if (this.domain == null) { + return null; + } + return canonicalDomain(this.domain); + } + + cdomain() { + return this.canonicalizedDomain(); + } +} + +Cookie.cookiesCreated = 0; +Cookie.parse = parse; +Cookie.fromJSON = fromJSON; +Cookie.serializableProperties = Object.keys(cookieDefaults); +Cookie.sameSiteLevel = { + strict: 3, + lax: 2, + none: 1 +}; + +Cookie.sameSiteCanonical = { + strict: "Strict", + lax: "Lax" +}; + +function getNormalizedPrefixSecurity(prefixSecurity) { + if (prefixSecurity != null) { + const normalizedPrefixSecurity = prefixSecurity.toLowerCase(); + /* The three supported options */ + switch (normalizedPrefixSecurity) { + case PrefixSecurityEnum.STRICT: + case PrefixSecurityEnum.SILENT: + case PrefixSecurityEnum.DISABLED: + return normalizedPrefixSecurity; + } + } + /* Default is SILENT */ + return PrefixSecurityEnum.SILENT; +} + +class CookieJar { + constructor(store, options = { rejectPublicSuffixes: true }) { + if (typeof options === "boolean") { + options = { rejectPublicSuffixes: options }; + } + this.rejectPublicSuffixes = options.rejectPublicSuffixes; + this.enableLooseMode = !!options.looseMode; + this.allowSpecialUseDomain = !!options.allowSpecialUseDomain; + this.store = store || new MemoryCookieStore(); + this.prefixSecurity = getNormalizedPrefixSecurity(options.prefixSecurity); + this._cloneSync = syncWrap("clone"); + this._importCookiesSync = syncWrap("_importCookies"); + this.getCookiesSync = syncWrap("getCookies"); + this.getCookieStringSync = syncWrap("getCookieString"); + this.getSetCookieStringsSync = syncWrap("getSetCookieStrings"); + this.removeAllCookiesSync = syncWrap("removeAllCookies"); + this.setCookieSync = syncWrap("setCookie"); + this.serializeSync = syncWrap("serialize"); + } + + setCookie(cookie, url, options, cb) { + let err; + const context = getCookieContext(url); + if (typeof options === "function") { + cb = options; + options = {}; + } + + const host = canonicalDomain(context.hostname); + const loose = options.loose || this.enableLooseMode; + + let sameSiteContext = null; + if (options.sameSiteContext) { + sameSiteContext = checkSameSiteContext(options.sameSiteContext); + if (!sameSiteContext) { + return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); + } + } + + // S5.3 step 1 + if (typeof cookie === "string" || cookie instanceof String) { + cookie = Cookie.parse(cookie, { loose: loose }); + if (!cookie) { + err = new Error("Cookie failed to parse"); + return cb(options.ignoreError ? null : err); + } + } else if (!(cookie instanceof Cookie)) { + // If you're seeing this error, and are passing in a Cookie object, + // it *might* be a Cookie object from another loaded version of tough-cookie. + err = new Error( + "First argument to setCookie must be a Cookie object or string" + ); + return cb(options.ignoreError ? null : err); + } + + // S5.3 step 2 + const now = options.now || new Date(); // will assign later to save effort in the face of errors + + // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() + + // S5.3 step 4: NOOP; domain is null by default + + // S5.3 step 5: public suffixes + if (this.rejectPublicSuffixes && cookie.domain) { + const suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); + if (suffix == null) { + // e.g. "com" + err = new Error("Cookie has domain set to a public suffix"); + return cb(options.ignoreError ? null : err); + } + } + + // S5.3 step 6: + if (cookie.domain) { + if (!domainMatch(host, cookie.cdomain(), false)) { + err = new Error( + `Cookie not in this host's domain. Cookie:${cookie.cdomain()} Request:${host}` + ); + return cb(options.ignoreError ? null : err); + } + + if (cookie.hostOnly == null) { + // don't reset if already set + cookie.hostOnly = false; + } + } else { + cookie.hostOnly = true; + cookie.domain = host; + } + + //S5.2.4 If the attribute-value is empty or if the first character of the + //attribute-value is not %x2F ("/"): + //Let cookie-path be the default-path. + if (!cookie.path || cookie.path[0] !== "/") { + cookie.path = defaultPath(context.pathname); + cookie.pathIsDefault = true; + } + + // S5.3 step 8: NOOP; secure attribute + // S5.3 step 9: NOOP; httpOnly attribute + + // S5.3 step 10 + if (options.http === false && cookie.httpOnly) { + err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + + // 6252bis-02 S5.4 Step 13 & 14: + if (cookie.sameSite !== "none" && sameSiteContext) { + // "If the cookie's "same-site-flag" is not "None", and the cookie + // is being set from a context whose "site for cookies" is not an + // exact match for request-uri's host's registered domain, then + // abort these steps and ignore the newly created cookie entirely." + if (sameSiteContext === "none") { + err = new Error( + "Cookie is SameSite but this is a cross-origin request" + ); + return cb(options.ignoreError ? null : err); + } + } + + /* 6265bis-02 S5.4 Steps 15 & 16 */ + const ignoreErrorForPrefixSecurity = + this.prefixSecurity === PrefixSecurityEnum.SILENT; + const prefixSecurityDisabled = + this.prefixSecurity === PrefixSecurityEnum.DISABLED; + /* If prefix checking is not disabled ...*/ + if (!prefixSecurityDisabled) { + let errorFound = false; + let errorMsg; + /* Check secure prefix condition */ + if (!isSecurePrefixConditionMet(cookie)) { + errorFound = true; + errorMsg = "Cookie has __Secure prefix but Secure attribute is not set"; + } else if (!isHostPrefixConditionMet(cookie)) { + /* Check host prefix condition */ + errorFound = true; + errorMsg = + "Cookie has __Host prefix but either Secure or HostOnly attribute is not set or Path is not '/'"; + } + if (errorFound) { + return cb( + options.ignoreError || ignoreErrorForPrefixSecurity + ? null + : new Error(errorMsg) + ); + } + } + + const store = this.store; + + if (!store.updateCookie) { + store.updateCookie = function(oldCookie, newCookie, cb) { + this.putCookie(newCookie, cb); + }; + } + + function withCookie(err, oldCookie) { + if (err) { + return cb(err); + } + + const next = function(err) { + if (err) { + return cb(err); + } else { + cb(null, cookie); + } + }; + + if (oldCookie) { + // S5.3 step 11 - "If the cookie store contains a cookie with the same name, + // domain, and path as the newly created cookie:" + if (options.http === false && oldCookie.httpOnly) { + // step 11.2 + err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + cookie.creation = oldCookie.creation; // step 11.3 + cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker + cookie.lastAccessed = now; + // Step 11.4 (delete cookie) is implied by just setting the new one: + store.updateCookie(oldCookie, cookie, next); // step 12 + } else { + cookie.creation = cookie.lastAccessed = now; + store.putCookie(cookie, next); // step 12 + } + } + + store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); + } + + // RFC6365 S5.4 + getCookies(url, options, cb) { + const context = getCookieContext(url); + if (typeof options === "function") { + cb = options; + options = {}; + } + + const host = canonicalDomain(context.hostname); + const path = context.pathname || "/"; + + let secure = options.secure; + if ( + secure == null && + context.protocol && + (context.protocol == "https:" || context.protocol == "wss:") + ) { + secure = true; + } + + let sameSiteLevel = 0; + if (options.sameSiteContext) { + const sameSiteContext = checkSameSiteContext(options.sameSiteContext); + sameSiteLevel = Cookie.sameSiteLevel[sameSiteContext]; + if (!sameSiteLevel) { + return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); + } + } + + let http = options.http; + if (http == null) { + http = true; + } + + const now = options.now || Date.now(); + const expireCheck = options.expire !== false; + const allPaths = !!options.allPaths; + const store = this.store; + + function matchingCookie(c) { + // "Either: + // The cookie's host-only-flag is true and the canonicalized + // request-host is identical to the cookie's domain. + // Or: + // The cookie's host-only-flag is false and the canonicalized + // request-host domain-matches the cookie's domain." + if (c.hostOnly) { + if (c.domain != host) { + return false; + } + } else { + if (!domainMatch(host, c.domain, false)) { + return false; + } + } + + // "The request-uri's path path-matches the cookie's path." + if (!allPaths && !pathMatch(path, c.path)) { + return false; + } + + // "If the cookie's secure-only-flag is true, then the request-uri's + // scheme must denote a "secure" protocol" + if (c.secure && !secure) { + return false; + } + + // "If the cookie's http-only-flag is true, then exclude the cookie if the + // cookie-string is being generated for a "non-HTTP" API" + if (c.httpOnly && !http) { + return false; + } + + // RFC6265bis-02 S5.3.7 + if (sameSiteLevel) { + const cookieLevel = Cookie.sameSiteLevel[c.sameSite || "none"]; + if (cookieLevel > sameSiteLevel) { + // only allow cookies at or below the request level + return false; + } + } + + // deferred from S5.3 + // non-RFC: allow retention of expired cookies by choice + if (expireCheck && c.expiryTime() <= now) { + store.removeCookie(c.domain, c.path, c.key, () => {}); // result ignored + return false; + } + + return true; + } + + store.findCookies( + host, + allPaths ? null : path, + this.allowSpecialUseDomain, + (err, cookies) => { + if (err) { + return cb(err); + } + + cookies = cookies.filter(matchingCookie); + + // sorting of S5.4 part 2 + if (options.sort !== false) { + cookies = cookies.sort(cookieCompare); + } + + // S5.4 part 3 + const now = new Date(); + for (const cookie of cookies) { + cookie.lastAccessed = now; + } + // TODO persist lastAccessed + + cb(null, cookies); + } + ); + } + + getCookieString(...args) { + const cb = args.pop(); + const next = function(err, cookies) { + if (err) { + cb(err); + } else { + cb( + null, + cookies + .sort(cookieCompare) + .map(c => c.cookieString()) + .join("; ") + ); + } + }; + args.push(next); + this.getCookies.apply(this, args); + } + + getSetCookieStrings(...args) { + const cb = args.pop(); + const next = function(err, cookies) { + if (err) { + cb(err); + } else { + cb( + null, + cookies.map(c => { + return c.toString(); + }) + ); + } + }; + args.push(next); + this.getCookies.apply(this, args); + } + + serialize(cb) { + let type = this.store.constructor.name; + if (type === "Object") { + type = null; + } + + // update README.md "Serialization Format" if you change this, please! + const serialized = { + // The version of tough-cookie that serialized this jar. Generally a good + // practice since future versions can make data import decisions based on + // known past behavior. When/if this matters, use `semver`. + version: `tough-cookie@${VERSION}`, + + // add the store type, to make humans happy: + storeType: type, + + // CookieJar configuration: + rejectPublicSuffixes: !!this.rejectPublicSuffixes, + + // this gets filled from getAllCookies: + cookies: [] + }; + + if ( + !( + this.store.getAllCookies && + typeof this.store.getAllCookies === "function" + ) + ) { + return cb( + new Error( + "store does not support getAllCookies and cannot be serialized" + ) + ); + } + + this.store.getAllCookies((err, cookies) => { + if (err) { + return cb(err); + } + + serialized.cookies = cookies.map(cookie => { + // convert to serialized 'raw' cookies + cookie = cookie instanceof Cookie ? cookie.toJSON() : cookie; + + // Remove the index so new ones get assigned during deserialization + delete cookie.creationIndex; + + return cookie; + }); + + return cb(null, serialized); + }); + } + + toJSON() { + return this.serializeSync(); + } + + // use the class method CookieJar.deserialize instead of calling this directly + _importCookies(serialized, cb) { + let cookies = serialized.cookies; + if (!cookies || !Array.isArray(cookies)) { + return cb(new Error("serialized jar has no cookies array")); + } + cookies = cookies.slice(); // do not modify the original + + const putNext = err => { + if (err) { + return cb(err); + } + + if (!cookies.length) { + return cb(err, this); + } + + let cookie; + try { + cookie = fromJSON(cookies.shift()); + } catch (e) { + return cb(e); + } + + if (cookie === null) { + return putNext(null); // skip this cookie + } + + this.store.putCookie(cookie, putNext); + }; + + putNext(); + } + + clone(newStore, cb) { + if (arguments.length === 1) { + cb = newStore; + newStore = null; + } + + this.serialize((err, serialized) => { + if (err) { + return cb(err); + } + CookieJar.deserialize(serialized, newStore, cb); + }); + } + + cloneSync(newStore) { + if (arguments.length === 0) { + return this._cloneSync(); + } + if (!newStore.synchronous) { + throw new Error( + "CookieJar clone destination store is not synchronous; use async API instead." + ); + } + return this._cloneSync(newStore); + } + + removeAllCookies(cb) { + const store = this.store; + + // Check that the store implements its own removeAllCookies(). The default + // implementation in Store will immediately call the callback with a "not + // implemented" Error. + if ( + typeof store.removeAllCookies === "function" && + store.removeAllCookies !== Store.prototype.removeAllCookies + ) { + return store.removeAllCookies(cb); + } + + store.getAllCookies((err, cookies) => { + if (err) { + return cb(err); + } + + if (cookies.length === 0) { + return cb(null); + } + + let completedCount = 0; + const removeErrors = []; + + function removeCookieCb(removeErr) { + if (removeErr) { + removeErrors.push(removeErr); + } + + completedCount++; + + if (completedCount === cookies.length) { + return cb(removeErrors.length ? removeErrors[0] : null); + } + } + + cookies.forEach(cookie => { + store.removeCookie( + cookie.domain, + cookie.path, + cookie.key, + removeCookieCb + ); + }); + }); + } + + static deserialize(strOrObj, store, cb) { + if (arguments.length !== 3) { + // store is optional + cb = store; + store = null; + } + + let serialized; + if (typeof strOrObj === "string") { + serialized = jsonParse(strOrObj); + if (serialized instanceof Error) { + return cb(serialized); + } + } else { + serialized = strOrObj; + } + + const jar = new CookieJar(store, serialized.rejectPublicSuffixes); + jar._importCookies(serialized, err => { + if (err) { + return cb(err); + } + cb(null, jar); + }); + } + + static deserializeSync(strOrObj, store) { + const serialized = + typeof strOrObj === "string" ? JSON.parse(strOrObj) : strOrObj; + const jar = new CookieJar(store, serialized.rejectPublicSuffixes); + + // catch this mistake early: + if (!jar.store.synchronous) { + throw new Error( + "CookieJar store is not synchronous; use async API instead." + ); + } + + jar._importCookiesSync(serialized); + return jar; + } +} +CookieJar.fromJSON = CookieJar.deserializeSync; + +[ + "_importCookies", + "clone", + "getCookies", + "getCookieString", + "getSetCookieStrings", + "removeAllCookies", + "serialize", + "setCookie" +].forEach(name => { + CookieJar.prototype[name] = fromCallback(CookieJar.prototype[name]); +}); +CookieJar.deserialize = fromCallback(CookieJar.deserialize); + +// Use a closure to provide a true imperative API for synchronous stores. +function syncWrap(method) { + return function(...args) { + if (!this.store.synchronous) { + throw new Error( + "CookieJar store is not synchronous; use async API instead." + ); + } + + let syncErr, syncResult; + this[method](...args, (err, result) => { + syncErr = err; + syncResult = result; + }); + + if (syncErr) { + throw syncErr; + } + return syncResult; + }; +} + +exports.version = VERSION; +exports.CookieJar = CookieJar; +exports.Cookie = Cookie; +exports.Store = Store; +exports.MemoryCookieStore = MemoryCookieStore; +exports.parseDate = parseDate; +exports.formatDate = formatDate; +exports.parse = parse; +exports.fromJSON = fromJSON; +exports.domainMatch = domainMatch; +exports.defaultPath = defaultPath; +exports.pathMatch = pathMatch; +exports.getPublicSuffix = pubsuffix.getPublicSuffix; +exports.cookieCompare = cookieCompare; +exports.permuteDomain = require("./permuteDomain").permuteDomain; +exports.permutePath = permutePath; +exports.canonicalDomain = canonicalDomain; +exports.PrefixSecurityEnum = PrefixSecurityEnum; diff --git a/node_modules/tough-cookie/lib/memstore.js b/node_modules/tough-cookie/lib/memstore.js new file mode 100644 index 0000000..912eead --- /dev/null +++ b/node_modules/tough-cookie/lib/memstore.js @@ -0,0 +1,190 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +"use strict"; +const { fromCallback } = require("universalify"); +const Store = require("./store").Store; +const permuteDomain = require("./permuteDomain").permuteDomain; +const pathMatch = require("./pathMatch").pathMatch; +const util = require("util"); + +class MemoryCookieStore extends Store { + constructor() { + super(); + this.synchronous = true; + this.idx = {}; + if (util.inspect.custom) { + this[util.inspect.custom] = this.inspect; + } + } + + inspect() { + return `{ idx: ${util.inspect(this.idx, false, 2)} }`; + } + + findCookie(domain, path, key, cb) { + if (!this.idx[domain]) { + return cb(null, undefined); + } + if (!this.idx[domain][path]) { + return cb(null, undefined); + } + return cb(null, this.idx[domain][path][key] || null); + } + findCookies(domain, path, allowSpecialUseDomain, cb) { + const results = []; + if (typeof allowSpecialUseDomain === "function") { + cb = allowSpecialUseDomain; + allowSpecialUseDomain = false; + } + if (!domain) { + return cb(null, []); + } + + let pathMatcher; + if (!path) { + // null means "all paths" + pathMatcher = function matchAll(domainIndex) { + for (const curPath in domainIndex) { + const pathIndex = domainIndex[curPath]; + for (const key in pathIndex) { + results.push(pathIndex[key]); + } + } + }; + } else { + pathMatcher = function matchRFC(domainIndex) { + //NOTE: we should use path-match algorithm from S5.1.4 here + //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) + Object.keys(domainIndex).forEach(cookiePath => { + if (pathMatch(path, cookiePath)) { + const pathIndex = domainIndex[cookiePath]; + for (const key in pathIndex) { + results.push(pathIndex[key]); + } + } + }); + }; + } + + const domains = permuteDomain(domain, allowSpecialUseDomain) || [domain]; + const idx = this.idx; + domains.forEach(curDomain => { + const domainIndex = idx[curDomain]; + if (!domainIndex) { + return; + } + pathMatcher(domainIndex); + }); + + cb(null, results); + } + + putCookie(cookie, cb) { + if (!this.idx[cookie.domain]) { + this.idx[cookie.domain] = {}; + } + if (!this.idx[cookie.domain][cookie.path]) { + this.idx[cookie.domain][cookie.path] = {}; + } + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); + } + updateCookie(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie, cb); + } + removeCookie(domain, path, key, cb) { + if ( + this.idx[domain] && + this.idx[domain][path] && + this.idx[domain][path][key] + ) { + delete this.idx[domain][path][key]; + } + cb(null); + } + removeCookies(domain, path, cb) { + if (this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); + } + removeAllCookies(cb) { + this.idx = {}; + return cb(null); + } + getAllCookies(cb) { + const cookies = []; + const idx = this.idx; + + const domains = Object.keys(idx); + domains.forEach(domain => { + const paths = Object.keys(idx[domain]); + paths.forEach(path => { + const keys = Object.keys(idx[domain][path]); + keys.forEach(key => { + if (key !== null) { + cookies.push(idx[domain][path][key]); + } + }); + }); + }); + + // Sort by creationIndex so deserializing retains the creation order. + // When implementing your own store, this SHOULD retain the order too + cookies.sort((a, b) => { + return (a.creationIndex || 0) - (b.creationIndex || 0); + }); + + cb(null, cookies); + } +} + +[ + "findCookie", + "findCookies", + "putCookie", + "updateCookie", + "removeCookie", + "removeCookies", + "removeAllCookies", + "getAllCookies" +].forEach(name => { + MemoryCookieStore[name] = fromCallback(MemoryCookieStore.prototype[name]); +}); + +exports.MemoryCookieStore = MemoryCookieStore; diff --git a/node_modules/tough-cookie/lib/pathMatch.js b/node_modules/tough-cookie/lib/pathMatch.js new file mode 100644 index 0000000..16ff63e --- /dev/null +++ b/node_modules/tough-cookie/lib/pathMatch.js @@ -0,0 +1,61 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +"use strict"; +/* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ +function pathMatch(reqPath, cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; + } + + const idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } + + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length, 1) === "/") { + return true; + } + } + + return false; +} + +exports.pathMatch = pathMatch; diff --git a/node_modules/tough-cookie/lib/permuteDomain.js b/node_modules/tough-cookie/lib/permuteDomain.js new file mode 100644 index 0000000..78e6cad --- /dev/null +++ b/node_modules/tough-cookie/lib/permuteDomain.js @@ -0,0 +1,70 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +"use strict"; +const pubsuffix = require("./pubsuffix-psl"); + +// Gives the permutation of all possible domainMatch()es of a given domain. The +// array is in shortest-to-longest order. Handy for indexing. +const SPECIAL_USE_DOMAINS = ["local"]; // RFC 6761 +function permuteDomain(domain, allowSpecialUseDomain) { + let pubSuf = null; + if (allowSpecialUseDomain) { + const domainParts = domain.split("."); + if (SPECIAL_USE_DOMAINS.includes(domainParts[domainParts.length - 1])) { + pubSuf = `${domainParts[domainParts.length - 2]}.${ + domainParts[domainParts.length - 1] + }`; + } else { + pubSuf = pubsuffix.getPublicSuffix(domain); + } + } else { + pubSuf = pubsuffix.getPublicSuffix(domain); + } + + if (!pubSuf) { + return null; + } + if (pubSuf == domain) { + return [domain]; + } + + const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" + const parts = prefix.split(".").reverse(); + let cur = pubSuf; + const permutations = [cur]; + while (parts.length) { + cur = `${parts.shift()}.${cur}`; + permutations.push(cur); + } + return permutations; +} + +exports.permuteDomain = permuteDomain; diff --git a/node_modules/tough-cookie/lib/pubsuffix-psl.js b/node_modules/tough-cookie/lib/pubsuffix-psl.js new file mode 100644 index 0000000..93a8577 --- /dev/null +++ b/node_modules/tough-cookie/lib/pubsuffix-psl.js @@ -0,0 +1,38 @@ +/*! + * Copyright (c) 2018, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +"use strict"; +const psl = require("psl"); + +function getPublicSuffix(domain) { + return psl.get(domain); +} + +exports.getPublicSuffix = getPublicSuffix; diff --git a/node_modules/tough-cookie/lib/store.js b/node_modules/tough-cookie/lib/store.js new file mode 100644 index 0000000..2ed0259 --- /dev/null +++ b/node_modules/tough-cookie/lib/store.js @@ -0,0 +1,76 @@ +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +"use strict"; +/*jshint unused:false */ + +class Store { + constructor() { + this.synchronous = false; + } + + findCookie(domain, path, key, cb) { + throw new Error("findCookie is not implemented"); + } + + findCookies(domain, path, allowSpecialUseDomain, cb) { + throw new Error("findCookies is not implemented"); + } + + putCookie(cookie, cb) { + throw new Error("putCookie is not implemented"); + } + + updateCookie(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error("updateCookie is not implemented"); + } + + removeCookie(domain, path, key, cb) { + throw new Error("removeCookie is not implemented"); + } + + removeCookies(domain, path, cb) { + throw new Error("removeCookies is not implemented"); + } + + removeAllCookies(cb) { + throw new Error("removeAllCookies is not implemented"); + } + + getAllCookies(cb) { + throw new Error( + "getAllCookies is not implemented (therefore jar cannot be serialized)" + ); + } +} + +exports.Store = Store; diff --git a/node_modules/tough-cookie/lib/version.js b/node_modules/tough-cookie/lib/version.js new file mode 100644 index 0000000..e52f25b --- /dev/null +++ b/node_modules/tough-cookie/lib/version.js @@ -0,0 +1,2 @@ +// generated by genversion +module.exports = '4.0.0' diff --git a/node_modules/tough-cookie/package.json b/node_modules/tough-cookie/package.json new file mode 100644 index 0000000..3754f54 --- /dev/null +++ b/node_modules/tough-cookie/package.json @@ -0,0 +1,124 @@ +{ + "_args": [ + [ + "tough-cookie@4.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "tough-cookie@4.0.0", + "_id": "tough-cookie@4.0.0", + "_inBundle": false, + "_integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", + "_location": "/tough-cookie", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "tough-cookie@4.0.0", + "name": "tough-cookie", + "escapedName": "tough-cookie", + "rawSpec": "4.0.0", + "saveSpec": null, + "fetchSpec": "4.0.0" + }, + "_requiredBy": [ + "/faye" + ], + "_resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", + "_spec": "4.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Jeremy Stashewsky", + "email": "jstash@gmail.com" + }, + "bugs": { + "url": "https://github.com/salesforce/tough-cookie/issues" + }, + "contributors": [ + { + "name": "Ivan Nikulin" + }, + { + "name": "Shivan Kaul Sahib" + }, + { + "name": "Clint Ruoho" + }, + { + "name": "Ian Livingstone" + }, + { + "name": "Andrew Waterman" + }, + { + "name": "Michael de Libero" + }, + { + "name": "Jonathan Stewmon" + }, + { + "name": "Miguel Roncancio" + }, + { + "name": "Sebastian Mayr" + }, + { + "name": "Alexander Savin" + }, + { + "name": "Lalit Kapoor" + }, + { + "name": "Sam Thompson" + } + ], + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.1.2" + }, + "description": "RFC6265 Cookies and Cookie Jar for node.js", + "devDependencies": { + "async": "^2.6.2", + "eslint": "^5.16.0", + "eslint-config-prettier": "^4.2.0", + "eslint-plugin-prettier": "^3.0.1", + "genversion": "^2.1.0", + "nyc": "^14.0.0", + "prettier": "^1.17.0", + "vows": "^0.8.2" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/salesforce/tough-cookie", + "keywords": [ + "HTTP", + "cookie", + "cookies", + "set-cookie", + "cookiejar", + "jar", + "RFC6265", + "RFC2965" + ], + "license": "BSD-3-Clause", + "main": "./lib/cookie", + "name": "tough-cookie", + "repository": { + "type": "git", + "url": "git://github.com/salesforce/tough-cookie.git" + }, + "scripts": { + "cover": "nyc --reporter=lcov --reporter=html vows test/*_test.js", + "eslint": "eslint --env node --ext .js .", + "format": "npm run eslint -- --fix", + "prettier": "prettier '**/*.{json,ts,yaml,md}'", + "test": "vows test/*_test.js", + "version": "genversion lib/version.js && git add lib/version.js" + }, + "version": "4.0.0" +} diff --git a/node_modules/tr46/.npmignore b/node_modules/tr46/.npmignore new file mode 100644 index 0000000..96e9161 --- /dev/null +++ b/node_modules/tr46/.npmignore @@ -0,0 +1,4 @@ +scripts/ +test/ + +!lib/mapping_table.json diff --git a/node_modules/tr46/index.js b/node_modules/tr46/index.js new file mode 100644 index 0000000..9ce12ca --- /dev/null +++ b/node_modules/tr46/index.js @@ -0,0 +1,193 @@ +"use strict"; + +var punycode = require("punycode"); +var mappingTable = require("./lib/mappingTable.json"); + +var PROCESSING_OPTIONS = { + TRANSITIONAL: 0, + NONTRANSITIONAL: 1 +}; + +function normalize(str) { // fix bug in v8 + return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); +} + +function findStatus(val) { + var start = 0; + var end = mappingTable.length - 1; + + while (start <= end) { + var mid = Math.floor((start + end) / 2); + + var target = mappingTable[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + return target; + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +function countSymbols(string) { + return string + // replace every surrogate pair with a BMP symbol + .replace(regexAstralSymbols, '_') + // then get the length + .length; +} + +function mapChars(domain_name, useSTD3, processing_option) { + var hasError = false; + var processed = ""; + + var len = countSymbols(domain_name); + for (var i = 0; i < len; ++i) { + var codePoint = domain_name.codePointAt(i); + var status = findStatus(codePoint); + + switch (status[1]) { + case "disallowed": + hasError = true; + processed += String.fromCodePoint(codePoint); + break; + case "ignored": + break; + case "mapped": + processed += String.fromCodePoint.apply(String, status[2]); + break; + case "deviation": + if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { + processed += String.fromCodePoint.apply(String, status[2]); + } else { + processed += String.fromCodePoint(codePoint); + } + break; + case "valid": + processed += String.fromCodePoint(codePoint); + break; + case "disallowed_STD3_mapped": + if (useSTD3) { + hasError = true; + processed += String.fromCodePoint(codePoint); + } else { + processed += String.fromCodePoint.apply(String, status[2]); + } + break; + case "disallowed_STD3_valid": + if (useSTD3) { + hasError = true; + } + + processed += String.fromCodePoint(codePoint); + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; + +function validateLabel(label, processing_option) { + if (label.substr(0, 4) === "xn--") { + label = punycode.toUnicode(label); + processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; + } + + var error = false; + + if (normalize(label) !== label || + (label[3] === "-" && label[4] === "-") || + label[0] === "-" || label[label.length - 1] === "-" || + label.indexOf(".") !== -1 || + label.search(combiningMarksRegex) === 0) { + error = true; + } + + var len = countSymbols(label); + for (var i = 0; i < len; ++i) { + var status = findStatus(label.codePointAt(i)); + if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || + (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && + status[1] !== "valid" && status[1] !== "deviation")) { + error = true; + break; + } + } + + return { + label: label, + error: error + }; +} + +function processing(domain_name, useSTD3, processing_option) { + var result = mapChars(domain_name, useSTD3, processing_option); + result.string = normalize(result.string); + + var labels = result.string.split("."); + for (var i = 0; i < labels.length; ++i) { + try { + var validation = validateLabel(labels[i]); + labels[i] = validation.label; + result.error = result.error || validation.error; + } catch(e) { + result.error = true; + } + } + + return { + string: labels.join("."), + error: result.error + }; +} + +module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { + var result = processing(domain_name, useSTD3, processing_option); + var labels = result.string.split("."); + labels = labels.map(function(l) { + try { + return punycode.toASCII(l); + } catch(e) { + result.error = true; + return l; + } + }); + + if (verifyDnsLength) { + var total = labels.slice(0, labels.length - 1).join(".").length; + if (total.length > 253 || total.length === 0) { + result.error = true; + } + + for (var i=0; i < labels.length; ++i) { + if (labels.length > 63 || labels.length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) return null; + return labels.join("."); +}; + +module.exports.toUnicode = function(domain_name, useSTD3) { + var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + + return { + domain: result.string, + error: result.error + }; +}; + +module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; diff --git a/node_modules/tr46/lib/.gitkeep b/node_modules/tr46/lib/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/tr46/lib/mappingTable.json b/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 0000000..89cf19a --- /dev/null +++ b/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]] \ No newline at end of file diff --git a/node_modules/tr46/package.json b/node_modules/tr46/package.json new file mode 100644 index 0000000..e3dada9 --- /dev/null +++ b/node_modules/tr46/package.json @@ -0,0 +1,59 @@ +{ + "_from": "tr46@~0.0.3", + "_id": "tr46@0.0.3", + "_inBundle": false, + "_integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "_location": "/tr46", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "tr46@~0.0.3", + "name": "tr46", + "escapedName": "tr46", + "rawSpec": "~0.0.3", + "saveSpec": null, + "fetchSpec": "~0.0.3" + }, + "_requiredBy": [ + "/whatwg-url" + ], + "_resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "_shasum": "8184fd347dac9cdc185992f3a6622e14b9d9ab6a", + "_spec": "tr46@~0.0.3", + "_where": "/home/other/discord_bot/node_modules/whatwg-url", + "author": { + "name": "Sebastian Mayr", + "email": "npm@smayr.name" + }, + "bugs": { + "url": "https://github.com/Sebmaster/tr46.js/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "An implementation of the Unicode TR46 spec", + "devDependencies": { + "mocha": "^2.2.5", + "request": "^2.57.0" + }, + "homepage": "https://github.com/Sebmaster/tr46.js#readme", + "keywords": [ + "unicode", + "tr46", + "url", + "whatwg" + ], + "license": "MIT", + "main": "index.js", + "name": "tr46", + "repository": { + "type": "git", + "url": "git+https://github.com/Sebmaster/tr46.js.git" + }, + "scripts": { + "prepublish": "node scripts/generateMappingTable.js", + "pretest": "node scripts/getLatestUnicodeTests.js", + "test": "mocha" + }, + "version": "0.0.3" +} diff --git a/node_modules/ts-mixer/CHANGELOG.md b/node_modules/ts-mixer/CHANGELOG.md new file mode 100644 index 0000000..2283377 --- /dev/null +++ b/node_modules/ts-mixer/CHANGELOG.md @@ -0,0 +1,113 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [6.0.3](https://github.com/tannerntannern/ts-mixer/compare/v6.0.2...v6.0.3) (2023-02-09) + + +### Bug Fixes + +* allow abstract constructor signature for hasMixin ([f82e27b](https://github.com/tannerntannern/ts-mixer/commit/f82e27b96d142cfdec6446930a1db354167e88d2)), closes [tannerntannern/ts-mixer#56](https://github.com/tannerntannern/ts-mixer/issues/56) +* allow abstract constructor signatures for hasMixin ([8964b59](https://github.com/tannerntannern/ts-mixer/commit/8964b59e062854fde52424497930ca3e8bb98e87)), closes [#57](https://github.com/tannerntannern/ts-mixer/issues/57) +* simplify signature ([8a79197](https://github.com/tannerntannern/ts-mixer/commit/8a79197cc6bca5757d7c06560d7b26e73491b11f)) + +### [6.0.2](https://github.com/tannerntannern/ts-mixer/compare/v6.0.1...v6.0.2) (2022-11-10) + + +### Bug Fixes + +* **decorators:** support class decorators that don't return anything ([7433cf3](https://github.com/tannerntannern/ts-mixer/commit/7433cf36a43bb18a1dd280aa629ac81ef532c74a)) + +### [6.0.1](https://github.com/tannerntannern/ts-mixer/compare/v6.0.0...v6.0.1) (2022-03-13) + +### Bug Fixes + +* fix bug in `directDecoratorSearch` ([51c50b8](https://github.com/tannerntannern/ts-mixer/commit/51c50b8c50a63e85b133bdd61eaad4427a22e515)) (thanks, [@AMcBain](https://github.com/AMcBain)!) + +## [6.0.0](https://github.com/tannerntannern/ts-mixer/compare/v6.0.0-beta.0...v6.0.0) (2021-07-07) + +## [6.0.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v5.4.1...v6.0.0-beta.0) (2021-06-24) + + +### ⚠ BREAKING CHANGES + +* drop TS < 4.2 support + +### Features + +* add abstract mixin support ([1c4b306](https://github.com/tannerntannern/ts-mixer/commit/1c4b306bae62fa6319c74d1f3040c8aba0da2c28)) + +### [5.4.1](https://github.com/tannerntannern/ts-mixer/compare/v5.4.0...v5.4.1) (2021-04-30) + + +### Bug Fixes + +* "publish" workflow ([bd2e4ec](https://github.com/tannerntannern/ts-mixer/commit/bd2e4ec088b19a403bc013926c7f3a2545cc4171)) +* circular dependency ([66f7e2d](https://github.com/tannerntannern/ts-mixer/commit/66f7e2dc929c90e8c15d718415114ceaa31402c2)) + +## [5.4.0](https://github.com/tannerntannern/ts-mixer/compare/v5.3.0...v5.4.0) (2020-11-18) + + +### Features + +* deep decorator inheritance ([6daabc5](https://github.com/tannerntannern/ts-mixer/commit/6daabc5d340d20c8eda4fe96b635a54f6a7e18fb)) + +## [5.3.0](https://github.com/tannerntannern/ts-mixer/compare/v5.3.0-beta.0...v5.3.0) (2020-06-01) + +## [5.3.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v5.2.1...v5.3.0-beta.0) (2020-05-31) + + +### Features + +* add hasMixin function ([#27](https://github.com/tannerntannern/ts-mixer/issues/27)) ([c8bfc2d](https://github.com/tannerntannern/ts-mixer/commit/c8bfc2d48854808755088332636e8d166007ed9f)) + +### [5.2.1](https://github.com/tannerntannern/ts-mixer/compare/v5.2.0...v5.2.1) (2020-05-08) + + +### Bug Fixes + +* mix decorator not preserving constructor name ([7274fa2](https://github.com/tannerntannern/ts-mixer/commit/7274fa26a68e05cc59cde1108610e6a1ab51b430)) + +## [5.2.0](https://github.com/tannerntannern/ts-mixer/compare/v5.2.0-beta.1...v5.2.0) (2020-04-29) + +## [5.2.0-beta.1](https://github.com/tannerntannern/ts-mixer/compare/v5.2.0-beta.0...v5.2.0-beta.1) (2020-04-23) + + +### Bug Fixes + +* wrong this in init functions for Mixin(A, Mixin(B, C)) scenario ([0ba1128](https://github.com/tannerntannern/ts-mixer/commit/0ba11283c63a878271b85c282f75190758101e63)) + +## [5.2.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v5.1.0...v5.2.0-beta.0) (2020-04-13) + + +### Features + +* adds init func feature for impure constructors ([99a946b](https://github.com/tannerntannern/ts-mixer/commit/99a946b8e272773f6bafd7a7e8bf8313517dec16)) + +## [5.1.0](https://github.com/tannerntannern/ts-mixer/compare/v5.1.0-beta.0...v5.1.0) (2020-03-27) + +## [5.1.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v5.0.0...v5.1.0-beta.0) (2020-03-26) + + +### Features + +* decorator support for class-validators, typeORM, etc ([2c14812](https://github.com/tannerntannern/ts-mixer/commit/2c1481237b325916ca95dbb9e33141b3220f8068)) + +## [5.0.0](https://github.com/tannerntannern/ts-mixer/compare/v5.0.0-beta.0...v5.0.0) (2020-03-01) + +## [5.0.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v4.0.0...v5.0.0-beta.0) (2020-02-02) + + +### Features + +* adds and tests a nearestCommonAncestor function ([b084579](https://github.com/tannerntannern/ts-mixer/commit/b084579d5ac52e0b456be95ff6b776309b436473)) +* initial static inheritance implementation ([8467c40](https://github.com/tannerntannern/ts-mixer/commit/8467c40c9748e769eebf77b45cccad5ce785bac9)) +* initial version of proxyMix ([95a91c7](https://github.com/tannerntannern/ts-mixer/commit/95a91c78e5f05af75cfc95d82a65ce5b3413b9f1)) +* makes mixin constructor argument inference slightly smarter ([b844b5c](https://github.com/tannerntannern/ts-mixer/commit/b844b5c93f5eab0d6f522559ed567f67291fae76)) + + +### Bug Fixes + +* mixins with shared ancestor when using proxy prototype ([5af189d](https://github.com/tannerntannern/ts-mixer/commit/5af189d9903083f675f65b5039875c4aa97be1a6)) +* resolves indefinite tuple issue with `Longest` type ([68342b0](https://github.com/tannerntannern/ts-mixer/commit/68342b0a3fe224a485f220039af872050aa941fc)) +* static chain inheritance ([0aca8f0](https://github.com/tannerntannern/ts-mixer/commit/0aca8f056a005ccf27cc564d5a84abe1ef999d7b)) diff --git a/node_modules/ts-mixer/LICENSE b/node_modules/ts-mixer/LICENSE new file mode 100644 index 0000000..c8a6114 --- /dev/null +++ b/node_modules/ts-mixer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Tanner Nielsen + +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/ts-mixer/README.md b/node_modules/ts-mixer/README.md new file mode 100644 index 0000000..b9e66bd --- /dev/null +++ b/node_modules/ts-mixer/README.md @@ -0,0 +1,270 @@ +# ts-mixer +[version-badge]: https://badgen.net/npm/v/ts-mixer +[version-link]: https://npmjs.com/package/ts-mixer +[build-link]: https://github.com/tannerntannern/ts-mixer/actions +[ts-versions]: https://badgen.net/badge/icon/4.2,4.4,4.6,4.8?icon=typescript&label&list=| +[node-versions]: https://badgen.net/badge/node/12%2C14%2C16%2C18/blue/?list=| +[![npm version][version-badge]][version-link] +[![TS Versions][ts-versions]][build-link] +[![Node.js Versions][node-versions]][build-link] +[![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer) +[![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org) + +## Overview +`ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble. + +The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered. + +[Quick start guide](#quick-start) + +### Features +* mixes plain classes +* mixes classes that extend other classes +* mixes classes that were mixed with `ts-mixer` +* supports static properties +* supports protected/private properties (the popular function-that-returns-a-class solution does not) +* mixes abstract classes (requires TypeScript >= 4.2) +* mixes generic classes (with caveats [[1](#caveats)]) +* supports class, method, and property decorators (with caveats [[2, 5](#caveats)]) +* mostly supports the complexity presented by constructor functions (with caveats [[3](#caveats)]) +* comes with an `instanceof`-like replacement (with caveats [[4, 5](#caveats)]) +* [multiple mixing strategies](#settings) (ES6 proxies vs hard copy) + +### Caveats +1. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below. +2. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below. +3. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below. +4. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details. +5. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without. + +## Quick Start +### Installation +``` +$ npm install ts-mixer +``` + +or if you prefer [Yarn](https://yarnpkg.com): + +``` +$ yarn add ts-mixer +``` + +### Basic Example +```typescript +import { Mixin } from 'ts-mixer'; + +class Foo { + protected makeFoo() { + return 'foo'; + } +} + +class Bar { + protected makeBar() { + return 'bar'; + } +} + +class FooBar extends Mixin(Foo, Bar) { + public makeFooBar() { + return this.makeFoo() + this.makeBar(); + } +} + +const fooBar = new FooBar(); + +console.log(fooBar.makeFooBar()); // "foobar" +``` + +## Special Cases +### Mixing Generic Classes +Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.` + +The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below: + +```typescript +import { mix } from 'ts-mixer'; + +class Foo { + public fooMethod(input: T): T { + return input; + } +} + +class Bar { + public barMethod(input: T): T { + return input; + } +} + +interface FooBar extends Foo, Bar { } +@mix(Foo, Bar) +class FooBar { + public fooBarMethod(input1: T1, input2: T2) { + return [this.fooMethod(input1), this.barMethod(input2)]; + } +} +``` + +Key takeaways from this example: +* `interface FooBar extends Foo, Bar { }` makes sure `FooBar` has the typing we want, thanks to declaration merging +* `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior. +* The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts. + +### Mixing with Decorators +Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`: + +```typescript +import { IsBoolean, IsIn, validate } from 'class-validator'; +import { Mixin, decorate } from 'ts-mixer'; + +class Disposable { + @decorate(IsBoolean()) // instead of @IsBoolean() + isDisposed: boolean = false; +} + +class Statusable { + @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green']) + status: string = 'green'; +} + +class ExtendedObject extends Mixin(Disposable, Statusable) {} + +const extendedObject = new ExtendedObject(); +extendedObject.status = 'blue'; + +validate(extendedObject).then(errors => { + console.log(errors); +}); +``` + +### Dealing with Constructors +As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`. + +**This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors). + +If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example: + +```typescript +import { Mixin, settings } from 'ts-mixer'; + +settings.initFunction = 'init'; + +class Person { + public static allPeople: Set = new Set(); + + protected init() { + Person.allPeople.add(this); + } +} + +type PartyAffiliation = 'democrat' | 'republican'; + +class PoliticalParticipant { + public static democrats: Set = new Set(); + public static republicans: Set = new Set(); + + public party: PartyAffiliation; + + // note that these same args will also be passed to init function + public constructor(party: PartyAffiliation) { + this.party = party; + } + + protected init(party: PartyAffiliation) { + if (party === 'democrat') + PoliticalParticipant.democrats.add(this); + else + PoliticalParticipant.republicans.add(this); + } +} + +class Voter extends Mixin(Person, PoliticalParticipant) {} + +const v1 = new Voter('democrat'); +const v2 = new Voter('democrat'); +const v3 = new Voter('republican'); +const v4 = new Voter('republican'); +``` + +Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above. + +## Other Features +### hasMixin +As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided. + +You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example: + +```typescript +import { Mixin, hasMixin } from 'ts-mixer'; + +class Foo {} +class Bar {} +class FooBar extends Mixin(Foo, Bar) {} + +const instance = new FooBar(); + +// doesn't work with instanceof... +console.log(instance instanceof FooBar) // true +console.log(instance instanceof Foo) // false +console.log(instance instanceof Bar) // false + +// but everything works nicely with hasMixin! +console.log(hasMixin(instance, FooBar)) // true +console.log(hasMixin(instance, Foo)) // true +console.log(hasMixin(instance, Bar)) // true +``` + +`hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards): + +```typescript +if (hasMixin(instance, Foo)) { + // inferred type of instance is "Foo" +} + +if (hasMixin(instance, Bar)) { + // inferred type of instance of "Bar" +} +``` + +## Settings +ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example: + +```typescript +import { settings, Mixin } from 'ts-mixer'; + +settings.prototypeStrategy = 'proxy'; + +// then use `Mixin` as normal... +``` + +### `settings.prototypeStrategy` +* Determines how ts-mixer will mix class prototypes together +* Possible values: + - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting. + - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible. + +### `settings.staticsStrategy` +* Determines how static properties are inherited +* Possible values: + - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing. + - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides. + +### `settings.initFunction` +* If set, `ts-mixer` will automatically call the function with this name upon construction +* Possible values: + - `null` (default) - disables the behavior + - a string - function name to call upon construction +* Read more about why you would want this in [dealing with constructors](#dealing-with-constructors) + +### `settings.decoratorInheritance` +* Determines how decorators are inherited from classes passed to `Mixin(...)` +* Possible values: + - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors + - `'direct'` - Only inherits decorators defined directly on the given classes + - `'none'` - Skips decorator inheritance + +# Author +Tanner Nielsen +* Website - [tannernielsen.com](http://tannernielsen.com) +* Github - [tannerntannern](https://github.com/tannerntannern) diff --git a/node_modules/ts-mixer/dist/cjs/decorator.js b/node_modules/ts-mixer/dist/cjs/decorator.js new file mode 100644 index 0000000..45d6dba --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/decorator.js @@ -0,0 +1,109 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decorate = exports.getDecoratorsForClass = exports.directDecoratorSearch = exports.deepDecoratorSearch = void 0; +const util_1 = require("./util"); +const mixin_tracking_1 = require("./mixin-tracking"); +const mergeObjectsOfDecorators = (o1, o2) => { + var _a, _b; + const allKeys = (0, util_1.unique)([...Object.getOwnPropertyNames(o1), ...Object.getOwnPropertyNames(o2)]); + const mergedObject = {}; + for (let key of allKeys) + mergedObject[key] = (0, util_1.unique)([...((_a = o1 === null || o1 === void 0 ? void 0 : o1[key]) !== null && _a !== void 0 ? _a : []), ...((_b = o2 === null || o2 === void 0 ? void 0 : o2[key]) !== null && _b !== void 0 ? _b : [])]); + return mergedObject; +}; +const mergePropertyAndMethodDecorators = (d1, d2) => { + var _a, _b, _c, _d; + return ({ + property: mergeObjectsOfDecorators((_a = d1 === null || d1 === void 0 ? void 0 : d1.property) !== null && _a !== void 0 ? _a : {}, (_b = d2 === null || d2 === void 0 ? void 0 : d2.property) !== null && _b !== void 0 ? _b : {}), + method: mergeObjectsOfDecorators((_c = d1 === null || d1 === void 0 ? void 0 : d1.method) !== null && _c !== void 0 ? _c : {}, (_d = d2 === null || d2 === void 0 ? void 0 : d2.method) !== null && _d !== void 0 ? _d : {}), + }); +}; +const mergeDecorators = (d1, d2) => { + var _a, _b, _c, _d, _e, _f; + return ({ + class: (0, util_1.unique)([...(_a = d1 === null || d1 === void 0 ? void 0 : d1.class) !== null && _a !== void 0 ? _a : [], ...(_b = d2 === null || d2 === void 0 ? void 0 : d2.class) !== null && _b !== void 0 ? _b : []]), + static: mergePropertyAndMethodDecorators((_c = d1 === null || d1 === void 0 ? void 0 : d1.static) !== null && _c !== void 0 ? _c : {}, (_d = d2 === null || d2 === void 0 ? void 0 : d2.static) !== null && _d !== void 0 ? _d : {}), + instance: mergePropertyAndMethodDecorators((_e = d1 === null || d1 === void 0 ? void 0 : d1.instance) !== null && _e !== void 0 ? _e : {}, (_f = d2 === null || d2 === void 0 ? void 0 : d2.instance) !== null && _f !== void 0 ? _f : {}), + }); +}; +const decorators = new Map(); +const findAllConstituentClasses = (...classes) => { + var _a; + const allClasses = new Set(); + const frontier = new Set([...classes]); + while (frontier.size > 0) { + for (let clazz of frontier) { + const protoChainClasses = (0, util_1.protoChain)(clazz.prototype).map(proto => proto.constructor); + const mixinClasses = (_a = (0, mixin_tracking_1.getMixinsForClass)(clazz)) !== null && _a !== void 0 ? _a : []; + const potentiallyNewClasses = [...protoChainClasses, ...mixinClasses]; + const newClasses = potentiallyNewClasses.filter(c => !allClasses.has(c)); + for (let newClass of newClasses) + frontier.add(newClass); + allClasses.add(clazz); + frontier.delete(clazz); + } + } + return [...allClasses]; +}; +const deepDecoratorSearch = (...classes) => { + const decoratorsForClassChain = findAllConstituentClasses(...classes) + .map(clazz => decorators.get(clazz)) + .filter(decorators => !!decorators); + if (decoratorsForClassChain.length == 0) + return {}; + if (decoratorsForClassChain.length == 1) + return decoratorsForClassChain[0]; + return decoratorsForClassChain.reduce((d1, d2) => mergeDecorators(d1, d2)); +}; +exports.deepDecoratorSearch = deepDecoratorSearch; +const directDecoratorSearch = (...classes) => { + const classDecorators = classes.map(clazz => (0, exports.getDecoratorsForClass)(clazz)); + if (classDecorators.length === 0) + return {}; + if (classDecorators.length === 1) + return classDecorators[0]; + return classDecorators.reduce((d1, d2) => mergeDecorators(d1, d2)); +}; +exports.directDecoratorSearch = directDecoratorSearch; +const getDecoratorsForClass = (clazz) => { + let decoratorsForClass = decorators.get(clazz); + if (!decoratorsForClass) { + decoratorsForClass = {}; + decorators.set(clazz, decoratorsForClass); + } + return decoratorsForClass; +}; +exports.getDecoratorsForClass = getDecoratorsForClass; +const decorateClass = (decorator) => ((clazz) => { + const decoratorsForClass = (0, exports.getDecoratorsForClass)(clazz); + let classDecorators = decoratorsForClass.class; + if (!classDecorators) { + classDecorators = []; + decoratorsForClass.class = classDecorators; + } + classDecorators.push(decorator); + return decorator(clazz); +}); +const decorateMember = (decorator) => ((object, key, ...otherArgs) => { + var _a, _b, _c; + const decoratorTargetType = typeof object === 'function' ? 'static' : 'instance'; + const decoratorType = typeof object[key] === 'function' ? 'method' : 'property'; + const clazz = decoratorTargetType === 'static' ? object : object.constructor; + const decoratorsForClass = (0, exports.getDecoratorsForClass)(clazz); + const decoratorsForTargetType = (_a = decoratorsForClass === null || decoratorsForClass === void 0 ? void 0 : decoratorsForClass[decoratorTargetType]) !== null && _a !== void 0 ? _a : {}; + decoratorsForClass[decoratorTargetType] = decoratorsForTargetType; + let decoratorsForType = (_b = decoratorsForTargetType === null || decoratorsForTargetType === void 0 ? void 0 : decoratorsForTargetType[decoratorType]) !== null && _b !== void 0 ? _b : {}; + decoratorsForTargetType[decoratorType] = decoratorsForType; + let decoratorsForKey = (_c = decoratorsForType === null || decoratorsForType === void 0 ? void 0 : decoratorsForType[key]) !== null && _c !== void 0 ? _c : []; + decoratorsForType[key] = decoratorsForKey; + // @ts-ignore: array is type `A[] | B[]` and item is type `A | B`, so technically a type error, but it's fine + decoratorsForKey.push(decorator); + // @ts-ignore + return decorator(object, key, ...otherArgs); +}); +const decorate = (decorator) => ((...args) => { + if (args.length === 1) + return decorateClass(decorator)(args[0]); + return decorateMember(decorator)(...args); +}); +exports.decorate = decorate; diff --git a/node_modules/ts-mixer/dist/cjs/index.js b/node_modules/ts-mixer/dist/cjs/index.js new file mode 100644 index 0000000..5702401 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/index.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasMixin = exports.decorate = exports.settings = exports.mix = exports.Mixin = void 0; +var mixins_1 = require("./mixins"); +Object.defineProperty(exports, "Mixin", { enumerable: true, get: function () { return mixins_1.Mixin; } }); +Object.defineProperty(exports, "mix", { enumerable: true, get: function () { return mixins_1.mix; } }); +var settings_1 = require("./settings"); +Object.defineProperty(exports, "settings", { enumerable: true, get: function () { return settings_1.settings; } }); +var decorator_1 = require("./decorator"); +Object.defineProperty(exports, "decorate", { enumerable: true, get: function () { return decorator_1.decorate; } }); +var mixin_tracking_1 = require("./mixin-tracking"); +Object.defineProperty(exports, "hasMixin", { enumerable: true, get: function () { return mixin_tracking_1.hasMixin; } }); diff --git a/node_modules/ts-mixer/dist/cjs/mixin-tracking.js b/node_modules/ts-mixer/dist/cjs/mixin-tracking.js new file mode 100644 index 0000000..33ac2e7 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/mixin-tracking.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasMixin = exports.registerMixins = exports.getMixinsForClass = void 0; +const util_1 = require("./util"); +// Keeps track of constituent classes for every mixin class created by ts-mixer. +const mixins = new Map(); +const getMixinsForClass = (clazz) => mixins.get(clazz); +exports.getMixinsForClass = getMixinsForClass; +const registerMixins = (mixedClass, constituents) => mixins.set(mixedClass, constituents); +exports.registerMixins = registerMixins; +const hasMixin = (instance, mixin) => { + if (instance instanceof mixin) + return true; + const constructor = instance.constructor; + const visited = new Set(); + let frontier = new Set(); + frontier.add(constructor); + while (frontier.size > 0) { + // check if the frontier has the mixin we're looking for. if not, we can say we visited every item in the frontier + if (frontier.has(mixin)) + return true; + frontier.forEach(item => visited.add(item)); + // build a new frontier based on the associated mixin classes and prototype chains of each frontier item + const newFrontier = new Set(); + frontier.forEach(item => { + var _a; + const itemConstituents = (_a = mixins.get(item)) !== null && _a !== void 0 ? _a : (0, util_1.protoChain)(item.prototype).map(proto => proto.constructor).filter(item => item !== null); + if (itemConstituents) + itemConstituents.forEach(constituent => { + if (!visited.has(constituent) && !frontier.has(constituent)) + newFrontier.add(constituent); + }); + }); + // we have a new frontier, now search again + frontier = newFrontier; + } + // if we get here, we couldn't find the mixin anywhere in the prototype chain or associated mixin classes + return false; +}; +exports.hasMixin = hasMixin; diff --git a/node_modules/ts-mixer/dist/cjs/mixins.js b/node_modules/ts-mixer/dist/cjs/mixins.js new file mode 100644 index 0000000..925e90a --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/mixins.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mix = exports.Mixin = void 0; +const proxy_1 = require("./proxy"); +const settings_1 = require("./settings"); +const util_1 = require("./util"); +const decorator_1 = require("./decorator"); +const mixin_tracking_1 = require("./mixin-tracking"); +function Mixin(...constructors) { + var _a, _b, _c; + const prototypes = constructors.map(constructor => constructor.prototype); + // Here we gather up the init functions of the ingredient prototypes, combine them into one init function, and + // attach it to the mixed class prototype. The reason we do this is because we want the init functions to mix + // similarly to constructors -- not methods, which simply override each other. + const initFunctionName = settings_1.settings.initFunction; + if (initFunctionName !== null) { + const initFunctions = prototypes + .map(proto => proto[initFunctionName]) + .filter(func => typeof func === 'function'); + const combinedInitFunction = function (...args) { + for (let initFunction of initFunctions) + initFunction.apply(this, args); + }; + const extraProto = { [initFunctionName]: combinedInitFunction }; + prototypes.push(extraProto); + } + function MixedClass(...args) { + for (const constructor of constructors) + // @ts-ignore: potentially abstract class + (0, util_1.copyProps)(this, new constructor(...args)); + if (initFunctionName !== null && typeof this[initFunctionName] === 'function') + this[initFunctionName].apply(this, args); + } + MixedClass.prototype = settings_1.settings.prototypeStrategy === 'copy' + ? (0, util_1.hardMixProtos)(prototypes, MixedClass) + : (0, proxy_1.softMixProtos)(prototypes, MixedClass); + Object.setPrototypeOf(MixedClass, settings_1.settings.staticsStrategy === 'copy' + ? (0, util_1.hardMixProtos)(constructors, null, ['prototype']) + : (0, proxy_1.proxyMix)(constructors, Function.prototype)); + let DecoratedMixedClass = MixedClass; + if (settings_1.settings.decoratorInheritance !== 'none') { + const classDecorators = settings_1.settings.decoratorInheritance === 'deep' + ? (0, decorator_1.deepDecoratorSearch)(...constructors) + : (0, decorator_1.directDecoratorSearch)(...constructors); + for (let decorator of (_a = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.class) !== null && _a !== void 0 ? _a : []) { + const result = decorator(DecoratedMixedClass); + if (result) { + DecoratedMixedClass = result; + } + } + applyPropAndMethodDecorators((_b = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.static) !== null && _b !== void 0 ? _b : {}, DecoratedMixedClass); + applyPropAndMethodDecorators((_c = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.instance) !== null && _c !== void 0 ? _c : {}, DecoratedMixedClass.prototype); + } + (0, mixin_tracking_1.registerMixins)(DecoratedMixedClass, constructors); + return DecoratedMixedClass; +} +exports.Mixin = Mixin; +const applyPropAndMethodDecorators = (propAndMethodDecorators, target) => { + const propDecorators = propAndMethodDecorators.property; + const methodDecorators = propAndMethodDecorators.method; + if (propDecorators) + for (let key in propDecorators) + for (let decorator of propDecorators[key]) + decorator(target, key); + if (methodDecorators) + for (let key in methodDecorators) + for (let decorator of methodDecorators[key]) + decorator(target, key, Object.getOwnPropertyDescriptor(target, key)); +}; +/** + * A decorator version of the `Mixin` function. You'll want to use this instead of `Mixin` for mixing generic classes. + */ +const mix = (...ingredients) => decoratedClass => { + // @ts-ignore + const mixedClass = Mixin(...ingredients.concat([decoratedClass])); + Object.defineProperty(mixedClass, 'name', { + value: decoratedClass.name, + writable: false, + }); + return mixedClass; +}; +exports.mix = mix; diff --git a/node_modules/ts-mixer/dist/cjs/proxy.js b/node_modules/ts-mixer/dist/cjs/proxy.js new file mode 100644 index 0000000..f7974c3 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/proxy.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.softMixProtos = exports.proxyMix = exports.getIngredientWithProp = void 0; +const util_1 = require("./util"); +/** + * Finds the ingredient with the given prop, searching in reverse order and breadth-first if searching ingredient + * prototypes is required. + */ +const getIngredientWithProp = (prop, ingredients) => { + const protoChains = ingredients.map(ingredient => (0, util_1.protoChain)(ingredient)); + // since we search breadth-first, we need to keep track of our depth in the prototype chains + let protoDepth = 0; + // not all prototype chains are the same depth, so this remains true as long as at least one of the ingredients' + // prototype chains has an object at this depth + let protosAreLeftToSearch = true; + while (protosAreLeftToSearch) { + // with the start of each horizontal slice, we assume this is the one that's deeper than any of the proto chains + protosAreLeftToSearch = false; + // scan through the ingredients right to left + for (let i = ingredients.length - 1; i >= 0; i--) { + const searchTarget = protoChains[i][protoDepth]; + if (searchTarget !== undefined && searchTarget !== null) { + // if we find something, this is proof that this horizontal slice potentially more objects to search + protosAreLeftToSearch = true; + // eureka, we found it + if (Object.getOwnPropertyDescriptor(searchTarget, prop) != undefined) { + return protoChains[i][0]; + } + } + } + protoDepth++; + } + return undefined; +}; +exports.getIngredientWithProp = getIngredientWithProp; +/** + * "Mixes" ingredients by wrapping them in a Proxy. The optional prototype argument allows the mixed object to sit + * downstream of an existing prototype chain. Note that "properties" cannot be added, deleted, or modified. + */ +const proxyMix = (ingredients, prototype = Object.prototype) => new Proxy({}, { + getPrototypeOf() { + return prototype; + }, + setPrototypeOf() { + throw Error('Cannot set prototype of Proxies created by ts-mixer'); + }, + getOwnPropertyDescriptor(_, prop) { + return Object.getOwnPropertyDescriptor((0, exports.getIngredientWithProp)(prop, ingredients) || {}, prop); + }, + defineProperty() { + throw new Error('Cannot define new properties on Proxies created by ts-mixer'); + }, + has(_, prop) { + return (0, exports.getIngredientWithProp)(prop, ingredients) !== undefined || prototype[prop] !== undefined; + }, + get(_, prop) { + return ((0, exports.getIngredientWithProp)(prop, ingredients) || prototype)[prop]; + }, + set(_, prop, val) { + const ingredientWithProp = (0, exports.getIngredientWithProp)(prop, ingredients); + if (ingredientWithProp === undefined) + throw new Error('Cannot set new properties on Proxies created by ts-mixer'); + ingredientWithProp[prop] = val; + return true; + }, + deleteProperty() { + throw new Error('Cannot delete properties on Proxies created by ts-mixer'); + }, + ownKeys() { + return ingredients + .map(Object.getOwnPropertyNames) + .reduce((prev, curr) => curr.concat(prev.filter(key => curr.indexOf(key) < 0))); + }, +}); +exports.proxyMix = proxyMix; +/** + * Creates a new proxy-prototype object that is a "soft" mixture of the given prototypes. The mixing is achieved by + * proxying all property access to the ingredients. This is not ES5 compatible and less performant. However, any + * changes made to the source prototypes will be reflected in the proxy-prototype, which may be desirable. + */ +const softMixProtos = (ingredients, constructor) => (0, exports.proxyMix)([...ingredients, { constructor }]); +exports.softMixProtos = softMixProtos; diff --git a/node_modules/ts-mixer/dist/cjs/settings.js b/node_modules/ts-mixer/dist/cjs/settings.js new file mode 100644 index 0000000..dabb6d3 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/settings.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.settings = void 0; +exports.settings = { + initFunction: null, + staticsStrategy: 'copy', + prototypeStrategy: 'copy', + decoratorInheritance: 'deep', +}; diff --git a/node_modules/ts-mixer/dist/cjs/types.js b/node_modules/ts-mixer/dist/cjs/types.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/ts-mixer/dist/cjs/util.js b/node_modules/ts-mixer/dist/cjs/util.js new file mode 100644 index 0000000..5151696 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/util.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.flatten = exports.unique = exports.hardMixProtos = exports.nearestCommonProto = exports.protoChain = exports.copyProps = void 0; +/** + * Utility function that works like `Object.apply`, but copies getters and setters properly as well. Additionally gives + * the option to exclude properties by name. + */ +const copyProps = (dest, src, exclude = []) => { + const props = Object.getOwnPropertyDescriptors(src); + for (let prop of exclude) + delete props[prop]; + Object.defineProperties(dest, props); +}; +exports.copyProps = copyProps; +/** + * Returns the full chain of prototypes up until Object.prototype given a starting object. The order of prototypes will + * be closest to farthest in the chain. + */ +const protoChain = (obj, currentChain = [obj]) => { + const proto = Object.getPrototypeOf(obj); + if (proto === null) + return currentChain; + return (0, exports.protoChain)(proto, [...currentChain, proto]); +}; +exports.protoChain = protoChain; +/** + * Identifies the nearest ancestor common to all the given objects in their prototype chains. For most unrelated + * objects, this function should return Object.prototype. + */ +const nearestCommonProto = (...objs) => { + if (objs.length === 0) + return undefined; + let commonProto = undefined; + const protoChains = objs.map(obj => (0, exports.protoChain)(obj)); + while (protoChains.every(protoChain => protoChain.length > 0)) { + const protos = protoChains.map(protoChain => protoChain.pop()); + const potentialCommonProto = protos[0]; + if (protos.every(proto => proto === potentialCommonProto)) + commonProto = potentialCommonProto; + else + break; + } + return commonProto; +}; +exports.nearestCommonProto = nearestCommonProto; +/** + * Creates a new prototype object that is a mixture of the given prototypes. The mixing is achieved by first + * identifying the nearest common ancestor and using it as the prototype for a new object. Then all properties/methods + * downstream of this prototype (ONLY downstream) are copied into the new object. + * + * The resulting prototype is more performant than softMixProtos(...), as well as ES5 compatible. However, it's not as + * flexible as updates to the source prototypes aren't captured by the mixed result. See softMixProtos for why you may + * want to use that instead. + */ +const hardMixProtos = (ingredients, constructor, exclude = []) => { + var _a; + const base = (_a = (0, exports.nearestCommonProto)(...ingredients)) !== null && _a !== void 0 ? _a : Object.prototype; + const mixedProto = Object.create(base); + // Keeps track of prototypes we've already visited to avoid copying the same properties multiple times. We init the + // list with the proto chain below the nearest common ancestor because we don't want any of those methods mixed in + // when they will already be accessible via prototype access. + const visitedProtos = (0, exports.protoChain)(base); + for (let prototype of ingredients) { + let protos = (0, exports.protoChain)(prototype); + // Apply the prototype chain in reverse order so that old methods don't override newer ones. + for (let i = protos.length - 1; i >= 0; i--) { + let newProto = protos[i]; + if (visitedProtos.indexOf(newProto) === -1) { + (0, exports.copyProps)(mixedProto, newProto, ['constructor', ...exclude]); + visitedProtos.push(newProto); + } + } + } + mixedProto.constructor = constructor; + return mixedProto; +}; +exports.hardMixProtos = hardMixProtos; +const unique = (arr) => arr.filter((e, i) => arr.indexOf(e) == i); +exports.unique = unique; +const flatten = (arr) => arr.length === 0 + ? [] + : arr.length === 1 + ? arr[0] + : arr.reduce((a1, a2) => [...a1, ...a2]); +exports.flatten = flatten; diff --git a/node_modules/ts-mixer/dist/esm/decorator.d.ts b/node_modules/ts-mixer/dist/esm/decorator.d.ts new file mode 100644 index 0000000..dde5df2 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/decorator.d.ts @@ -0,0 +1,18 @@ +import { Class } from './types'; +type ObjectOfDecorators = { + [key: string]: T[]; +}; +export type PropertyAndMethodDecorators = { + property?: ObjectOfDecorators; + method?: ObjectOfDecorators; +}; +type Decorators = { + class?: ClassDecorator[]; + static?: PropertyAndMethodDecorators; + instance?: PropertyAndMethodDecorators; +}; +export declare const deepDecoratorSearch: (...classes: Class[]) => Decorators; +export declare const directDecoratorSearch: (...classes: Class[]) => Decorators; +export declare const getDecoratorsForClass: (clazz: Class) => Decorators; +export declare const decorate: (decorator: T) => T; +export {}; diff --git a/node_modules/ts-mixer/dist/esm/index.d.ts b/node_modules/ts-mixer/dist/esm/index.d.ts new file mode 100644 index 0000000..2a16080 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/index.d.ts @@ -0,0 +1,4 @@ +export { Mixin, mix } from './mixins'; +export { settings } from './settings'; +export { decorate } from './decorator'; +export { hasMixin } from './mixin-tracking'; diff --git a/node_modules/ts-mixer/dist/esm/index.js b/node_modules/ts-mixer/dist/esm/index.js new file mode 100644 index 0000000..991d21b --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/index.js @@ -0,0 +1,364 @@ +/** + * Utility function that works like `Object.apply`, but copies getters and setters properly as well. Additionally gives + * the option to exclude properties by name. + */ +const copyProps = (dest, src, exclude = []) => { + const props = Object.getOwnPropertyDescriptors(src); + for (let prop of exclude) + delete props[prop]; + Object.defineProperties(dest, props); +}; +/** + * Returns the full chain of prototypes up until Object.prototype given a starting object. The order of prototypes will + * be closest to farthest in the chain. + */ +const protoChain = (obj, currentChain = [obj]) => { + const proto = Object.getPrototypeOf(obj); + if (proto === null) + return currentChain; + return protoChain(proto, [...currentChain, proto]); +}; +/** + * Identifies the nearest ancestor common to all the given objects in their prototype chains. For most unrelated + * objects, this function should return Object.prototype. + */ +const nearestCommonProto = (...objs) => { + if (objs.length === 0) + return undefined; + let commonProto = undefined; + const protoChains = objs.map(obj => protoChain(obj)); + while (protoChains.every(protoChain => protoChain.length > 0)) { + const protos = protoChains.map(protoChain => protoChain.pop()); + const potentialCommonProto = protos[0]; + if (protos.every(proto => proto === potentialCommonProto)) + commonProto = potentialCommonProto; + else + break; + } + return commonProto; +}; +/** + * Creates a new prototype object that is a mixture of the given prototypes. The mixing is achieved by first + * identifying the nearest common ancestor and using it as the prototype for a new object. Then all properties/methods + * downstream of this prototype (ONLY downstream) are copied into the new object. + * + * The resulting prototype is more performant than softMixProtos(...), as well as ES5 compatible. However, it's not as + * flexible as updates to the source prototypes aren't captured by the mixed result. See softMixProtos for why you may + * want to use that instead. + */ +const hardMixProtos = (ingredients, constructor, exclude = []) => { + var _a; + const base = (_a = nearestCommonProto(...ingredients)) !== null && _a !== void 0 ? _a : Object.prototype; + const mixedProto = Object.create(base); + // Keeps track of prototypes we've already visited to avoid copying the same properties multiple times. We init the + // list with the proto chain below the nearest common ancestor because we don't want any of those methods mixed in + // when they will already be accessible via prototype access. + const visitedProtos = protoChain(base); + for (let prototype of ingredients) { + let protos = protoChain(prototype); + // Apply the prototype chain in reverse order so that old methods don't override newer ones. + for (let i = protos.length - 1; i >= 0; i--) { + let newProto = protos[i]; + if (visitedProtos.indexOf(newProto) === -1) { + copyProps(mixedProto, newProto, ['constructor', ...exclude]); + visitedProtos.push(newProto); + } + } + } + mixedProto.constructor = constructor; + return mixedProto; +}; +const unique = (arr) => arr.filter((e, i) => arr.indexOf(e) == i); + +/** + * Finds the ingredient with the given prop, searching in reverse order and breadth-first if searching ingredient + * prototypes is required. + */ +const getIngredientWithProp = (prop, ingredients) => { + const protoChains = ingredients.map(ingredient => protoChain(ingredient)); + // since we search breadth-first, we need to keep track of our depth in the prototype chains + let protoDepth = 0; + // not all prototype chains are the same depth, so this remains true as long as at least one of the ingredients' + // prototype chains has an object at this depth + let protosAreLeftToSearch = true; + while (protosAreLeftToSearch) { + // with the start of each horizontal slice, we assume this is the one that's deeper than any of the proto chains + protosAreLeftToSearch = false; + // scan through the ingredients right to left + for (let i = ingredients.length - 1; i >= 0; i--) { + const searchTarget = protoChains[i][protoDepth]; + if (searchTarget !== undefined && searchTarget !== null) { + // if we find something, this is proof that this horizontal slice potentially more objects to search + protosAreLeftToSearch = true; + // eureka, we found it + if (Object.getOwnPropertyDescriptor(searchTarget, prop) != undefined) { + return protoChains[i][0]; + } + } + } + protoDepth++; + } + return undefined; +}; +/** + * "Mixes" ingredients by wrapping them in a Proxy. The optional prototype argument allows the mixed object to sit + * downstream of an existing prototype chain. Note that "properties" cannot be added, deleted, or modified. + */ +const proxyMix = (ingredients, prototype = Object.prototype) => new Proxy({}, { + getPrototypeOf() { + return prototype; + }, + setPrototypeOf() { + throw Error('Cannot set prototype of Proxies created by ts-mixer'); + }, + getOwnPropertyDescriptor(_, prop) { + return Object.getOwnPropertyDescriptor(getIngredientWithProp(prop, ingredients) || {}, prop); + }, + defineProperty() { + throw new Error('Cannot define new properties on Proxies created by ts-mixer'); + }, + has(_, prop) { + return getIngredientWithProp(prop, ingredients) !== undefined || prototype[prop] !== undefined; + }, + get(_, prop) { + return (getIngredientWithProp(prop, ingredients) || prototype)[prop]; + }, + set(_, prop, val) { + const ingredientWithProp = getIngredientWithProp(prop, ingredients); + if (ingredientWithProp === undefined) + throw new Error('Cannot set new properties on Proxies created by ts-mixer'); + ingredientWithProp[prop] = val; + return true; + }, + deleteProperty() { + throw new Error('Cannot delete properties on Proxies created by ts-mixer'); + }, + ownKeys() { + return ingredients + .map(Object.getOwnPropertyNames) + .reduce((prev, curr) => curr.concat(prev.filter(key => curr.indexOf(key) < 0))); + }, +}); +/** + * Creates a new proxy-prototype object that is a "soft" mixture of the given prototypes. The mixing is achieved by + * proxying all property access to the ingredients. This is not ES5 compatible and less performant. However, any + * changes made to the source prototypes will be reflected in the proxy-prototype, which may be desirable. + */ +const softMixProtos = (ingredients, constructor) => proxyMix([...ingredients, { constructor }]); + +const settings = { + initFunction: null, + staticsStrategy: 'copy', + prototypeStrategy: 'copy', + decoratorInheritance: 'deep', +}; + +// Keeps track of constituent classes for every mixin class created by ts-mixer. +const mixins = new Map(); +const getMixinsForClass = (clazz) => mixins.get(clazz); +const registerMixins = (mixedClass, constituents) => mixins.set(mixedClass, constituents); +const hasMixin = (instance, mixin) => { + if (instance instanceof mixin) + return true; + const constructor = instance.constructor; + const visited = new Set(); + let frontier = new Set(); + frontier.add(constructor); + while (frontier.size > 0) { + // check if the frontier has the mixin we're looking for. if not, we can say we visited every item in the frontier + if (frontier.has(mixin)) + return true; + frontier.forEach(item => visited.add(item)); + // build a new frontier based on the associated mixin classes and prototype chains of each frontier item + const newFrontier = new Set(); + frontier.forEach(item => { + var _a; + const itemConstituents = (_a = mixins.get(item)) !== null && _a !== void 0 ? _a : protoChain(item.prototype).map(proto => proto.constructor).filter(item => item !== null); + if (itemConstituents) + itemConstituents.forEach(constituent => { + if (!visited.has(constituent) && !frontier.has(constituent)) + newFrontier.add(constituent); + }); + }); + // we have a new frontier, now search again + frontier = newFrontier; + } + // if we get here, we couldn't find the mixin anywhere in the prototype chain or associated mixin classes + return false; +}; + +const mergeObjectsOfDecorators = (o1, o2) => { + var _a, _b; + const allKeys = unique([...Object.getOwnPropertyNames(o1), ...Object.getOwnPropertyNames(o2)]); + const mergedObject = {}; + for (let key of allKeys) + mergedObject[key] = unique([...((_a = o1 === null || o1 === void 0 ? void 0 : o1[key]) !== null && _a !== void 0 ? _a : []), ...((_b = o2 === null || o2 === void 0 ? void 0 : o2[key]) !== null && _b !== void 0 ? _b : [])]); + return mergedObject; +}; +const mergePropertyAndMethodDecorators = (d1, d2) => { + var _a, _b, _c, _d; + return ({ + property: mergeObjectsOfDecorators((_a = d1 === null || d1 === void 0 ? void 0 : d1.property) !== null && _a !== void 0 ? _a : {}, (_b = d2 === null || d2 === void 0 ? void 0 : d2.property) !== null && _b !== void 0 ? _b : {}), + method: mergeObjectsOfDecorators((_c = d1 === null || d1 === void 0 ? void 0 : d1.method) !== null && _c !== void 0 ? _c : {}, (_d = d2 === null || d2 === void 0 ? void 0 : d2.method) !== null && _d !== void 0 ? _d : {}), + }); +}; +const mergeDecorators = (d1, d2) => { + var _a, _b, _c, _d, _e, _f; + return ({ + class: unique([...(_a = d1 === null || d1 === void 0 ? void 0 : d1.class) !== null && _a !== void 0 ? _a : [], ...(_b = d2 === null || d2 === void 0 ? void 0 : d2.class) !== null && _b !== void 0 ? _b : []]), + static: mergePropertyAndMethodDecorators((_c = d1 === null || d1 === void 0 ? void 0 : d1.static) !== null && _c !== void 0 ? _c : {}, (_d = d2 === null || d2 === void 0 ? void 0 : d2.static) !== null && _d !== void 0 ? _d : {}), + instance: mergePropertyAndMethodDecorators((_e = d1 === null || d1 === void 0 ? void 0 : d1.instance) !== null && _e !== void 0 ? _e : {}, (_f = d2 === null || d2 === void 0 ? void 0 : d2.instance) !== null && _f !== void 0 ? _f : {}), + }); +}; +const decorators = new Map(); +const findAllConstituentClasses = (...classes) => { + var _a; + const allClasses = new Set(); + const frontier = new Set([...classes]); + while (frontier.size > 0) { + for (let clazz of frontier) { + const protoChainClasses = protoChain(clazz.prototype).map(proto => proto.constructor); + const mixinClasses = (_a = getMixinsForClass(clazz)) !== null && _a !== void 0 ? _a : []; + const potentiallyNewClasses = [...protoChainClasses, ...mixinClasses]; + const newClasses = potentiallyNewClasses.filter(c => !allClasses.has(c)); + for (let newClass of newClasses) + frontier.add(newClass); + allClasses.add(clazz); + frontier.delete(clazz); + } + } + return [...allClasses]; +}; +const deepDecoratorSearch = (...classes) => { + const decoratorsForClassChain = findAllConstituentClasses(...classes) + .map(clazz => decorators.get(clazz)) + .filter(decorators => !!decorators); + if (decoratorsForClassChain.length == 0) + return {}; + if (decoratorsForClassChain.length == 1) + return decoratorsForClassChain[0]; + return decoratorsForClassChain.reduce((d1, d2) => mergeDecorators(d1, d2)); +}; +const directDecoratorSearch = (...classes) => { + const classDecorators = classes.map(clazz => getDecoratorsForClass(clazz)); + if (classDecorators.length === 0) + return {}; + if (classDecorators.length === 1) + return classDecorators[0]; + return classDecorators.reduce((d1, d2) => mergeDecorators(d1, d2)); +}; +const getDecoratorsForClass = (clazz) => { + let decoratorsForClass = decorators.get(clazz); + if (!decoratorsForClass) { + decoratorsForClass = {}; + decorators.set(clazz, decoratorsForClass); + } + return decoratorsForClass; +}; +const decorateClass = (decorator) => ((clazz) => { + const decoratorsForClass = getDecoratorsForClass(clazz); + let classDecorators = decoratorsForClass.class; + if (!classDecorators) { + classDecorators = []; + decoratorsForClass.class = classDecorators; + } + classDecorators.push(decorator); + return decorator(clazz); +}); +const decorateMember = (decorator) => ((object, key, ...otherArgs) => { + var _a, _b, _c; + const decoratorTargetType = typeof object === 'function' ? 'static' : 'instance'; + const decoratorType = typeof object[key] === 'function' ? 'method' : 'property'; + const clazz = decoratorTargetType === 'static' ? object : object.constructor; + const decoratorsForClass = getDecoratorsForClass(clazz); + const decoratorsForTargetType = (_a = decoratorsForClass === null || decoratorsForClass === void 0 ? void 0 : decoratorsForClass[decoratorTargetType]) !== null && _a !== void 0 ? _a : {}; + decoratorsForClass[decoratorTargetType] = decoratorsForTargetType; + let decoratorsForType = (_b = decoratorsForTargetType === null || decoratorsForTargetType === void 0 ? void 0 : decoratorsForTargetType[decoratorType]) !== null && _b !== void 0 ? _b : {}; + decoratorsForTargetType[decoratorType] = decoratorsForType; + let decoratorsForKey = (_c = decoratorsForType === null || decoratorsForType === void 0 ? void 0 : decoratorsForType[key]) !== null && _c !== void 0 ? _c : []; + decoratorsForType[key] = decoratorsForKey; + // @ts-ignore: array is type `A[] | B[]` and item is type `A | B`, so technically a type error, but it's fine + decoratorsForKey.push(decorator); + // @ts-ignore + return decorator(object, key, ...otherArgs); +}); +const decorate = (decorator) => ((...args) => { + if (args.length === 1) + return decorateClass(decorator)(args[0]); + return decorateMember(decorator)(...args); +}); + +function Mixin(...constructors) { + var _a, _b, _c; + const prototypes = constructors.map(constructor => constructor.prototype); + // Here we gather up the init functions of the ingredient prototypes, combine them into one init function, and + // attach it to the mixed class prototype. The reason we do this is because we want the init functions to mix + // similarly to constructors -- not methods, which simply override each other. + const initFunctionName = settings.initFunction; + if (initFunctionName !== null) { + const initFunctions = prototypes + .map(proto => proto[initFunctionName]) + .filter(func => typeof func === 'function'); + const combinedInitFunction = function (...args) { + for (let initFunction of initFunctions) + initFunction.apply(this, args); + }; + const extraProto = { [initFunctionName]: combinedInitFunction }; + prototypes.push(extraProto); + } + function MixedClass(...args) { + for (const constructor of constructors) + // @ts-ignore: potentially abstract class + copyProps(this, new constructor(...args)); + if (initFunctionName !== null && typeof this[initFunctionName] === 'function') + this[initFunctionName].apply(this, args); + } + MixedClass.prototype = settings.prototypeStrategy === 'copy' + ? hardMixProtos(prototypes, MixedClass) + : softMixProtos(prototypes, MixedClass); + Object.setPrototypeOf(MixedClass, settings.staticsStrategy === 'copy' + ? hardMixProtos(constructors, null, ['prototype']) + : proxyMix(constructors, Function.prototype)); + let DecoratedMixedClass = MixedClass; + if (settings.decoratorInheritance !== 'none') { + const classDecorators = settings.decoratorInheritance === 'deep' + ? deepDecoratorSearch(...constructors) + : directDecoratorSearch(...constructors); + for (let decorator of (_a = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.class) !== null && _a !== void 0 ? _a : []) { + const result = decorator(DecoratedMixedClass); + if (result) { + DecoratedMixedClass = result; + } + } + applyPropAndMethodDecorators((_b = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.static) !== null && _b !== void 0 ? _b : {}, DecoratedMixedClass); + applyPropAndMethodDecorators((_c = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.instance) !== null && _c !== void 0 ? _c : {}, DecoratedMixedClass.prototype); + } + registerMixins(DecoratedMixedClass, constructors); + return DecoratedMixedClass; +} +const applyPropAndMethodDecorators = (propAndMethodDecorators, target) => { + const propDecorators = propAndMethodDecorators.property; + const methodDecorators = propAndMethodDecorators.method; + if (propDecorators) + for (let key in propDecorators) + for (let decorator of propDecorators[key]) + decorator(target, key); + if (methodDecorators) + for (let key in methodDecorators) + for (let decorator of methodDecorators[key]) + decorator(target, key, Object.getOwnPropertyDescriptor(target, key)); +}; +/** + * A decorator version of the `Mixin` function. You'll want to use this instead of `Mixin` for mixing generic classes. + */ +const mix = (...ingredients) => decoratedClass => { + // @ts-ignore + const mixedClass = Mixin(...ingredients.concat([decoratedClass])); + Object.defineProperty(mixedClass, 'name', { + value: decoratedClass.name, + writable: false, + }); + return mixedClass; +}; + +export { Mixin, decorate, hasMixin, mix, settings }; diff --git a/node_modules/ts-mixer/dist/esm/index.min.js b/node_modules/ts-mixer/dist/esm/index.min.js new file mode 100644 index 0000000..04ab5ba --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/index.min.js @@ -0,0 +1 @@ +const t=(t,e,o=[])=>{const r=Object.getOwnPropertyDescriptors(e);for(let t of o)delete r[t];Object.defineProperties(t,r)},e=(t,o=[t])=>{const r=Object.getPrototypeOf(t);return null===r?o:e(r,[...o,r])},o=(o,r,n=[])=>{var l;const i=null!==(l=((...t)=>{if(0===t.length)return;let o;const r=t.map((t=>e(t)));for(;r.every((t=>t.length>0));){const t=r.map((t=>t.pop())),e=t[0];if(!t.every((t=>t===e)))break;o=e}return o})(...o))&&void 0!==l?l:Object.prototype,c=Object.create(i),s=e(i);for(let r of o){let o=e(r);for(let e=o.length-1;e>=0;e--){let r=o[e];-1===s.indexOf(r)&&(t(c,r,["constructor",...n]),s.push(r))}}return c.constructor=r,c},r=t=>t.filter(((e,o)=>t.indexOf(e)==o)),n=(t,o)=>{const r=o.map((t=>e(t)));let n=0,l=!0;for(;l;){l=!1;for(let e=o.length-1;e>=0;e--){const o=r[e][n];if(null!=o&&(l=!0,null!=Object.getOwnPropertyDescriptor(o,t)))return r[e][0]}n++}},l=(t,e=Object.prototype)=>new Proxy({},{getPrototypeOf:()=>e,setPrototypeOf(){throw Error("Cannot set prototype of Proxies created by ts-mixer")},getOwnPropertyDescriptor:(e,o)=>Object.getOwnPropertyDescriptor(n(o,t)||{},o),defineProperty(){throw new Error("Cannot define new properties on Proxies created by ts-mixer")},has:(o,r)=>void 0!==n(r,t)||void 0!==e[r],get:(o,r)=>(n(r,t)||e)[r],set(e,o,r){const l=n(o,t);if(void 0===l)throw new Error("Cannot set new properties on Proxies created by ts-mixer");return l[o]=r,!0},deleteProperty(){throw new Error("Cannot delete properties on Proxies created by ts-mixer")},ownKeys:()=>t.map(Object.getOwnPropertyNames).reduce(((t,e)=>e.concat(t.filter((t=>e.indexOf(t)<0)))))}),i={initFunction:null,staticsStrategy:"copy",prototypeStrategy:"copy",decoratorInheritance:"deep"},c=new Map,s=t=>c.get(t),p=(t,o)=>{if(t instanceof o)return!0;const r=t.constructor,n=new Set;let l=new Set;for(l.add(r);l.size>0;){if(l.has(o))return!0;l.forEach((t=>n.add(t)));const t=new Set;l.forEach((o=>{var r;const i=null!==(r=c.get(o))&&void 0!==r?r:e(o.prototype).map((t=>t.constructor)).filter((t=>null!==t));i&&i.forEach((e=>{n.has(e)||l.has(e)||t.add(e)}))})),l=t}return!1},u=(t,e)=>{var o,n;const l=r([...Object.getOwnPropertyNames(t),...Object.getOwnPropertyNames(e)]),i={};for(let c of l)i[c]=r([...null!==(o=null==t?void 0:t[c])&&void 0!==o?o:[],...null!==(n=null==e?void 0:e[c])&&void 0!==n?n:[]]);return i},a=(t,e)=>{var o,r,n,l;return{property:u(null!==(o=null==t?void 0:t.property)&&void 0!==o?o:{},null!==(r=null==e?void 0:e.property)&&void 0!==r?r:{}),method:u(null!==(n=null==t?void 0:t.method)&&void 0!==n?n:{},null!==(l=null==e?void 0:e.method)&&void 0!==l?l:{})}},d=(t,e)=>{var o,n,l,i,c,s;return{class:r([...null!==(o=null==t?void 0:t.class)&&void 0!==o?o:[],...null!==(n=null==e?void 0:e.class)&&void 0!==n?n:[]]),static:a(null!==(l=null==t?void 0:t.static)&&void 0!==l?l:{},null!==(i=null==e?void 0:e.static)&&void 0!==i?i:{}),instance:a(null!==(c=null==t?void 0:t.instance)&&void 0!==c?c:{},null!==(s=null==e?void 0:e.instance)&&void 0!==s?s:{})}},f=new Map,v=(...t)=>{const o=((...t)=>{var o;const r=new Set,n=new Set([...t]);for(;n.size>0;)for(let t of n){const l=[...e(t.prototype).map((t=>t.constructor)),...null!==(o=s(t))&&void 0!==o?o:[]].filter((t=>!r.has(t)));for(let t of l)n.add(t);r.add(t),n.delete(t)}return[...r]})(...t).map((t=>f.get(t))).filter((t=>!!t));return 0==o.length?{}:1==o.length?o[0]:o.reduce(((t,e)=>d(t,e)))},y=t=>{let e=f.get(t);return e||(e={},f.set(t,e)),e},h=t=>(...e)=>1===e.length?(t=>e=>{const o=y(e);let r=o.class;return r||(r=[],o.class=r),r.push(t),t(e)})(t)(e[0]):(t=>(e,o,...r)=>{var n,l,i;const c="function"==typeof e?"static":"instance",s="function"==typeof e[o]?"method":"property",p="static"===c?e:e.constructor,u=y(p),a=null!==(n=null==u?void 0:u[c])&&void 0!==n?n:{};u[c]=a;let d=null!==(l=null==a?void 0:a[s])&&void 0!==l?l:{};a[s]=d;let f=null!==(i=null==d?void 0:d[o])&&void 0!==i?i:[];return d[o]=f,f.push(t),t(e,o,...r)})(t)(...e);function O(...e){var r,n,s;const p=e.map((t=>t.prototype)),u=i.initFunction;if(null!==u){const t=p.map((t=>t[u])).filter((t=>"function"==typeof t)),e={[u]:function(...e){for(let o of t)o.apply(this,e)}};p.push(e)}function a(...o){for(const r of e)t(this,new r(...o));null!==u&&"function"==typeof this[u]&&this[u].apply(this,o)}var f,h;a.prototype="copy"===i.prototypeStrategy?o(p,a):(f=p,h=a,l([...f,{constructor:h}])),Object.setPrototypeOf(a,"copy"===i.staticsStrategy?o(e,null,["prototype"]):l(e,Function.prototype));let O=a;if("none"!==i.decoratorInheritance){const t="deep"===i.decoratorInheritance?v(...e):((...t)=>{const e=t.map((t=>y(t)));return 0===e.length?{}:1===e.length?e[0]:e.reduce(((t,e)=>d(t,e)))})(...e);for(let e of null!==(r=null==t?void 0:t.class)&&void 0!==r?r:[]){const t=e(O);t&&(O=t)}g(null!==(n=null==t?void 0:t.static)&&void 0!==n?n:{},O),g(null!==(s=null==t?void 0:t.instance)&&void 0!==s?s:{},O.prototype)}var w,m;return w=O,m=e,c.set(w,m),O}const g=(t,e)=>{const o=t.property,r=t.method;if(o)for(let t in o)for(let r of o[t])r(e,t);if(r)for(let t in r)for(let o of r[t])o(e,t,Object.getOwnPropertyDescriptor(e,t))},w=(...t)=>e=>{const o=O(...t.concat([e]));return Object.defineProperty(o,"name",{value:e.name,writable:!1}),o};export{O as Mixin,h as decorate,p as hasMixin,w as mix,i as settings}; diff --git a/node_modules/ts-mixer/dist/esm/mixin-tracking.d.ts b/node_modules/ts-mixer/dist/esm/mixin-tracking.d.ts new file mode 100644 index 0000000..1beaf87 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/mixin-tracking.d.ts @@ -0,0 +1,4 @@ +import { Class } from './types'; +export declare const getMixinsForClass: (clazz: Class) => Function[] | undefined; +export declare const registerMixins: (mixedClass: any, constituents: Function[]) => Map; +export declare const hasMixin: (instance: any, mixin: abstract new (...args: any[]) => M) => instance is M; diff --git a/node_modules/ts-mixer/dist/esm/mixins.d.ts b/node_modules/ts-mixer/dist/esm/mixins.d.ts new file mode 100644 index 0000000..a4f65be --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/mixins.d.ts @@ -0,0 +1,16 @@ +import { Class, Longest } from './types'; +declare function Mixin(c1: Class): Class; +declare function Mixin(c1: Class, c2: Class): Class, I1 & I2, S1 & S2>; +declare function Mixin(c1: Class, c2: Class, c3: Class): Class, I1 & I2 & I3, S1 & S2 & S3>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class): Class, I1 & I2 & I3 & I4, S1 & S2 & S3 & S4>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class): Class, I1 & I2 & I3 & I4 & I5, S1 & S2 & S3 & S4 & S5>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class): Class, I1 & I2 & I3 & I4 & I5 & I6, S1 & S2 & S3 & S4 & S5 & S6>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7, S1 & S2 & S3 & S4 & S5 & S6 & S7>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class, c9: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class, c9: Class, c10: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9 & I10, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10>; +/** + * A decorator version of the `Mixin` function. You'll want to use this instead of `Mixin` for mixing generic classes. + */ +declare const mix: (...ingredients: Class[]) => (decoratedClass: any) => any; +export { Mixin, mix }; diff --git a/node_modules/ts-mixer/dist/esm/proxy.d.ts b/node_modules/ts-mixer/dist/esm/proxy.d.ts new file mode 100644 index 0000000..fafe399 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/proxy.d.ts @@ -0,0 +1,16 @@ +/** + * Finds the ingredient with the given prop, searching in reverse order and breadth-first if searching ingredient + * prototypes is required. + */ +export declare const getIngredientWithProp: (prop: string | number | symbol, ingredients: any[]) => object | undefined; +/** + * "Mixes" ingredients by wrapping them in a Proxy. The optional prototype argument allows the mixed object to sit + * downstream of an existing prototype chain. Note that "properties" cannot be added, deleted, or modified. + */ +export declare const proxyMix: (ingredients: any[], prototype?: Object) => {}; +/** + * Creates a new proxy-prototype object that is a "soft" mixture of the given prototypes. The mixing is achieved by + * proxying all property access to the ingredients. This is not ES5 compatible and less performant. However, any + * changes made to the source prototypes will be reflected in the proxy-prototype, which may be desirable. + */ +export declare const softMixProtos: (ingredients: any[], constructor: Function) => object; diff --git a/node_modules/ts-mixer/dist/esm/settings.d.ts b/node_modules/ts-mixer/dist/esm/settings.d.ts new file mode 100644 index 0000000..d34d2b4 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/settings.d.ts @@ -0,0 +1,7 @@ +export type Settings = { + initFunction: string | null; + staticsStrategy: 'copy' | 'proxy'; + prototypeStrategy: 'copy' | 'proxy'; + decoratorInheritance: 'deep' | 'direct' | 'none'; +}; +export declare const settings: Settings; diff --git a/node_modules/ts-mixer/dist/esm/types.d.ts b/node_modules/ts-mixer/dist/esm/types.d.ts new file mode 100644 index 0000000..cb25fc1 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/types.d.ts @@ -0,0 +1,13 @@ +/** + * Returns the longer of the two tuples. Indefinite tuples will always be considered longest. + */ +type _Longest = any[] extends T1 ? T1 : any[] extends T2 ? T2 : Exclude extends never ? T2 : T1; +/** + * Returns the longest of up to 10 different tuples. + */ +export type Longest = _Longest<_Longest<_Longest<_Longest, _Longest>, _Longest<_Longest, _Longest>>, _Longest>; +/** + * A rigorous type alias for a class. + */ +export type Class = (abstract new (...args: any[]) => InstanceType) & StaticType; +export {}; diff --git a/node_modules/ts-mixer/dist/esm/util.d.ts b/node_modules/ts-mixer/dist/esm/util.d.ts new file mode 100644 index 0000000..4797ef4 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/util.d.ts @@ -0,0 +1,27 @@ +/** + * Utility function that works like `Object.apply`, but copies getters and setters properly as well. Additionally gives + * the option to exclude properties by name. + */ +export declare const copyProps: (dest: object, src: object, exclude?: string[]) => void; +/** + * Returns the full chain of prototypes up until Object.prototype given a starting object. The order of prototypes will + * be closest to farthest in the chain. + */ +export declare const protoChain: (obj: object, currentChain?: object[]) => object[]; +/** + * Identifies the nearest ancestor common to all the given objects in their prototype chains. For most unrelated + * objects, this function should return Object.prototype. + */ +export declare const nearestCommonProto: (...objs: object[]) => object | undefined; +/** + * Creates a new prototype object that is a mixture of the given prototypes. The mixing is achieved by first + * identifying the nearest common ancestor and using it as the prototype for a new object. Then all properties/methods + * downstream of this prototype (ONLY downstream) are copied into the new object. + * + * The resulting prototype is more performant than softMixProtos(...), as well as ES5 compatible. However, it's not as + * flexible as updates to the source prototypes aren't captured by the mixed result. See softMixProtos for why you may + * want to use that instead. + */ +export declare const hardMixProtos: (ingredients: any[], constructor: Function | null, exclude?: string[]) => object; +export declare const unique: (arr: T[]) => T[]; +export declare const flatten: (arr: T[][]) => T[]; diff --git a/node_modules/ts-mixer/dist/types/decorator.d.ts b/node_modules/ts-mixer/dist/types/decorator.d.ts new file mode 100644 index 0000000..dde5df2 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/decorator.d.ts @@ -0,0 +1,18 @@ +import { Class } from './types'; +type ObjectOfDecorators = { + [key: string]: T[]; +}; +export type PropertyAndMethodDecorators = { + property?: ObjectOfDecorators; + method?: ObjectOfDecorators; +}; +type Decorators = { + class?: ClassDecorator[]; + static?: PropertyAndMethodDecorators; + instance?: PropertyAndMethodDecorators; +}; +export declare const deepDecoratorSearch: (...classes: Class[]) => Decorators; +export declare const directDecoratorSearch: (...classes: Class[]) => Decorators; +export declare const getDecoratorsForClass: (clazz: Class) => Decorators; +export declare const decorate: (decorator: T) => T; +export {}; diff --git a/node_modules/ts-mixer/dist/types/index.d.ts b/node_modules/ts-mixer/dist/types/index.d.ts new file mode 100644 index 0000000..2a16080 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/index.d.ts @@ -0,0 +1,4 @@ +export { Mixin, mix } from './mixins'; +export { settings } from './settings'; +export { decorate } from './decorator'; +export { hasMixin } from './mixin-tracking'; diff --git a/node_modules/ts-mixer/dist/types/mixin-tracking.d.ts b/node_modules/ts-mixer/dist/types/mixin-tracking.d.ts new file mode 100644 index 0000000..1beaf87 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/mixin-tracking.d.ts @@ -0,0 +1,4 @@ +import { Class } from './types'; +export declare const getMixinsForClass: (clazz: Class) => Function[] | undefined; +export declare const registerMixins: (mixedClass: any, constituents: Function[]) => Map; +export declare const hasMixin: (instance: any, mixin: abstract new (...args: any[]) => M) => instance is M; diff --git a/node_modules/ts-mixer/dist/types/mixins.d.ts b/node_modules/ts-mixer/dist/types/mixins.d.ts new file mode 100644 index 0000000..a4f65be --- /dev/null +++ b/node_modules/ts-mixer/dist/types/mixins.d.ts @@ -0,0 +1,16 @@ +import { Class, Longest } from './types'; +declare function Mixin(c1: Class): Class; +declare function Mixin(c1: Class, c2: Class): Class, I1 & I2, S1 & S2>; +declare function Mixin(c1: Class, c2: Class, c3: Class): Class, I1 & I2 & I3, S1 & S2 & S3>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class): Class, I1 & I2 & I3 & I4, S1 & S2 & S3 & S4>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class): Class, I1 & I2 & I3 & I4 & I5, S1 & S2 & S3 & S4 & S5>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class): Class, I1 & I2 & I3 & I4 & I5 & I6, S1 & S2 & S3 & S4 & S5 & S6>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7, S1 & S2 & S3 & S4 & S5 & S6 & S7>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class, c9: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class, c9: Class, c10: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9 & I10, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10>; +/** + * A decorator version of the `Mixin` function. You'll want to use this instead of `Mixin` for mixing generic classes. + */ +declare const mix: (...ingredients: Class[]) => (decoratedClass: any) => any; +export { Mixin, mix }; diff --git a/node_modules/ts-mixer/dist/types/proxy.d.ts b/node_modules/ts-mixer/dist/types/proxy.d.ts new file mode 100644 index 0000000..fafe399 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/proxy.d.ts @@ -0,0 +1,16 @@ +/** + * Finds the ingredient with the given prop, searching in reverse order and breadth-first if searching ingredient + * prototypes is required. + */ +export declare const getIngredientWithProp: (prop: string | number | symbol, ingredients: any[]) => object | undefined; +/** + * "Mixes" ingredients by wrapping them in a Proxy. The optional prototype argument allows the mixed object to sit + * downstream of an existing prototype chain. Note that "properties" cannot be added, deleted, or modified. + */ +export declare const proxyMix: (ingredients: any[], prototype?: Object) => {}; +/** + * Creates a new proxy-prototype object that is a "soft" mixture of the given prototypes. The mixing is achieved by + * proxying all property access to the ingredients. This is not ES5 compatible and less performant. However, any + * changes made to the source prototypes will be reflected in the proxy-prototype, which may be desirable. + */ +export declare const softMixProtos: (ingredients: any[], constructor: Function) => object; diff --git a/node_modules/ts-mixer/dist/types/settings.d.ts b/node_modules/ts-mixer/dist/types/settings.d.ts new file mode 100644 index 0000000..d34d2b4 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/settings.d.ts @@ -0,0 +1,7 @@ +export type Settings = { + initFunction: string | null; + staticsStrategy: 'copy' | 'proxy'; + prototypeStrategy: 'copy' | 'proxy'; + decoratorInheritance: 'deep' | 'direct' | 'none'; +}; +export declare const settings: Settings; diff --git a/node_modules/ts-mixer/dist/types/types.d.ts b/node_modules/ts-mixer/dist/types/types.d.ts new file mode 100644 index 0000000..cb25fc1 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/types.d.ts @@ -0,0 +1,13 @@ +/** + * Returns the longer of the two tuples. Indefinite tuples will always be considered longest. + */ +type _Longest = any[] extends T1 ? T1 : any[] extends T2 ? T2 : Exclude extends never ? T2 : T1; +/** + * Returns the longest of up to 10 different tuples. + */ +export type Longest = _Longest<_Longest<_Longest<_Longest, _Longest>, _Longest<_Longest, _Longest>>, _Longest>; +/** + * A rigorous type alias for a class. + */ +export type Class = (abstract new (...args: any[]) => InstanceType) & StaticType; +export {}; diff --git a/node_modules/ts-mixer/dist/types/util.d.ts b/node_modules/ts-mixer/dist/types/util.d.ts new file mode 100644 index 0000000..4797ef4 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/util.d.ts @@ -0,0 +1,27 @@ +/** + * Utility function that works like `Object.apply`, but copies getters and setters properly as well. Additionally gives + * the option to exclude properties by name. + */ +export declare const copyProps: (dest: object, src: object, exclude?: string[]) => void; +/** + * Returns the full chain of prototypes up until Object.prototype given a starting object. The order of prototypes will + * be closest to farthest in the chain. + */ +export declare const protoChain: (obj: object, currentChain?: object[]) => object[]; +/** + * Identifies the nearest ancestor common to all the given objects in their prototype chains. For most unrelated + * objects, this function should return Object.prototype. + */ +export declare const nearestCommonProto: (...objs: object[]) => object | undefined; +/** + * Creates a new prototype object that is a mixture of the given prototypes. The mixing is achieved by first + * identifying the nearest common ancestor and using it as the prototype for a new object. Then all properties/methods + * downstream of this prototype (ONLY downstream) are copied into the new object. + * + * The resulting prototype is more performant than softMixProtos(...), as well as ES5 compatible. However, it's not as + * flexible as updates to the source prototypes aren't captured by the mixed result. See softMixProtos for why you may + * want to use that instead. + */ +export declare const hardMixProtos: (ingredients: any[], constructor: Function | null, exclude?: string[]) => object; +export declare const unique: (arr: T[]) => T[]; +export declare const flatten: (arr: T[][]) => T[]; diff --git a/node_modules/ts-mixer/package.json b/node_modules/ts-mixer/package.json new file mode 100644 index 0000000..ddb92f2 --- /dev/null +++ b/node_modules/ts-mixer/package.json @@ -0,0 +1,63 @@ +{ + "name": "ts-mixer", + "version": "6.0.3", + "description": "A very small TypeScript library that provides tolerable Mixin functionality.", + "main": "dist/cjs/index.js", + "module": "dist/esm/index.js", + "browser": "dist/esm/index.js", + "unpkg": "dist/esm/index.min.js", + "types": "dist/types/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "prebuild": "yarn clean", + "build": "rollup -c && tsc", + "clean": "rimraf dist", + "lint": "eslint src/**/*.ts", + "test": "nyc mocha", + "codegen": "node ./codegen.js", + "release": "standard-version" + }, + "devDependencies": { + "@commitlint/cli": "^12.1.4", + "@commitlint/config-conventional": "^12.1.4", + "@rollup/plugin-typescript": "^8.2.1", + "@types/chai": "^4.2.19", + "@types/mocha": "^8.2.2", + "@types/node": "^15.12.4", + "@types/sinon": "^10.0.2", + "@typescript-eslint/parser": "^4.27.0", + "chai": "^4.3.4", + "class-validator": "^0.13.1", + "coveralls": "^3.1.0", + "eslint": "^7.29.0", + "husky": "^4.2.5", + "js-yaml": "^4.1.0", + "mocha": "^9.0.1", + "nyc": "14.1.1", + "rimraf": "^3.0.2", + "rollup": "^2.52.1", + "rollup-plugin-terser": "^7.0.2", + "sinon": "^11.1.1", + "standard-version": "^9.3.0", + "ts-node": "^10.0.0", + "tslib": "^2.3.0", + "typescript": "^4.3.4", + "yarn-add-no-save": "^1.0.3" + }, + "homepage": "https://github.com/tannerntannern/ts-mixer#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/tannerntannern/ts-mixer.git" + }, + "keywords": [ + "typescript", + "mixin", + "mixins", + "multiple inheritance", + "mixin classes" + ], + "author": "Tanner Nielsen", + "license": "MIT" +} diff --git a/node_modules/tslib/CopyrightNotice.txt b/node_modules/tslib/CopyrightNotice.txt new file mode 100644 index 0000000..0e42542 --- /dev/null +++ b/node_modules/tslib/CopyrightNotice.txt @@ -0,0 +1,15 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + diff --git a/node_modules/tslib/LICENSE.txt b/node_modules/tslib/LICENSE.txt new file mode 100644 index 0000000..bfe6430 --- /dev/null +++ b/node_modules/tslib/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/node_modules/tslib/README.md b/node_modules/tslib/README.md new file mode 100644 index 0000000..72ff8e7 --- /dev/null +++ b/node_modules/tslib/README.md @@ -0,0 +1,164 @@ +# tslib + +This is a runtime library for [TypeScript](http://www.typescriptlang.org/) that contains all of the TypeScript helper functions. + +This library is primarily used by the `--importHelpers` flag in TypeScript. +When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file: + +```ts +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +exports.x = {}; +exports.y = __assign({}, exports.x); + +``` + +will instead be emitted as something like the following: + +```ts +var tslib_1 = require("tslib"); +exports.x = {}; +exports.y = tslib_1.__assign({}, exports.x); +``` + +Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead. +For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`. + +# Installing + +For the latest stable version, run: + +## npm + +```sh +# TypeScript 3.9.2 or later +npm install tslib + +# TypeScript 3.8.4 or earlier +npm install tslib@^1 + +# TypeScript 2.3.2 or earlier +npm install tslib@1.6.1 +``` + +## yarn + +```sh +# TypeScript 3.9.2 or later +yarn add tslib + +# TypeScript 3.8.4 or earlier +yarn add tslib@^1 + +# TypeScript 2.3.2 or earlier +yarn add tslib@1.6.1 +``` + +## bower + +```sh +# TypeScript 3.9.2 or later +bower install tslib + +# TypeScript 3.8.4 or earlier +bower install tslib@^1 + +# TypeScript 2.3.2 or earlier +bower install tslib@1.6.1 +``` + +## JSPM + +```sh +# TypeScript 3.9.2 or later +jspm install tslib + +# TypeScript 3.8.4 or earlier +jspm install tslib@^1 + +# TypeScript 2.3.2 or earlier +jspm install tslib@1.6.1 +``` + +# Usage + +Set the `importHelpers` compiler option on the command line: + +``` +tsc --importHelpers file.ts +``` + +or in your tsconfig.json: + +```json +{ + "compilerOptions": { + "importHelpers": true + } +} +``` + +#### For bower and JSPM users + +You will need to add a `paths` mapping for `tslib`, e.g. For Bower users: + +```json +{ + "compilerOptions": { + "module": "amd", + "importHelpers": true, + "baseUrl": "./", + "paths": { + "tslib" : ["bower_components/tslib/tslib.d.ts"] + } + } +} +``` + +For JSPM users: + +```json +{ + "compilerOptions": { + "module": "system", + "importHelpers": true, + "baseUrl": "./", + "paths": { + "tslib" : ["jspm_packages/npm/tslib@2.x.y/tslib.d.ts"] + } + } +} +``` + +## Deployment + +- Choose your new version number +- Set it in `package.json` and `bower.json` +- Create a tag: `git tag [version]` +- Push the tag: `git push --tags` +- Create a [release in GitHub](https://github.com/microsoft/tslib/releases) +- Run the [publish to npm](https://github.com/microsoft/tslib/actions?query=workflow%3A%22Publish+to+NPM%22) workflow + +Done. + +# Contribute + +There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. + +* [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. +* Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). +* Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). +* Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. +* [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). + +# Documentation + +* [Quick tutorial](http://www.typescriptlang.org/Tutorial) +* [Programming handbook](http://www.typescriptlang.org/Handbook) +* [Homepage](http://www.typescriptlang.org/) diff --git a/node_modules/tslib/SECURITY.md b/node_modules/tslib/SECURITY.md new file mode 100644 index 0000000..869fdfe --- /dev/null +++ b/node_modules/tslib/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). + + diff --git a/node_modules/tslib/modules/index.js b/node_modules/tslib/modules/index.js new file mode 100644 index 0000000..3ce70a5 --- /dev/null +++ b/node_modules/tslib/modules/index.js @@ -0,0 +1,63 @@ +import tslib from '../tslib.js'; +const { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, +} = tslib; +export { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, +}; diff --git a/node_modules/tslib/modules/package.json b/node_modules/tslib/modules/package.json new file mode 100644 index 0000000..aafa0e4 --- /dev/null +++ b/node_modules/tslib/modules/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/node_modules/tslib/package.json b/node_modules/tslib/package.json new file mode 100644 index 0000000..2386973 --- /dev/null +++ b/node_modules/tslib/package.json @@ -0,0 +1,38 @@ +{ + "name": "tslib", + "author": "Microsoft Corp.", + "homepage": "https://www.typescriptlang.org/", + "version": "2.5.0", + "license": "0BSD", + "description": "Runtime library for TypeScript helper functions", + "keywords": [ + "TypeScript", + "Microsoft", + "compiler", + "language", + "javascript", + "tslib", + "runtime" + ], + "bugs": { + "url": "https://github.com/Microsoft/TypeScript/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/tslib.git" + }, + "main": "tslib.js", + "module": "tslib.es6.js", + "jsnext:main": "tslib.es6.js", + "typings": "tslib.d.ts", + "sideEffects": false, + "exports": { + ".": { + "module": "./tslib.es6.js", + "import": "./modules/index.js", + "default": "./tslib.js" + }, + "./*": "./*", + "./": "./" + } +} diff --git a/node_modules/tslib/tslib.d.ts b/node_modules/tslib/tslib.d.ts new file mode 100644 index 0000000..f1c5208 --- /dev/null +++ b/node_modules/tslib/tslib.d.ts @@ -0,0 +1,430 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +/** + * Used to shim class extends. + * + * @param d The derived class. + * @param b The base class. + */ +export declare function __extends(d: Function, b: Function): void; + +/** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * + * @param t The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ +export declare function __assign(t: any, ...sources: any[]): any; + +/** + * Performs a rest spread on an object. + * + * @param t The source value. + * @param propertyNames The property names excluded from the rest spread. + */ +export declare function __rest(t: any, propertyNames: (string | symbol)[]): any; + +/** + * Applies decorators to a target object + * + * @param decorators The set of decorators to apply. + * @param target The target object. + * @param key If specified, the own property to apply the decorators to. + * @param desc The property descriptor, defaults to fetching the descriptor from the target object. + * @experimental + */ +export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any; + +/** + * Creates an observing function decorator from a parameter decorator. + * + * @param paramIndex The parameter index to apply the decorator to. + * @param decorator The parameter decorator to apply. Note that the return value is ignored. + * @experimental + */ +export declare function __param(paramIndex: number, decorator: Function): Function; + +/** + * Applies decorators to a class or class member, following the native ECMAScript decorator specification. + * @param ctor For non-field class members, the class constructor. Otherwise, `null`. + * @param descriptorIn The `PropertyDescriptor` to use when unable to look up the property from `ctor`. + * @param decorators The decorators to apply + * @param contextIn The `DecoratorContext` to clone for each decorator application. + * @param initializers An array of field initializer mutation functions into which new initializers are written. + * @param extraInitializers An array of extra initializer functions into which new initializers are written. + */ +export declare function __esDecorate(ctor: Function | null, descriptorIn: object | null, decorators: Function[], contextIn: object, initializers: Function[] | null, extraInitializers: Function[]): void; + +/** + * Runs field initializers or extra initializers generated by `__esDecorate`. + * @param thisArg The `this` argument to use. + * @param initializers The array of initializers to evaluate. + * @param value The initial value to pass to the initializers. + */ +export declare function __runInitializers(thisArg: unknown, initializers: Function[], value?: any): any; + +/** + * Converts a computed property name into a `string` or `symbol` value. + */ +export declare function __propKey(x: any): string | symbol; + +/** + * Assigns the name of a function derived from the left-hand side of an assignment. + * @param f The function to rename. + * @param name The new name for the function. + * @param prefix A prefix (such as `"get"` or `"set"`) to insert before the name. + */ +export declare function __setFunctionName(f: Function, name: string | symbol, prefix?: string): Function; + +/** + * Creates a decorator that sets metadata. + * + * @param metadataKey The metadata key + * @param metadataValue The metadata value + * @experimental + */ +export declare function __metadata(metadataKey: any, metadataValue: any): Function; + +/** + * Converts a generator function into a pseudo-async function, by treating each `yield` as an `await`. + * + * @param thisArg The reference to use as the `this` value in the generator function + * @param _arguments The optional arguments array + * @param P The optional promise constructor argument, defaults to the `Promise` property of the global object. + * @param generator The generator function + */ +export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any; + +/** + * Creates an Iterator object using the body as the implementation. + * + * @param thisArg The reference to use as the `this` value in the function + * @param body The generator state-machine based implementation. + * + * @see [./docs/generator.md] + */ +export declare function __generator(thisArg: any, body: Function): any; + +/** + * Creates bindings for all enumerable properties of `m` on `exports` + * + * @param m The source object + * @param exports The `exports` object. + */ +export declare function __exportStar(m: any, o: any): void; + +/** + * Creates a value iterator from an `Iterable` or `ArrayLike` object. + * + * @param o The object. + * @throws {TypeError} If `o` is neither `Iterable`, nor an `ArrayLike`. + */ +export declare function __values(o: any): any; + +/** + * Reads values from an `Iterable` or `ArrayLike` object and returns the resulting array. + * + * @param o The object to read from. + * @param n The maximum number of arguments to read, defaults to `Infinity`. + */ +export declare function __read(o: any, n?: number): any[]; + +/** + * Creates an array from iterable spread. + * + * @param args The Iterable objects to spread. + * @deprecated since TypeScript 4.2 - Use `__spreadArray` + */ +export declare function __spread(...args: any[][]): any[]; + +/** + * Creates an array from array spread. + * + * @param args The ArrayLikes to spread into the resulting array. + * @deprecated since TypeScript 4.2 - Use `__spreadArray` + */ +export declare function __spreadArrays(...args: any[][]): any[]; + +/** + * Spreads the `from` array into the `to` array. + * + * @param pack Replace empty elements with `undefined`. + */ +export declare function __spreadArray(to: any[], from: any[], pack?: boolean): any[]; + +/** + * Creates an object that signals to `__asyncGenerator` that it shouldn't be yielded, + * and instead should be awaited and the resulting value passed back to the generator. + * + * @param v The value to await. + */ +export declare function __await(v: any): any; + +/** + * Converts a generator function into an async generator function, by using `yield __await` + * in place of normal `await`. + * + * @param thisArg The reference to use as the `this` value in the generator function + * @param _arguments The optional arguments array + * @param generator The generator function + */ +export declare function __asyncGenerator(thisArg: any, _arguments: any, generator: Function): any; + +/** + * Used to wrap a potentially async iterator in such a way so that it wraps the result + * of calling iterator methods of `o` in `__await` instances, and then yields the awaited values. + * + * @param o The potentially async iterator. + * @returns A synchronous iterator yielding `__await` instances on every odd invocation + * and returning the awaited `IteratorResult` passed to `next` every even invocation. + */ +export declare function __asyncDelegator(o: any): any; + +/** + * Creates a value async iterator from an `AsyncIterable`, `Iterable` or `ArrayLike` object. + * + * @param o The object. + * @throws {TypeError} If `o` is neither `AsyncIterable`, `Iterable`, nor an `ArrayLike`. + */ +export declare function __asyncValues(o: any): any; + +/** + * Creates a `TemplateStringsArray` frozen object from the `cooked` and `raw` arrays. + * + * @param cooked The cooked possibly-sparse array. + * @param raw The raw string content. + */ +export declare function __makeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray; + +/** + * Used to shim default and named imports in ECMAScript Modules transpiled to CommonJS. + * + * ```js + * import Default, { Named, Other } from "mod"; + * // or + * import { default as Default, Named, Other } from "mod"; + * ``` + * + * @param mod The CommonJS module exports object. + */ +export declare function __importStar(mod: T): T; + +/** + * Used to shim default imports in ECMAScript Modules transpiled to CommonJS. + * + * ```js + * import Default from "mod"; + * ``` + * + * @param mod The CommonJS module exports object. + */ +export declare function __importDefault(mod: T): T | { default: T }; + +/** + * Emulates reading a private instance field. + * + * @param receiver The instance from which to read the private field. + * @param state A WeakMap containing the private field value for an instance. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet( + receiver: T, + state: { has(o: T): boolean, get(o: T): V | undefined }, + kind?: "f" +): V; + +/** + * Emulates reading a private static field. + * + * @param receiver The object from which to read the private static field. + * @param state The class constructor containing the definition of the static field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The descriptor that holds the static field value. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V>( + receiver: T, + state: T, + kind: "f", + f: { value: V } +): V; + +/** + * Emulates evaluating a private instance "get" accessor. + * + * @param receiver The instance on which to evaluate the private "get" accessor. + * @param state A WeakSet used to verify an instance supports the private "get" accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "get" accessor function to evaluate. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet( + receiver: T, + state: { has(o: T): boolean }, + kind: "a", + f: () => V +): V; + +/** + * Emulates evaluating a private static "get" accessor. + * + * @param receiver The object on which to evaluate the private static "get" accessor. + * @param state The class constructor containing the definition of the static "get" accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "get" accessor function to evaluate. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V>( + receiver: T, + state: T, + kind: "a", + f: () => V +): V; + +/** + * Emulates reading a private instance method. + * + * @param receiver The instance from which to read a private method. + * @param state A WeakSet used to verify an instance supports the private method. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The function to return as the private instance method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet unknown>( + receiver: T, + state: { has(o: T): boolean }, + kind: "m", + f: V +): V; + +/** + * Emulates reading a private static method. + * + * @param receiver The object from which to read the private static method. + * @param state The class constructor containing the definition of the static method. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The function to return as the private static method. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V extends (...args: any[]) => unknown>( + receiver: T, + state: T, + kind: "m", + f: V +): V; + +/** + * Emulates writing to a private instance field. + * + * @param receiver The instance on which to set a private field value. + * @param state A WeakMap used to store the private field value for an instance. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldSet( + receiver: T, + state: { has(o: T): boolean, set(o: T, value: V): unknown }, + value: V, + kind?: "f" +): V; + +/** + * Emulates writing to a private static field. + * + * @param receiver The object on which to set the private static field. + * @param state The class constructor containing the definition of the private static field. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The descriptor that holds the static field value. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldSet unknown, V>( + receiver: T, + state: T, + value: V, + kind: "f", + f: { value: V } +): V; + +/** + * Emulates writing to a private instance "set" accessor. + * + * @param receiver The instance on which to evaluate the private instance "set" accessor. + * @param state A WeakSet used to verify an instance supports the private "set" accessor. + * @param value The value to store in the private accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "set" accessor function to evaluate. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldSet( + receiver: T, + state: { has(o: T): boolean }, + value: V, + kind: "a", + f: (v: V) => void +): V; + +/** + * Emulates writing to a private static "set" accessor. + * + * @param receiver The object on which to evaluate the private static "set" accessor. + * @param state The class constructor containing the definition of the static "set" accessor. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "set" accessor function to evaluate. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldSet unknown, V>( + receiver: T, + state: T, + value: V, + kind: "a", + f: (v: V) => void +): V; + +/** + * Checks for the existence of a private field/method/accessor. + * + * @param state The class constructor containing the static member, or the WeakMap or WeakSet associated with a private instance member. + * @param receiver The object for which to test the presence of the private member. + */ +export declare function __classPrivateFieldIn( + state: (new (...args: any[]) => unknown) | { has(o: any): boolean }, + receiver: unknown, +): boolean; + +/** + * Creates a re-export binding on `object` with key `objectKey` that references `target[key]`. + * + * @param object The local `exports` object. + * @param target The object to re-export from. + * @param key The property key of `target` to re-export. + * @param objectKey The property key to re-export as. Defaults to `key`. + */ +export declare function __createBinding(object: object, target: object, key: PropertyKey, objectKey?: PropertyKey): void; diff --git a/node_modules/tslib/tslib.es6.html b/node_modules/tslib/tslib.es6.html new file mode 100644 index 0000000..b122e41 --- /dev/null +++ b/node_modules/tslib/tslib.es6.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/tslib/tslib.es6.js b/node_modules/tslib/tslib.es6.js new file mode 100644 index 0000000..1002dfc --- /dev/null +++ b/node_modules/tslib/tslib.es6.js @@ -0,0 +1,293 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.push(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.push(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __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]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} diff --git a/node_modules/tslib/tslib.html b/node_modules/tslib/tslib.html new file mode 100644 index 0000000..44c9ba5 --- /dev/null +++ b/node_modules/tslib/tslib.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/tslib/tslib.js b/node_modules/tslib/tslib.js new file mode 100644 index 0000000..0f0e892 --- /dev/null +++ b/node_modules/tslib/tslib.js @@ -0,0 +1,370 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __classPrivateFieldIn; +var __createBinding; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if (typeof module === "object" && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.push(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.push(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __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]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); +}); diff --git a/node_modules/tunnel-agent/LICENSE b/node_modules/tunnel-agent/LICENSE new file mode 100644 index 0000000..a4a9aee --- /dev/null +++ b/node_modules/tunnel-agent/LICENSE @@ -0,0 +1,55 @@ +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: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +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 + +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 \ No newline at end of file diff --git a/node_modules/tunnel-agent/README.md b/node_modules/tunnel-agent/README.md new file mode 100644 index 0000000..bb533d5 --- /dev/null +++ b/node_modules/tunnel-agent/README.md @@ -0,0 +1,4 @@ +tunnel-agent +============ + +HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. diff --git a/node_modules/tunnel-agent/index.js b/node_modules/tunnel-agent/index.js new file mode 100644 index 0000000..3ee9abc --- /dev/null +++ b/node_modules/tunnel-agent/index.js @@ -0,0 +1,244 @@ +'use strict' + +var net = require('net') + , tls = require('tls') + , http = require('http') + , https = require('https') + , events = require('events') + , assert = require('assert') + , util = require('util') + , Buffer = require('safe-buffer').Buffer + ; + +exports.httpOverHttp = httpOverHttp +exports.httpsOverHttp = httpsOverHttp +exports.httpOverHttps = httpOverHttps +exports.httpsOverHttps = httpsOverHttps + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options) + agent.request = http.request + return agent +} + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options) + agent.request = http.request + agent.createSocket = createSecureSocket + agent.defaultPort = 443 + return agent +} + +function httpOverHttps(options) { + var agent = new TunnelingAgent(options) + agent.request = https.request + return agent +} + +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options) + agent.request = https.request + agent.createSocket = createSecureSocket + agent.defaultPort = 443 + return agent +} + + +function TunnelingAgent(options) { + var self = this + self.options = options || {} + self.proxyOptions = self.options.proxy || {} + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets + self.requests = [] + self.sockets = [] + + self.on('free', function onFree(socket, host, port) { + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i] + if (pending.host === host && pending.port === port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1) + pending.request.onSocket(socket) + return + } + } + socket.destroy() + self.removeSocket(socket) + }) +} +util.inherits(TunnelingAgent, events.EventEmitter) + +TunnelingAgent.prototype.addRequest = function addRequest(req, options) { + var self = this + + // Legacy API: addRequest(req, host, port, path) + if (typeof options === 'string') { + options = { + host: options, + port: arguments[2], + path: arguments[3] + }; + } + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push({host: options.host, port: options.port, request: req}) + return + } + + // If we are under maxSockets create a new one. + self.createConnection({host: options.host, port: options.port, request: req}) +} + +TunnelingAgent.prototype.createConnection = function createConnection(pending) { + var self = this + + self.createSocket(pending, function(socket) { + socket.on('free', onFree) + socket.on('close', onCloseOrRemove) + socket.on('agentRemove', onCloseOrRemove) + pending.request.onSocket(socket) + + function onFree() { + self.emit('free', socket, pending.host, pending.port) + } + + function onCloseOrRemove(err) { + self.removeSocket(socket) + socket.removeListener('free', onFree) + socket.removeListener('close', onCloseOrRemove) + socket.removeListener('agentRemove', onCloseOrRemove) + } + }) +} + +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this + var placeholder = {} + self.sockets.push(placeholder) + + var connectOptions = mergeOptions({}, self.proxyOptions, + { method: 'CONNECT' + , path: options.host + ':' + options.port + , agent: false + } + ) + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {} + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + Buffer.from(connectOptions.proxyAuth).toString('base64') + } + + debug('making CONNECT request') + var connectReq = self.request(connectOptions) + connectReq.useChunkedEncodingByDefault = false // for v0.6 + connectReq.once('response', onResponse) // for v0.6 + connectReq.once('upgrade', onUpgrade) // for v0.6 + connectReq.once('connect', onConnect) // for v0.7 or later + connectReq.once('error', onError) + connectReq.end() + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head) + }) + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners() + socket.removeAllListeners() + + if (res.statusCode === 200) { + assert.equal(head.length, 0) + debug('tunneling connection has established') + self.sockets[self.sockets.indexOf(placeholder)] = socket + cb(socket) + } else { + debug('tunneling socket could not be established, statusCode=%d', res.statusCode) + var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode) + error.code = 'ECONNRESET' + options.request.emit('error', error) + self.removeSocket(placeholder) + } + } + + function onError(cause) { + connectReq.removeAllListeners() + + debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack) + var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message) + error.code = 'ECONNRESET' + options.request.emit('error', error) + self.removeSocket(placeholder) + } +} + +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) return + + this.sockets.splice(pos, 1) + + var pending = this.requests.shift() + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createConnection(pending) + } +} + +function createSecureSocket(options, cb) { + var self = this + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, mergeOptions({}, self.options, + { servername: options.host + , socket: socket + } + )) + self.sockets[self.sockets.indexOf(socket)] = secureSocket + cb(secureSocket) + }) +} + + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i] + if (typeof overrides === 'object') { + var keys = Object.keys(overrides) + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j] + if (overrides[k] !== undefined) { + target[k] = overrides[k] + } + } + } + } + return target +} + + +var debug +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments) + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0] + } else { + args.unshift('TUNNEL:') + } + console.error.apply(console, args) + } +} else { + debug = function() {} +} +exports.debug = debug // for test diff --git a/node_modules/tunnel-agent/package.json b/node_modules/tunnel-agent/package.json new file mode 100644 index 0000000..94ada98 --- /dev/null +++ b/node_modules/tunnel-agent/package.json @@ -0,0 +1,58 @@ +{ + "_args": [ + [ + "tunnel-agent@0.6.0", + "/home/other/discord_bot" + ] + ], + "_from": "tunnel-agent@0.6.0", + "_id": "tunnel-agent@0.6.0", + "_inBundle": false, + "_integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "_location": "/tunnel-agent", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "tunnel-agent@0.6.0", + "name": "tunnel-agent", + "escapedName": "tunnel-agent", + "rawSpec": "0.6.0", + "saveSpec": null, + "fetchSpec": "0.6.0" + }, + "_requiredBy": [ + "/faye" + ], + "_resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "_spec": "0.6.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Mikeal Rogers", + "email": "mikeal.rogers@gmail.com", + "url": "http://www.futurealoof.com" + }, + "bugs": { + "url": "https://github.com/mikeal/tunnel-agent/issues" + }, + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "description": "HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module.", + "devDependencies": {}, + "engines": { + "node": "*" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/mikeal/tunnel-agent#readme", + "license": "Apache-2.0", + "main": "index.js", + "name": "tunnel-agent", + "optionalDependencies": {}, + "repository": { + "url": "git+https://github.com/mikeal/tunnel-agent.git" + }, + "version": "0.6.0" +} diff --git a/node_modules/type-fest/base.d.ts b/node_modules/type-fest/base.d.ts new file mode 100644 index 0000000..9005ef9 --- /dev/null +++ b/node_modules/type-fest/base.d.ts @@ -0,0 +1,38 @@ +// Types that are compatible with all supported TypeScript versions. +// It's shared between all TypeScript version-specific definitions. + +// Basic +export * from './source/basic'; + +// Utilities +export {Except} from './source/except'; +export {Mutable} from './source/mutable'; +export {Merge} from './source/merge'; +export {MergeExclusive} from './source/merge-exclusive'; +export {RequireAtLeastOne} from './source/require-at-least-one'; +export {RequireExactlyOne} from './source/require-exactly-one'; +export {PartialDeep} from './source/partial-deep'; +export {ReadonlyDeep} from './source/readonly-deep'; +export {LiteralUnion} from './source/literal-union'; +export {Promisable} from './source/promisable'; +export {Opaque} from './source/opaque'; +export {SetOptional} from './source/set-optional'; +export {SetRequired} from './source/set-required'; +export {ValueOf} from './source/value-of'; +export {PromiseValue} from './source/promise-value'; +export {AsyncReturnType} from './source/async-return-type'; +export {ConditionalExcept} from './source/conditional-except'; +export {ConditionalKeys} from './source/conditional-keys'; +export {ConditionalPick} from './source/conditional-pick'; +export {UnionToIntersection} from './source/union-to-intersection'; +export {Stringified} from './source/stringified'; +export {FixedLengthArray} from './source/fixed-length-array'; +export {IterableElement} from './source/iterable-element'; +export {Entry} from './source/entry'; +export {Entries} from './source/entries'; +export {SetReturnType} from './source/set-return-type'; +export {Asyncify} from './source/asyncify'; + +// Miscellaneous +export {PackageJson} from './source/package-json'; +export {TsConfigJson} from './source/tsconfig-json'; diff --git a/node_modules/type-fest/index.d.ts b/node_modules/type-fest/index.d.ts new file mode 100644 index 0000000..206261c --- /dev/null +++ b/node_modules/type-fest/index.d.ts @@ -0,0 +1,2 @@ +// These are all the basic types that's compatible with all supported TypeScript versions. +export * from './base'; diff --git a/node_modules/type-fest/license b/node_modules/type-fest/license new file mode 100644 index 0000000..3e4c85a --- /dev/null +++ b/node_modules/type-fest/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https:/sindresorhus.com) + +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/type-fest/package.json b/node_modules/type-fest/package.json new file mode 100644 index 0000000..37c89e6 --- /dev/null +++ b/node_modules/type-fest/package.json @@ -0,0 +1,93 @@ +{ + "_args": [ + [ + "type-fest@0.20.2", + "/home/other/discord_bot" + ] + ], + "_from": "type-fest@0.20.2", + "_id": "type-fest@0.20.2", + "_inBundle": false, + "_integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "_location": "/type-fest", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "type-fest@0.20.2", + "name": "type-fest", + "escapedName": "type-fest", + "rawSpec": "0.20.2", + "saveSpec": null, + "fetchSpec": "0.20.2" + }, + "_requiredBy": [ + "/boxen" + ], + "_resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "_spec": "0.20.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/type-fest/issues" + }, + "description": "A collection of essential TypeScript types", + "devDependencies": { + "@sindresorhus/tsconfig": "~0.7.0", + "tsd": "^0.13.1", + "typescript": "^4.1.2", + "xo": "^0.35.0" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.d.ts", + "base.d.ts", + "source", + "ts41" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/type-fest#readme", + "keywords": [ + "typescript", + "ts", + "types", + "utility", + "util", + "utilities", + "omit", + "merge", + "json" + ], + "license": "(MIT OR CC0-1.0)", + "name": "type-fest", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/type-fest.git" + }, + "scripts": { + "//test": "xo && tsd && tsc", + "test": "xo && tsc" + }, + "types": "./index.d.ts", + "typesVersions": { + ">=4.1": { + "*": [ + "ts41/*" + ] + } + }, + "version": "0.20.2", + "xo": { + "rules": { + "@typescript-eslint/ban-types": "off", + "@typescript-eslint/indent": "off", + "node/no-unsupported-features/es-builtins": "off" + } + } +} diff --git a/node_modules/type-fest/readme.md b/node_modules/type-fest/readme.md new file mode 100644 index 0000000..714df78 --- /dev/null +++ b/node_modules/type-fest/readme.md @@ -0,0 +1,658 @@ +
+
+
+ type-fest +
+
+ A collection of essential TypeScript types +
+
+
+
+
+ +[![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://giphy.com/gifs/illustration-rainbow-unicorn-26AHG5KGFxSkUWw1i) + + +Many of the types here should have been built-in. You can help by suggesting some of them to the [TypeScript project](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). + +Either add this package as a dependency or copy-paste the needed types. No credit required. 👌 + +PR welcome for additional commonly needed types and docs improvements. Read the [contributing guidelines](.github/contributing.md) first. + +## Install + +``` +$ npm install type-fest +``` + +*Requires TypeScript >=3.4* + +## Usage + +```ts +import {Except} from 'type-fest'; + +type Foo = { + unicorn: string; + rainbow: boolean; +}; + +type FooWithoutRainbow = Except; +//=> {unicorn: string} +``` + +## API + +Click the type names for complete docs. + +### Basic + +- [`Primitive`](source/basic.d.ts) - Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). +- [`Class`](source/basic.d.ts) - Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). +- [`TypedArray`](source/basic.d.ts) - Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`. +- [`JsonObject`](source/basic.d.ts) - Matches a JSON object. +- [`JsonArray`](source/basic.d.ts) - Matches a JSON array. +- [`JsonValue`](source/basic.d.ts) - Matches any valid JSON value. +- [`ObservableLike`](source/basic.d.ts) - Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable). + +### Utilities + +- [`Except`](source/except.d.ts) - Create a type from an object type without certain keys. This is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). +- [`Mutable`](source/mutable.d.ts) - Convert an object with `readonly` keys into a mutable object. The inverse of `Readonly`. +- [`Merge`](source/merge.d.ts) - Merge two types into a new type. Keys of the second type overrides keys of the first type. +- [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys. +- [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys. +- [`RequireExactlyOne`](source/require-exactly-one.d.ts) - Create a type that requires exactly a single key of the given keys and disallows more. +- [`PartialDeep`](source/partial-deep.d.ts) - Create a deeply optional version of another type. Use [`Partial`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) if you only need one level deep. +- [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of an `object`/`Map`/`Set`/`Array` type. Use [`Readonly`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) if you only need one level deep. +- [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). +- [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`. +- [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/). +- [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional. +- [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required. +- [`ValueOf`](source/value-of.d.ts) - Create a union of the given object's values, and optionally specify which keys to get the values from. +- [`PromiseValue`](source/promise-value.d.ts) - Returns the type that is wrapped inside a `Promise`. +- [`AsyncReturnType`](source/async-return-type.d.ts) - Unwrap the return type of a function that returns a `Promise`. +- [`ConditionalKeys`](source/conditional-keys.d.ts) - Extract keys from a shape where values extend the given `Condition` type. +- [`ConditionalPick`](source/conditional-pick.d.ts) - Like `Pick` except it selects properties from a shape where the values extend the given `Condition` type. +- [`ConditionalExcept`](source/conditional-except.d.ts) - Like `Omit` except it removes properties from a shape where the values extend the given `Condition` type. +- [`UnionToIntersection`](source/union-to-intersection.d.ts) - Convert a union type to an intersection type. +- [`Stringified`](source/stringified.d.ts) - Create a type with the keys of the given type changed to `string` type. +- [`FixedLengthArray`](source/fixed-length-array.d.ts) - Create a type that represents an array of the given type and length. +- [`IterableElement`](source/iterable-element.d.ts) - Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator. +- [`Entry`](source/entry.d.ts) - Create a type that represents the type of an entry of a collection. +- [`Entries`](source/entries.d.ts) - Create a type that represents the type of the entries of a collection. +- [`SetReturnType`](source/set-return-type.d.ts) - Create a function type with a return type of your choice and the same parameters as the given function type. +- [`Asyncify`](source/asyncify.d.ts) - Create an async version of the given function type. + +### Template literal types + +*Note:* These require [TypeScript 4.1 or newer](https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#template-literal-types). + +- [`CamelCase`](ts41/camel-case.d.ts) – Convert a string literal to camel-case (`fooBar`). +- [`KebabCase`](ts41/kebab-case.d.ts) – Convert a string literal to kebab-case (`foo-bar`). +- [`PascalCase`](ts41/pascal-case.d.ts) – Converts a string literal to pascal-case (`FooBar`) +- [`SnakeCase`](ts41/snake-case.d.ts) – Convert a string literal to snake-case (`foo_bar`). +- [`DelimiterCase`](ts41/delimiter-case.d.ts) – Convert a string literal to a custom string delimiter casing. + +### Miscellaneous + +- [`PackageJson`](source/package-json.d.ts) - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). +- [`TsConfigJson`](source/tsconfig-json.d.ts) - Type for [TypeScript's `tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) (TypeScript 3.7). + +## Declined types + +*If we decline a type addition, we will make sure to document the better solution here.* + +- [`Diff` and `Spread`](https://github.com/sindresorhus/type-fest/pull/7) - The PR author didn't provide any real-world use-cases and the PR went stale. If you think this type is useful, provide some real-world use-cases and we might reconsider. +- [`Dictionary`](https://github.com/sindresorhus/type-fest/issues/33) - You only save a few characters (`Dictionary` vs `Record`) from [`Record`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434), which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We have `Map` in JavaScript now. +- [`SubType`](https://github.com/sindresorhus/type-fest/issues/22) - The type is powerful, but lacks good use-cases and is prone to misuse. +- [`ExtractProperties` and `ExtractMethods`](https://github.com/sindresorhus/type-fest/pull/4) - The types violate the single responsibility principle. Instead, refine your types into more granular type hierarchies. + +## Tips + +### Built-in types + +There are many advanced types most users don't know about. + +- [`Partial`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1401-L1406) - Make all properties in `T` optional. +
+ + Example + + + [Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA) + + ```ts + interface NodeConfig { + appName: string; + port: number; + } + + class NodeAppBuilder { + private configuration: NodeConfig = { + appName: 'NodeApp', + port: 3000 + }; + + private updateConfig(key: Key, value: NodeConfig[Key]) { + this.configuration[key] = value; + } + + config(config: Partial) { + type NodeConfigKey = keyof NodeConfig; + + for (const key of Object.keys(config) as NodeConfigKey[]) { + const updateValue = config[key]; + + if (updateValue === undefined) { + continue; + } + + this.updateConfig(key, updateValue); + } + + return this; + } + } + + // `Partial`` allows us to provide only a part of the + // NodeConfig interface. + new NodeAppBuilder().config({appName: 'ToDoApp'}); + ``` +
+ +- [`Required`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1408-L1413) - Make all properties in `T` required. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgGED21VQGJZwC2wA3gFCjXAzFJgA2A-AFzADOUckA5gNxUaIYjA4ckvGG07c+g6gF8KQkAgCuEFFDA5O6gEbEwUbLm2ESwABQIixACJIoSdgCUYAR3Vg4MACYAPGYuFvYAfACU5Ko0APRxwADKMBD+wFAAFuh2Vv7OSBlYGdmc8ABu8LHKsRyGxqY4oQT21pTCIHQMjOwA5DAAHgACxAAOjDAAdChYxL0ANLHUouKSMH0AEmAAhJhY6ozpAJ77GTCMjMCiV0ToSAb7UJPPC9WRgrEJwAAqR6MwSRQPFGUFocDgRHYxnEfGAowh-zgUCOwF6KwkUl6tXqJhCeEsxDaS1AXSYfUGI3GUxmc0WSneQA) + + ```ts + interface ContactForm { + email?: string; + message?: string; + } + + function submitContactForm(formData: Required) { + // Send the form data to the server. + } + + submitContactForm({ + email: 'ex@mple.com', + message: 'Hi! Could you tell me more about…', + }); + + // TypeScript error: missing property 'message' + submitContactForm({ + email: 'ex@mple.com', + }); + ``` +
+ +- [`Readonly`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1415-L1420) - Make all properties in `T` readonly. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/AQ4UwOwVwW2AZA9gc3mAbmANsA3gKFCOAHkAzMgGkOJABEwAjKZa2kAUQCcvEu32AMQCGAF2FYBIAL4BufDRABLCKLBcywgMZgEKZOoDCiCGSXI8i4hGEwwALmABnUVxXJ57YFgzZHSVF8sT1BpBSItLGEnJz1kAy5LLy0TM2RHACUwYQATEywATwAeAITjU3MAPnkrCJMXLigtUT4AClxgGztKbyDgaX99I1TzAEokr1BRAAslJwA6FIqLAF48TtswHp9MHDla9hJGACswZvmyLjAwAC8wVpm5xZHkUZDaMKIwqyWXYCW0oN4sNlsA1h0ug5gAByACyBQAggAHJHQ7ZBIFoXbzBjMCz7OoQP5YIaJNYQMAAdziCVaALGNSIAHomcAACoFJFgADKWjcSNEwG4vC4ji0wggEEQguiTnMEGALWAV1yAFp8gVgEjeFyuKICvMrCTgVxnst5jtsGC4ljsPNhXxGaAWcAAOq6YRXYDCRg+RWIcA5JSC+kWdCepQ+v3RYCU3RInzRMCGwlpC19NYBW1Ye08R1AA) + + ```ts + enum LogLevel { + Off, + Debug, + Error, + Fatal + }; + + interface LoggerConfig { + name: string; + level: LogLevel; + } + + class Logger { + config: Readonly; + + constructor({name, level}: LoggerConfig) { + this.config = {name, level}; + Object.freeze(this.config); + } + } + + const config: LoggerConfig = { + name: 'MyApp', + level: LogLevel.Debug + }; + + const logger = new Logger(config); + + // TypeScript Error: cannot assign to read-only property. + logger.config.level = LogLevel.Error; + + // We are able to edit config variable as we please. + config.level = LogLevel.Error; + ``` +
+ +- [`Pick`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1422-L1427) - From `T`, pick a set of properties whose keys are in the union `K`. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgEE5TCgNugN4BQoZwOUBAXMAM5RyQDmA3KeSFABYCuAtgCMISMHloMmENh04oA9tBjQJjFuzIBfYrOAB6PcADCcGElh1gEGAHcKATwAO6ebyjB5CTNlwFwSxFR0BX5HeToYABNgBDh5fm8cfBg6AHIKG3ldA2BHOOcfFNpUygJ0pAhokr4hETFUgDpswywkggAFUwA3MFtgAF5gQgowKhhVKTYKGuFRcXo1aVZgbTIoJ3RW3xhOmB6+wfbcAGsAHi3kgBpgEtGy4AAfG54BWfqAPnZm4AAlZUj4MAkMA8GAGB4vEgfMlLLw6CwPBA8PYRmMgZVgAC6CgmI4cIommQELwICh8RBgKZKvALh1ur0bHQABR5PYMui0Wk7em2ADaAF0AJS0AASABUALIAGQAogR+Mp3CROCAFBBwVC2ikBpj5CgBIqGjizLA5TAFdAmalImAuqlBRoVQh5HBgEy1eDWfs7J5cjzGYKhroVfpDEhHM4MV6GRR5NN0JrtnRg6BVirTFBeHAKYmYY6QNpdB73LmCJZBlSAXAubtvczeSmQMNSuMbmKNgBlHFgPEUNwusBIPAAQlS1xetTmxT0SDoESgdD0C4aACtHMwxytLrohawgA) + + ```ts + interface Article { + title: string; + thumbnail: string; + content: string; + } + + // Creates new type out of the `Article` interface composed + // from the Articles' two properties: `title` and `thumbnail`. + // `ArticlePreview = {title: string; thumbnail: string}` + type ArticlePreview = Pick; + + // Render a list of articles using only title and description. + function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement { + const articles = document.createElement('div'); + + for (const preview of previews) { + // Append preview to the articles. + } + + return articles; + } + + const articles = renderArticlePreviews([ + { + title: 'TypeScript tutorial!', + thumbnail: '/assets/ts.jpg' + } + ]); + ``` +
+ +- [`Record`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1429-L1434) - Construct a type with a set of properties `K` of type `T`. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/AQ4ejYAUHsGcCWAXBMB2dgwGbAKYC2ADgDYwCeeemCaWArgE7ADGMxAhmuQHQBQoYEnJE8wALKEARnkaxEKdMAC8wAOS0kstGuAAfdQBM8ANzxlRjXQbVaWACwC0JPB0NqA3HwGgIwAJJoWozYHCxixnAsjAhStADmwESMMJYo1Fi4HMCIaPEu+MRklHj8gpqyoeHAAKJFFFTAAN4+giDYCIxwSAByHAR4AFw5SDF5Xm2gJBzdfQPD3WPxE5PAlBxdAPLYNQAelgh4aOHDaPQEMowrIAC+3oJ+AMKMrlrAXFhSAFZ4LEhC9g4-0BmA4JBISXgiCkBQABpILrJ5MhUGhYcATGD6Bk4Hh-jNgABrPDkOBlXyQAAq9ngYmJpOAAHcEOCRjAXqwYODfoo6DhakUSph+Uh7GI4P0xER4Cj0OSQGwMP8tP1hgAlX7swwAHgRl2RvIANALSA08ABtAC6AD4VM1Wm0Kow0MMrYaHYJjGYLLJXZb3at1HYnC43Go-QHQDcvA6-JsmEJXARgCDgMYWAhjIYhDAU+YiMAAFIwex0ZmilMITCGF79TLAGRsAgJYAAZRwSEZGzEABFTOZUrJ5Yn+jwnWgeER6HB7AAKJrADpdXqS4ZqYultTG6azVfqHswPBbtauLY7fayQ7HIbAAAMwBuAEoYw9IBq2Ixs9h2eFMOQYPQObALQKJgggABeYhghCIpikkKRpOQRIknAsZUiIeCttECBEP8NSMCkjDDAARMGziuIYxHwYOjDCMBmDNnAuTxA6irdCOBB1Lh5Dqpqn66tISIykawBnOCtqqC0gbjqc9DgpGkxegOliyfJDrRkAA) + + ```ts + // Positions of employees in our company. + type MemberPosition = 'intern' | 'developer' | 'tech-lead'; + + // Interface describing properties of a single employee. + interface Employee { + firstName: string; + lastName: string; + yearsOfExperience: number; + } + + // Create an object that has all possible `MemberPosition` values set as keys. + // Those keys will store a collection of Employees of the same position. + const team: Record = { + intern: [], + developer: [], + 'tech-lead': [], + }; + + // Our team has decided to help John with his dream of becoming Software Developer. + team.intern.push({ + firstName: 'John', + lastName: 'Doe', + yearsOfExperience: 0 + }); + + // `Record` forces you to initialize all of the property keys. + // TypeScript Error: "tech-lead" property is missing + const teamEmpty: Record = { + intern: null, + developer: null, + }; + ``` +
+ +- [`Exclude`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1436-L1439) - Exclude from `T` those types that are assignable to `U`. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA) + + ```ts + interface ServerConfig { + port: null | string | number; + } + + type RequestHandler = (request: Request, response: Response) => void; + + // Exclude `null` type from `null | string | number`. + // In case the port is equal to `null`, we will use default value. + function getPortValue(port: Exclude): number { + if (typeof port === 'string') { + return parseInt(port, 10); + } + + return port; + } + + function startServer(handler: RequestHandler, config: ServerConfig): void { + const server = require('http').createServer(handler); + + const port = config.port === null ? 3000 : getPortValue(config.port); + server.listen(port); + } + ``` +
+ +- [`Extract`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1441-L1444) - Extract from `T` those types that are assignable to `U`. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzSwEdkQBJYACgEoAueVZAWwCMQYBuAKDDwGcM8MgBF4AXngBlAJ6scESgHIRi6ty5ZUGdoihgEABXZ888AN5d48ANoiAuvUat23K6ihMQ9ATE0BzV3goPy8GZjZOLgBfLi4Aejj4AEEICBwAdz54MAALKFQQ+BxEeAAHY1NgKAwoIKy0grr4DByEUpgccpgMaXgAaxBerCzi+B9-ZulygDouFHRsU1z8kKMYE1RhaqgAHkt4AHkWACt4EAAPbVRgLLWNgBp9gGlBs8uQa6yAUUuYPQwdgNpKM7nh7mMML4CgA+R5WABqUAgpDeVxuhxO1he0jsXGh8EoOBO9COx3BQPo2PBADckaR6IjkSA6PBqTgsMBzPsicdrEC7OJWXSQNwYvFEgAVTS9JLXODpeDpKBZFg4GCoWa8VACIJykAKiQWKy2YQOAioYikCg0OEMDyhRSy4DyxS24KhAAMjyi6gS8AAwjh5OD0iBFHAkJoEOksC1mnkMJq8gUQKDNttKPlnfrwYp3J5XfBHXqoKpfYkAOI4ansTxaeDADmoRSCCBYAbxhC6TDx6rwYHIRX5bScjA4bLJwoDmDwDkfbA9JMrVMVdM1TN69LgkTgwgkchUahqIA) + + ```ts + declare function uniqueId(): number; + + const ID = Symbol('ID'); + + interface Person { + [ID]: number; + name: string; + age: number; + } + + // Allows changing the person data as long as the property key is of string type. + function changePersonData< + Obj extends Person, + Key extends Extract, + Value extends Obj[Key] + > (obj: Obj, key: Key, value: Value): void { + obj[key] = value; + } + + // Tiny Andrew was born. + const andrew = { + [ID]: uniqueId(), + name: 'Andrew', + age: 0, + }; + + // Cool, we're fine with that. + changePersonData(andrew, 'name', 'Pony'); + + // Goverment didn't like the fact that you wanted to change your identity. + changePersonData(andrew, ID, uniqueId()); + ``` +
+ +- [`NonNullable`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1446-L1449) - Exclude `null` and `undefined` from `T`. +
+ + Example + + Works with strictNullChecks set to true. (Read more here) + + [Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA) + + ```ts + type PortNumber = string | number | null; + + /** Part of a class definition that is used to build a server */ + class ServerBuilder { + portNumber!: NonNullable; + + port(this: ServerBuilder, port: PortNumber): ServerBuilder { + if (port == null) { + this.portNumber = 8000; + } else { + this.portNumber = port; + } + + return this; + } + } + + const serverBuilder = new ServerBuilder(); + + serverBuilder + .port('8000') // portNumber = '8000' + .port(null) // portNumber = 8000 + .port(3000); // portNumber = 3000 + + // TypeScript error + serverBuilder.portNumber = null; + ``` +
+ +- [`Parameters`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1451-L1454) - Obtain the parameters of a function type in a tuple. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA) + + ```ts + function shuffle(input: any[]): void { + // Mutate array randomly changing its' elements indexes. + } + + function callNTimes any> (func: Fn, callCount: number) { + // Type that represents the type of the received function parameters. + type FunctionParameters = Parameters; + + return function (...args: FunctionParameters) { + for (let i = 0; i < callCount; i++) { + func(...args); + } + } + } + + const shuffleTwice = callNTimes(shuffle, 2); + ``` +
+ +- [`ConstructorParameters`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1456-L1459) - Obtain the parameters of a constructor function type in a tuple. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA) + + ```ts + class ArticleModel { + title: string; + content?: string; + + constructor(title: string) { + this.title = title; + } + } + + class InstanceCache any)> { + private ClassConstructor: T; + private cache: Map> = new Map(); + + constructor (ctr: T) { + this.ClassConstructor = ctr; + } + + getInstance (...args: ConstructorParameters): InstanceType { + const hash = this.calculateArgumentsHash(...args); + + const existingInstance = this.cache.get(hash); + if (existingInstance !== undefined) { + return existingInstance; + } + + return new this.ClassConstructor(...args); + } + + private calculateArgumentsHash(...args: any[]): string { + // Calculate hash. + return 'hash'; + } + } + + const articleCache = new InstanceCache(ArticleModel); + const amazonArticle = articleCache.getInstance('Amazon forests burining!'); + ``` +
+ +- [`ReturnType`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1461-L1464) – Obtain the return type of a function type. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) + + ```ts + /** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */ + function mapIter< + Elem, + Func extends (elem: Elem) => any, + Ret extends ReturnType + >(iter: Iterable, callback: Func): Ret[] { + const mapped: Ret[] = []; + + for (const elem of iter) { + mapped.push(callback(elem)); + } + + return mapped; + } + + const setObject: Set = new Set(); + const mapObject: Map = new Map(); + + mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[] + + mapIter(mapObject, ([key, value]: [number, string]) => { + return key % 2 === 0 ? value : 'Odd'; + }); // string[] + ``` +
+ +- [`InstanceType`](https://github.com/Microsoft/TypeScript/blob/2961bc3fc0ea1117d4e53bc8e97fa76119bc33e3/src/lib/es5.d.ts#L1466-L1469) – Obtain the instance type of a constructor function type. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA) + + ```ts + class IdleService { + doNothing (): void {} + } + + class News { + title: string; + content: string; + + constructor(title: string, content: string) { + this.title = title; + this.content = content; + } + } + + const instanceCounter: Map = new Map(); + + interface Constructor { + new(...args: any[]): any; + } + + // Keep track how many instances of `Constr` constructor have been created. + function getInstance< + Constr extends Constructor, + Args extends ConstructorParameters + >(constructor: Constr, ...args: Args): InstanceType { + let count = instanceCounter.get(constructor) || 0; + + const instance = new constructor(...args); + + instanceCounter.set(constructor, count + 1); + + console.log(`Created ${count + 1} instances of ${Constr.name} class`); + + return instance; + } + + + const idleService = getInstance(IdleService); + // Will log: `Created 1 instances of IdleService class` + const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...'); + // Will log: `Created 1 instances of News class` + ``` +
+ +- [`Omit`](https://github.com/microsoft/TypeScript/blob/71af02f7459dc812e85ac31365bfe23daf14b4e4/src/lib/es5.d.ts#L1446) – Constructs a type by picking all properties from T and then removing K. +
+ + Example + + + [Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlks4BzCAVShwC5kBnMKUcgbmKYAcIFgIjBs1YgOXMpSFMWbANoBdTiW5woFddwAW0kfKWEAvoUIB6U8gDCUCHEiNkICAHdkYAJ69kz4GC3JcPG4oAHteKDABBxCYNAxsPFBIWEQUCAAPJG4wZABySUFcgJAAEzMLXNV1ck0dIuCw6EjBADpy5AB1FAQ4EGQAV0YUP2AHDy8wEOQbUugmBLwtEIA3OcmQnEjuZBgQqE7gAGtgZAhwKHdkHFGwNvGUdDIcAGUliIBJEF3kAF5kAHlML4ADyPBIAGjyBUYRQAPnkqho4NoYQA+TiEGD9EAISIhPozErQMG4AASK2gn2+AApek9pCSXm8wFSQooAJQMUkAFQAsgAZACiOAgmDOOSIJAQ+OYyGl4DgoDmf2QJRCCH6YvALQQNjsEGFovF1NyJWAy1y7OUyHMyE+yRAuFImG4Iq1YDswHxbRINjA-SgfXlHqVUE4xiAA) + + ```ts + interface Animal { + imageUrl: string; + species: string; + images: string[]; + paragraphs: string[]; + } + + // Creates new type with all properties of the `Animal` interface + // except 'images' and 'paragraphs' properties. We can use this + // type to render small hover tooltip for a wiki entry list. + type AnimalShortInfo = Omit; + + function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement { + const container = document.createElement('div'); + // Internal implementation. + return container; + } + ``` +
+ +You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/advanced-types.html#predefined-conditional-types). + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Jarek Radosz](https://github.com/CvX) +- [Dimitri Benin](https://github.com/BendingBender) +- [Pelle Wessman](https://github.com/voxpelli) + +## License + +(MIT OR CC0-1.0) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/type-fest/source/async-return-type.d.ts b/node_modules/type-fest/source/async-return-type.d.ts new file mode 100644 index 0000000..79ec1e9 --- /dev/null +++ b/node_modules/type-fest/source/async-return-type.d.ts @@ -0,0 +1,23 @@ +import {PromiseValue} from './promise-value'; + +type AsyncFunction = (...args: any[]) => Promise; + +/** +Unwrap the return type of a function that returns a `Promise`. + +There has been [discussion](https://github.com/microsoft/TypeScript/pull/35998) about implementing this type in TypeScript. + +@example +```ts +import {AsyncReturnType} from 'type-fest'; +import {asyncFunction} from 'api'; + +// This type resolves to the unwrapped return type of `asyncFunction`. +type Value = AsyncReturnType; + +async function doSomething(value: Value) {} + +asyncFunction().then(value => doSomething(value)); +``` +*/ +export type AsyncReturnType = PromiseValue>; diff --git a/node_modules/type-fest/source/asyncify.d.ts b/node_modules/type-fest/source/asyncify.d.ts new file mode 100644 index 0000000..455f2eb --- /dev/null +++ b/node_modules/type-fest/source/asyncify.d.ts @@ -0,0 +1,31 @@ +import {PromiseValue} from './promise-value'; +import {SetReturnType} from './set-return-type'; + +/** +Create an async version of the given function type, by boxing the return type in `Promise` while keeping the same parameter types. + +Use-case: You have two functions, one synchronous and one asynchronous that do the same thing. Instead of having to duplicate the type definition, you can use `Asyncify` to reuse the synchronous type. + +@example +``` +import {Asyncify} from 'type-fest'; + +// Synchronous function. +function getFooSync(someArg: SomeType): Foo { + // … +} + +type AsyncifiedFooGetter = Asyncify; +//=> type AsyncifiedFooGetter = (someArg: SomeType) => Promise; + +// Same as `getFooSync` but asynchronous. +const getFooAsync: AsyncifiedFooGetter = (someArg) => { + // TypeScript now knows that `someArg` is `SomeType` automatically. + // It also knows that this function must return `Promise`. + // If you have `@typescript-eslint/promise-function-async` linter rule enabled, it will even report that "Functions that return promises must be async.". + + // … +} +``` +*/ +export type Asyncify any> = SetReturnType>>>; diff --git a/node_modules/type-fest/source/basic.d.ts b/node_modules/type-fest/source/basic.d.ts new file mode 100644 index 0000000..d380c8b --- /dev/null +++ b/node_modules/type-fest/source/basic.d.ts @@ -0,0 +1,67 @@ +/// + +// TODO: This can just be `export type Primitive = not object` when the `not` keyword is out. +/** +Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). +*/ +export type Primitive = + | null + | undefined + | string + | number + | boolean + | symbol + | bigint; + +// TODO: Remove the `= unknown` sometime in the future when most users are on TS 3.5 as it's now the default +/** +Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). +*/ +export type Class = new(...arguments_: Arguments) => T; + +/** +Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`. +*/ +export type TypedArray = + | Int8Array + | Uint8Array + | Uint8ClampedArray + | Int16Array + | Uint16Array + | Int32Array + | Uint32Array + | Float32Array + | Float64Array + | BigInt64Array + | BigUint64Array; + +/** +Matches a JSON object. + +This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`. +*/ +export type JsonObject = {[Key in string]?: JsonValue}; + +/** +Matches a JSON array. +*/ +export interface JsonArray extends Array {} + +/** +Matches any valid JSON value. +*/ +export type JsonValue = string | number | boolean | null | JsonObject | JsonArray; + +declare global { + interface SymbolConstructor { + readonly observable: symbol; + } +} + +/** +Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable). +*/ +export interface ObservableLike { + subscribe(observer: (value: unknown) => void): void; + [Symbol.observable](): ObservableLike; +} diff --git a/node_modules/type-fest/source/conditional-except.d.ts b/node_modules/type-fest/source/conditional-except.d.ts new file mode 100644 index 0000000..ac506cc --- /dev/null +++ b/node_modules/type-fest/source/conditional-except.d.ts @@ -0,0 +1,43 @@ +import {Except} from './except'; +import {ConditionalKeys} from './conditional-keys'; + +/** +Exclude keys from a shape that matches the given `Condition`. + +This is useful when you want to create a new type with a specific set of keys from a shape. For example, you might want to exclude all the primitive properties from a class and form a new shape containing everything but the primitive properties. + +@example +``` +import {Primitive, ConditionalExcept} from 'type-fest'; + +class Awesome { + name: string; + successes: number; + failures: bigint; + + run() {} +} + +type ExceptPrimitivesFromAwesome = ConditionalExcept; +//=> {run: () => void} +``` + +@example +``` +import {ConditionalExcept} from 'type-fest'; + +interface Example { + a: string; + b: string | number; + c: () => void; + d: {}; +} + +type NonStringKeysOnly = ConditionalExcept; +//=> {b: string | number; c: () => void; d: {}} +``` +*/ +export type ConditionalExcept = Except< + Base, + ConditionalKeys +>; diff --git a/node_modules/type-fest/source/conditional-keys.d.ts b/node_modules/type-fest/source/conditional-keys.d.ts new file mode 100644 index 0000000..eb074dc --- /dev/null +++ b/node_modules/type-fest/source/conditional-keys.d.ts @@ -0,0 +1,43 @@ +/** +Extract the keys from a type where the value type of the key extends the given `Condition`. + +Internally this is used for the `ConditionalPick` and `ConditionalExcept` types. + +@example +``` +import {ConditionalKeys} from 'type-fest'; + +interface Example { + a: string; + b: string | number; + c?: string; + d: {}; +} + +type StringKeysOnly = ConditionalKeys; +//=> 'a' +``` + +To support partial types, make sure your `Condition` is a union of undefined (for example, `string | undefined`) as demonstrated below. + +@example +``` +type StringKeysAndUndefined = ConditionalKeys; +//=> 'a' | 'c' +``` +*/ +export type ConditionalKeys = NonNullable< + // Wrap in `NonNullable` to strip away the `undefined` type from the produced union. + { + // Map through all the keys of the given base type. + [Key in keyof Base]: + // Pick only keys with types extending the given `Condition` type. + Base[Key] extends Condition + // Retain this key since the condition passes. + ? Key + // Discard this key since the condition fails. + : never; + + // Convert the produced object into a union type of the keys which passed the conditional test. + }[keyof Base] +>; diff --git a/node_modules/type-fest/source/conditional-pick.d.ts b/node_modules/type-fest/source/conditional-pick.d.ts new file mode 100644 index 0000000..cecc3df --- /dev/null +++ b/node_modules/type-fest/source/conditional-pick.d.ts @@ -0,0 +1,42 @@ +import {ConditionalKeys} from './conditional-keys'; + +/** +Pick keys from the shape that matches the given `Condition`. + +This is useful when you want to create a new type from a specific subset of an existing type. For example, you might want to pick all the primitive properties from a class and form a new automatically derived type. + +@example +``` +import {Primitive, ConditionalPick} from 'type-fest'; + +class Awesome { + name: string; + successes: number; + failures: bigint; + + run() {} +} + +type PickPrimitivesFromAwesome = ConditionalPick; +//=> {name: string; successes: number; failures: bigint} +``` + +@example +``` +import {ConditionalPick} from 'type-fest'; + +interface Example { + a: string; + b: string | number; + c: () => void; + d: {}; +} + +type StringKeysOnly = ConditionalPick; +//=> {a: string} +``` +*/ +export type ConditionalPick = Pick< + Base, + ConditionalKeys +>; diff --git a/node_modules/type-fest/source/entries.d.ts b/node_modules/type-fest/source/entries.d.ts new file mode 100644 index 0000000..e02237a --- /dev/null +++ b/node_modules/type-fest/source/entries.d.ts @@ -0,0 +1,57 @@ +import {ArrayEntry, MapEntry, ObjectEntry, SetEntry} from './entry'; + +type ArrayEntries = Array>; +type MapEntries = Array>; +type ObjectEntries = Array>; +type SetEntries> = Array>; + +/** +Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entries` type will return the type of that collection's entries. + +For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable. + +@see `Entry` if you want to just access the type of a single entry. + +@example +``` +import {Entries} from 'type-fest'; + +interface Example { + someKey: number; +} + +const manipulatesEntries = (examples: Entries) => examples.map(example => [ + // Does some arbitrary processing on the key (with type information available) + example[0].toUpperCase(), + + // Does some arbitrary processing on the value (with type information available) + example[1].toFixed() +]); + +const example: Example = {someKey: 1}; +const entries = Object.entries(example) as Entries; +const output = manipulatesEntries(entries); + +// Objects +const objectExample = {a: 1}; +const objectEntries: Entries = [['a', 1]]; + +// Arrays +const arrayExample = ['a', 1]; +const arrayEntries: Entries = [[0, 'a'], [1, 1]]; + +// Maps +const mapExample = new Map([['a', 1]]); +const mapEntries: Entries = [['a', 1]]; + +// Sets +const setExample = new Set(['a', 1]); +const setEntries: Entries = [['a', 'a'], [1, 1]]; +``` +*/ +export type Entries = + BaseType extends Map ? MapEntries + : BaseType extends Set ? SetEntries + : BaseType extends unknown[] ? ArrayEntries + : BaseType extends object ? ObjectEntries + : never; diff --git a/node_modules/type-fest/source/entry.d.ts b/node_modules/type-fest/source/entry.d.ts new file mode 100644 index 0000000..41a13a9 --- /dev/null +++ b/node_modules/type-fest/source/entry.d.ts @@ -0,0 +1,60 @@ +type MapKey = BaseType extends Map ? KeyType : never; +type MapValue = BaseType extends Map ? ValueType : never; + +export type ArrayEntry = [number, BaseType[number]]; +export type MapEntry = [MapKey, MapValue]; +export type ObjectEntry = [keyof BaseType, BaseType[keyof BaseType]]; +export type SetEntry = BaseType extends Set ? [ItemType, ItemType] : never; + +/** +Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entry` type will return the type of that collection's entry. + +For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable. + +@see `Entries` if you want to just access the type of the array of entries (which is the return of the `.entries()` method). + +@example +``` +import {Entry} from 'type-fest'; + +interface Example { + someKey: number; +} + +const manipulatesEntry = (example: Entry) => [ + // Does some arbitrary processing on the key (with type information available) + example[0].toUpperCase(), + + // Does some arbitrary processing on the value (with type information available) + example[1].toFixed(), +]; + +const example: Example = {someKey: 1}; +const entry = Object.entries(example)[0] as Entry; +const output = manipulatesEntry(entry); + +// Objects +const objectExample = {a: 1}; +const objectEntry: Entry = ['a', 1]; + +// Arrays +const arrayExample = ['a', 1]; +const arrayEntryString: Entry = [0, 'a']; +const arrayEntryNumber: Entry = [1, 1]; + +// Maps +const mapExample = new Map([['a', 1]]); +const mapEntry: Entry = ['a', 1]; + +// Sets +const setExample = new Set(['a', 1]); +const setEntryString: Entry = ['a', 'a']; +const setEntryNumber: Entry = [1, 1]; +``` +*/ +export type Entry = + BaseType extends Map ? MapEntry + : BaseType extends Set ? SetEntry + : BaseType extends unknown[] ? ArrayEntry + : BaseType extends object ? ObjectEntry + : never; diff --git a/node_modules/type-fest/source/except.d.ts b/node_modules/type-fest/source/except.d.ts new file mode 100644 index 0000000..7dedbaa --- /dev/null +++ b/node_modules/type-fest/source/except.d.ts @@ -0,0 +1,22 @@ +/** +Create a type from an object type without certain keys. + +This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/30825) if you want to have the stricter version as a built-in in TypeScript. + +@example +``` +import {Except} from 'type-fest'; + +type Foo = { + a: number; + b: string; + c: boolean; +}; + +type FooWithoutA = Except; +//=> {b: string}; +``` +*/ +export type Except = Pick>; diff --git a/node_modules/type-fest/source/fixed-length-array.d.ts b/node_modules/type-fest/source/fixed-length-array.d.ts new file mode 100644 index 0000000..e3bc0f4 --- /dev/null +++ b/node_modules/type-fest/source/fixed-length-array.d.ts @@ -0,0 +1,38 @@ +/** +Methods to exclude. +*/ +type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'; + +/** +Create a type that represents an array of the given type and length. The array's length and the `Array` prototype methods that manipulate its length are excluded in the resulting type. + +Please participate in [this issue](https://github.com/microsoft/TypeScript/issues/26223) if you want to have a similiar type built into TypeScript. + +Use-cases: +- Declaring fixed-length tuples or arrays with a large number of items. +- Creating a range union (for example, `0 | 1 | 2 | 3 | 4` from the keys of such a type) without having to resort to recursive types. +- Creating an array of coordinates with a static length, for example, length of 3 for a 3D vector. + +@example +``` +import {FixedLengthArray} from 'type-fest'; + +type FencingTeam = FixedLengthArray; + +const guestFencingTeam: FencingTeam = ['Josh', 'Michael', 'Robert']; + +const homeFencingTeam: FencingTeam = ['George', 'John']; +//=> error TS2322: Type string[] is not assignable to type 'FencingTeam' + +guestFencingTeam.push('Sam'); +//=> error TS2339: Property 'push' does not exist on type 'FencingTeam' +``` +*/ +export type FixedLengthArray = Pick< + ArrayPrototype, + Exclude +> & { + [index: number]: Element; + [Symbol.iterator]: () => IterableIterator; + readonly length: Length; +}; diff --git a/node_modules/type-fest/source/iterable-element.d.ts b/node_modules/type-fest/source/iterable-element.d.ts new file mode 100644 index 0000000..174cfbf --- /dev/null +++ b/node_modules/type-fest/source/iterable-element.d.ts @@ -0,0 +1,46 @@ +/** +Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator. + +This can be useful, for example, if you want to get the type that is yielded in a generator function. Often the return type of those functions are not specified. + +This type works with both `Iterable`s and `AsyncIterable`s, so it can be use with synchronous and asynchronous generators. + +Here is an example of `IterableElement` in action with a generator function: + +@example +``` +function * iAmGenerator() { + yield 1; + yield 2; +} + +type MeNumber = IterableElement> +``` + +And here is an example with an async generator: + +@example +``` +async function * iAmGeneratorAsync() { + yield 'hi'; + yield true; +} + +type MeStringOrBoolean = IterableElement> +``` + +Many types in JavaScript/TypeScript are iterables. This type works on all types that implement those interfaces. For example, `Array`, `Set`, `Map`, `stream.Readable`, etc. + +An example with an array of strings: + +@example +``` +type MeString = IterableElement +``` +*/ +export type IterableElement = + TargetIterable extends Iterable ? + ElementType : + TargetIterable extends AsyncIterable ? + ElementType : + never; diff --git a/node_modules/type-fest/source/literal-union.d.ts b/node_modules/type-fest/source/literal-union.d.ts new file mode 100644 index 0000000..8debd93 --- /dev/null +++ b/node_modules/type-fest/source/literal-union.d.ts @@ -0,0 +1,33 @@ +import {Primitive} from './basic'; + +/** +Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. + +Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals. + +This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore. + +@example +``` +import {LiteralUnion} from 'type-fest'; + +// Before + +type Pet = 'dog' | 'cat' | string; + +const pet: Pet = ''; +// Start typing in your TypeScript-enabled IDE. +// You **will not** get auto-completion for `dog` and `cat` literals. + +// After + +type Pet2 = LiteralUnion<'dog' | 'cat', string>; + +const pet: Pet2 = ''; +// You **will** get auto-completion for `dog` and `cat` literals. +``` + */ +export type LiteralUnion< + LiteralType, + BaseType extends Primitive +> = LiteralType | (BaseType & {_?: never}); diff --git a/node_modules/type-fest/source/merge-exclusive.d.ts b/node_modules/type-fest/source/merge-exclusive.d.ts new file mode 100644 index 0000000..059bd2c --- /dev/null +++ b/node_modules/type-fest/source/merge-exclusive.d.ts @@ -0,0 +1,39 @@ +// Helper type. Not useful on its own. +type Without = {[KeyType in Exclude]?: never}; + +/** +Create a type that has mutually exclusive keys. + +This type was inspired by [this comment](https://github.com/Microsoft/TypeScript/issues/14094#issuecomment-373782604). + +This type works with a helper type, called `Without`. `Without` produces a type that has only keys from `FirstType` which are not present on `SecondType` and sets the value type for these keys to `never`. This helper type is then used in `MergeExclusive` to remove keys from either `FirstType` or `SecondType`. + +@example +``` +import {MergeExclusive} from 'type-fest'; + +interface ExclusiveVariation1 { + exclusive1: boolean; +} + +interface ExclusiveVariation2 { + exclusive2: string; +} + +type ExclusiveOptions = MergeExclusive; + +let exclusiveOptions: ExclusiveOptions; + +exclusiveOptions = {exclusive1: true}; +//=> Works +exclusiveOptions = {exclusive2: 'hi'}; +//=> Works +exclusiveOptions = {exclusive1: true, exclusive2: 'hi'}; +//=> Error +``` +*/ +export type MergeExclusive = + (FirstType | SecondType) extends object ? + (Without & SecondType) | (Without & FirstType) : + FirstType | SecondType; + diff --git a/node_modules/type-fest/source/merge.d.ts b/node_modules/type-fest/source/merge.d.ts new file mode 100644 index 0000000..4b3920b --- /dev/null +++ b/node_modules/type-fest/source/merge.d.ts @@ -0,0 +1,22 @@ +import {Except} from './except'; + +/** +Merge two types into a new type. Keys of the second type overrides keys of the first type. + +@example +``` +import {Merge} from 'type-fest'; + +type Foo = { + a: number; + b: string; +}; + +type Bar = { + b: number; +}; + +const ab: Merge = {a: 1, b: 2}; +``` +*/ +export type Merge = Except> & SecondType; diff --git a/node_modules/type-fest/source/mutable.d.ts b/node_modules/type-fest/source/mutable.d.ts new file mode 100644 index 0000000..03d0dda --- /dev/null +++ b/node_modules/type-fest/source/mutable.d.ts @@ -0,0 +1,22 @@ +/** +Convert an object with `readonly` keys into a mutable object. Inverse of `Readonly`. + +This can be used to [store and mutate options within a class](https://github.com/sindresorhus/pageres/blob/4a5d05fca19a5fbd2f53842cbf3eb7b1b63bddd2/source/index.ts#L72), [edit `readonly` objects within tests](https://stackoverflow.com/questions/50703834), and [construct a `readonly` object within a function](https://github.com/Microsoft/TypeScript/issues/24509). + +@example +``` +import {Mutable} from 'type-fest'; + +type Foo = { + readonly a: number; + readonly b: string; +}; + +const mutableFoo: Mutable = {a: 1, b: '2'}; +mutableFoo.a = 3; +``` +*/ +export type Mutable = { + // For each `Key` in the keys of `ObjectType`, make a mapped type by removing the `readonly` modifier from the key. + -readonly [KeyType in keyof ObjectType]: ObjectType[KeyType]; +}; diff --git a/node_modules/type-fest/source/opaque.d.ts b/node_modules/type-fest/source/opaque.d.ts new file mode 100644 index 0000000..20ab964 --- /dev/null +++ b/node_modules/type-fest/source/opaque.d.ts @@ -0,0 +1,65 @@ +/** +Create an opaque type, which hides its internal details from the public, and can only be created by being used explicitly. + +The generic type parameter can be anything. It doesn't have to be an object. + +[Read more about opaque types.](https://codemix.com/opaque-types-in-javascript/) + +There have been several discussions about adding this feature to TypeScript via the `opaque type` operator, similar to how Flow does it. Unfortunately, nothing has (yet) moved forward: + - [Microsoft/TypeScript#15408](https://github.com/Microsoft/TypeScript/issues/15408) + - [Microsoft/TypeScript#15807](https://github.com/Microsoft/TypeScript/issues/15807) + +@example +``` +import {Opaque} from 'type-fest'; + +type AccountNumber = Opaque; +type AccountBalance = Opaque; + +// The Token parameter allows the compiler to differentiate between types, whereas "unknown" will not. For example, consider the following structures: +type ThingOne = Opaque; +type ThingTwo = Opaque; + +// To the compiler, these types are allowed to be cast to each other as they have the same underlying type. They are both `string & { __opaque__: unknown }`. +// To avoid this behaviour, you would instead pass the "Token" parameter, like so. +type NewThingOne = Opaque; +type NewThingTwo = Opaque; + +// Now they're completely separate types, so the following will fail to compile. +function createNewThingOne (): NewThingOne { + // As you can see, casting from a string is still allowed. However, you may not cast NewThingOne to NewThingTwo, and vice versa. + return 'new thing one' as NewThingOne; +} + +// This will fail to compile, as they are fundamentally different types. +const thingTwo = createNewThingOne() as NewThingTwo; + +// Here's another example of opaque typing. +function createAccountNumber(): AccountNumber { + return 2 as AccountNumber; +} + +function getMoneyForAccount(accountNumber: AccountNumber): AccountBalance { + return 4 as AccountBalance; +} + +// This will compile successfully. +getMoneyForAccount(createAccountNumber()); + +// But this won't, because it has to be explicitly passed as an `AccountNumber` type. +getMoneyForAccount(2); + +// You can use opaque values like they aren't opaque too. +const accountNumber = createAccountNumber(); + +// This will not compile successfully. +const newAccountNumber = accountNumber + 2; + +// As a side note, you can (and should) use recursive types for your opaque types to make them stronger and hopefully easier to type. +type Person = { + id: Opaque; + name: string; +}; +``` +*/ +export type Opaque = Type & {readonly __opaque__: Token}; diff --git a/node_modules/type-fest/source/package-json.d.ts b/node_modules/type-fest/source/package-json.d.ts new file mode 100644 index 0000000..cf355d0 --- /dev/null +++ b/node_modules/type-fest/source/package-json.d.ts @@ -0,0 +1,611 @@ +import {LiteralUnion} from './literal-union'; + +declare namespace PackageJson { + /** + A person who has been involved in creating or maintaining the package. + */ + export type Person = + | string + | { + name: string; + url?: string; + email?: string; + }; + + export type BugsLocation = + | string + | { + /** + The URL to the package's issue tracker. + */ + url?: string; + + /** + The email address to which issues should be reported. + */ + email?: string; + }; + + export interface DirectoryLocations { + [directoryType: string]: unknown; + + /** + Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder. + */ + bin?: string; + + /** + Location for Markdown files. + */ + doc?: string; + + /** + Location for example scripts. + */ + example?: string; + + /** + Location for the bulk of the library. + */ + lib?: string; + + /** + Location for man pages. Sugar to generate a `man` array by walking the folder. + */ + man?: string; + + /** + Location for test files. + */ + test?: string; + } + + export type Scripts = { + /** + Run **before** the package is published (Also run on local `npm install` without any arguments). + */ + prepublish?: string; + + /** + Run both **before** the package is packed and published, and on local `npm install` without any arguments. This is run **after** `prepublish`, but **before** `prepublishOnly`. + */ + prepare?: string; + + /** + Run **before** the package is prepared and packed, **only** on `npm publish`. + */ + prepublishOnly?: string; + + /** + Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies). + */ + prepack?: string; + + /** + Run **after** the tarball has been generated and moved to its final destination. + */ + postpack?: string; + + /** + Run **after** the package is published. + */ + publish?: string; + + /** + Run **after** the package is published. + */ + postpublish?: string; + + /** + Run **before** the package is installed. + */ + preinstall?: string; + + /** + Run **after** the package is installed. + */ + install?: string; + + /** + Run **after** the package is installed and after `install`. + */ + postinstall?: string; + + /** + Run **before** the package is uninstalled and before `uninstall`. + */ + preuninstall?: string; + + /** + Run **before** the package is uninstalled. + */ + uninstall?: string; + + /** + Run **after** the package is uninstalled. + */ + postuninstall?: string; + + /** + Run **before** bump the package version and before `version`. + */ + preversion?: string; + + /** + Run **before** bump the package version. + */ + version?: string; + + /** + Run **after** bump the package version. + */ + postversion?: string; + + /** + Run with the `npm test` command, before `test`. + */ + pretest?: string; + + /** + Run with the `npm test` command. + */ + test?: string; + + /** + Run with the `npm test` command, after `test`. + */ + posttest?: string; + + /** + Run with the `npm stop` command, before `stop`. + */ + prestop?: string; + + /** + Run with the `npm stop` command. + */ + stop?: string; + + /** + Run with the `npm stop` command, after `stop`. + */ + poststop?: string; + + /** + Run with the `npm start` command, before `start`. + */ + prestart?: string; + + /** + Run with the `npm start` command. + */ + start?: string; + + /** + Run with the `npm start` command, after `start`. + */ + poststart?: string; + + /** + Run with the `npm restart` command, before `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. + */ + prerestart?: string; + + /** + Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. + */ + restart?: string; + + /** + Run with the `npm restart` command, after `restart`. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. + */ + postrestart?: string; + } & Record; + + /** + Dependencies of the package. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or Git URL. + */ + export type Dependency = Record; + + /** + Conditions which provide a way to resolve a package entry point based on the environment. + */ + export type ExportCondition = LiteralUnion< + | 'import' + | 'require' + | 'node' + | 'deno' + | 'browser' + | 'electron' + | 'react-native' + | 'default', + string + >; + + /** + Entry points of a module, optionally with conditions and subpath exports. + */ + export type Exports = + | string + | {[key in ExportCondition]: Exports} + | {[key: string]: Exports}; // eslint-disable-line @typescript-eslint/consistent-indexed-object-style + + export interface NonStandardEntryPoints { + /** + An ECMAScript module ID that is the primary entry point to the program. + */ + module?: string; + + /** + A module ID with untranspiled code that is the primary entry point to the program. + */ + esnext?: + | string + | { + [moduleName: string]: string | undefined; + main?: string; + browser?: string; + }; + + /** + A hint to JavaScript bundlers or component tools when packaging modules for client side use. + */ + browser?: + | string + | Record; + + /** + Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused. + + [Read more.](https://webpack.js.org/guides/tree-shaking/) + */ + sideEffects?: boolean | string[]; + } + + export interface TypeScriptConfiguration { + /** + Location of the bundled TypeScript declaration file. + */ + types?: string; + + /** + Location of the bundled TypeScript declaration file. Alias of `types`. + */ + typings?: string; + } + + /** + An alternative configuration for Yarn workspaces. + */ + export interface WorkspaceConfig { + /** + An array of workspace pattern strings which contain the workspace packages. + */ + packages?: WorkspacePattern[]; + + /** + Designed to solve the problem of packages which break when their `node_modules` are moved to the root workspace directory - a process known as hoisting. For these packages, both within your workspace, and also some that have been installed via `node_modules`, it is important to have a mechanism for preventing the default Yarn workspace behavior. By adding workspace pattern strings here, Yarn will resume non-workspace behavior for any package which matches the defined patterns. + + [Read more](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) + */ + nohoist?: WorkspacePattern[]; + } + + /** + A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process. + + The patterns are handled with [minimatch](https://github.com/isaacs/minimatch). + + @example + `docs` → Include the docs directory and install its dependencies. + `packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`. + */ + type WorkspacePattern = string; + + export interface YarnConfiguration { + /** + Used to configure [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/). + + Workspaces allow you to manage multiple packages within the same repository in such a way that you only need to run `yarn install` once to install all of them in a single pass. + + Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces. + */ + workspaces?: WorkspacePattern[] | WorkspaceConfig; + + /** + If your package only allows one version of a given dependency, and you’d like to enforce the same behavior as `yarn install --flat` on the command-line, set this to `true`. + + Note that if your `package.json` contains `"flat": true` and other packages depend on yours (e.g. you are building a library rather than an app), those other packages will also need `"flat": true` in their `package.json` or be installed with `yarn install --flat` on the command-line. + */ + flat?: boolean; + + /** + Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file. + */ + resolutions?: Dependency; + } + + export interface JSPMConfiguration { + /** + JSPM configuration. + */ + jspm?: PackageJson; + } + + /** + Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties. + */ + export interface PackageJsonStandard { + /** + The name of the package. + */ + name?: string; + + /** + Package version, parseable by [`node-semver`](https://github.com/npm/node-semver). + */ + version?: string; + + /** + Package description, listed in `npm search`. + */ + description?: string; + + /** + Keywords associated with package, listed in `npm search`. + */ + keywords?: string[]; + + /** + The URL to the package's homepage. + */ + homepage?: LiteralUnion<'.', string>; + + /** + The URL to the package's issue tracker and/or the email address to which issues should be reported. + */ + bugs?: BugsLocation; + + /** + The license for the package. + */ + license?: string; + + /** + The licenses for the package. + */ + licenses?: Array<{ + type?: string; + url?: string; + }>; + + author?: Person; + + /** + A list of people who contributed to the package. + */ + contributors?: Person[]; + + /** + A list of people who maintain the package. + */ + maintainers?: Person[]; + + /** + The files included in the package. + */ + files?: string[]; + + /** + Resolution algorithm for importing ".js" files from the package's scope. + + [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field) + */ + type?: 'module' | 'commonjs'; + + /** + The module ID that is the primary entry point to the program. + */ + main?: string; + + /** + Standard entry points of the package, with enhanced support for ECMAScript Modules. + + [Read more.](https://nodejs.org/api/esm.html#esm_package_entry_points) + */ + exports?: Exports; + + /** + The executable files that should be installed into the `PATH`. + */ + bin?: + | string + | Record; + + /** + Filenames to put in place for the `man` program to find. + */ + man?: string | string[]; + + /** + Indicates the structure of the package. + */ + directories?: DirectoryLocations; + + /** + Location for the code repository. + */ + repository?: + | string + | { + type: string; + url: string; + + /** + Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo). + + [Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md) + */ + directory?: string; + }; + + /** + Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point. + */ + scripts?: Scripts; + + /** + Is used to set configuration parameters used in package scripts that persist across upgrades. + */ + config?: Record; + + /** + The dependencies of the package. + */ + dependencies?: Dependency; + + /** + Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling. + */ + devDependencies?: Dependency; + + /** + Dependencies that are skipped if they fail to install. + */ + optionalDependencies?: Dependency; + + /** + Dependencies that will usually be required by the package user directly or via another dependency. + */ + peerDependencies?: Dependency; + + /** + Indicate peer dependencies that are optional. + */ + peerDependenciesMeta?: Record; + + /** + Package names that are bundled when the package is published. + */ + bundledDependencies?: string[]; + + /** + Alias of `bundledDependencies`. + */ + bundleDependencies?: string[]; + + /** + Engines that this package runs on. + */ + engines?: { + [EngineName in 'npm' | 'node' | string]: string; + }; + + /** + @deprecated + */ + engineStrict?: boolean; + + /** + Operating systems the module runs on. + */ + os?: Array>; + + /** + CPU architectures the module runs on. + */ + cpu?: Array>; + + /** + If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally. + + @deprecated + */ + preferGlobal?: boolean; + + /** + If set to `true`, then npm will refuse to publish it. + */ + private?: boolean; + + /** + A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default. + */ + publishConfig?: Record; + + /** + Describes and notifies consumers of a package's monetary support information. + + [Read more.](https://github.com/npm/rfcs/blob/latest/accepted/0017-add-funding-support.md) + */ + funding?: string | { + /** + The type of funding. + */ + type?: LiteralUnion< + | 'github' + | 'opencollective' + | 'patreon' + | 'individual' + | 'foundation' + | 'corporation', + string + >; + + /** + The URL to the funding page. + */ + url: string; + }; + } +} + +/** +Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn. +*/ +export type PackageJson = +PackageJson.PackageJsonStandard & +PackageJson.NonStandardEntryPoints & +PackageJson.TypeScriptConfiguration & +PackageJson.YarnConfiguration & +PackageJson.JSPMConfiguration; diff --git a/node_modules/type-fest/source/partial-deep.d.ts b/node_modules/type-fest/source/partial-deep.d.ts new file mode 100644 index 0000000..b962b84 --- /dev/null +++ b/node_modules/type-fest/source/partial-deep.d.ts @@ -0,0 +1,72 @@ +import {Primitive} from './basic'; + +/** +Create a type from another type with all keys and nested keys set to optional. + +Use-cases: +- Merging a default settings/config object with another object, the second object would be a deep partial of the default object. +- Mocking and testing complex entities, where populating an entire object with its keys would be redundant in terms of the mock or test. + +@example +``` +import {PartialDeep} from 'type-fest'; + +const settings: Settings = { + textEditor: { + fontSize: 14; + fontColor: '#000000'; + fontWeight: 400; + } + autocomplete: false; + autosave: true; +}; + +const applySavedSettings = (savedSettings: PartialDeep) => { + return {...settings, ...savedSettings}; +} + +settings = applySavedSettings({textEditor: {fontWeight: 500}}); +``` +*/ +export type PartialDeep = T extends Primitive + ? Partial + : T extends Map + ? PartialMapDeep + : T extends Set + ? PartialSetDeep + : T extends ReadonlyMap + ? PartialReadonlyMapDeep + : T extends ReadonlySet + ? PartialReadonlySetDeep + : T extends ((...arguments: any[]) => unknown) + ? T | undefined + : T extends object + ? PartialObjectDeep + : unknown; + +/** +Same as `PartialDeep`, but accepts only `Map`s and as inputs. Internal helper for `PartialDeep`. +*/ +interface PartialMapDeep extends Map, PartialDeep> {} + +/** +Same as `PartialDeep`, but accepts only `Set`s as inputs. Internal helper for `PartialDeep`. +*/ +interface PartialSetDeep extends Set> {} + +/** +Same as `PartialDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `PartialDeep`. +*/ +interface PartialReadonlyMapDeep extends ReadonlyMap, PartialDeep> {} + +/** +Same as `PartialDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `PartialDeep`. +*/ +interface PartialReadonlySetDeep extends ReadonlySet> {} + +/** +Same as `PartialDeep`, but accepts only `object`s as inputs. Internal helper for `PartialDeep`. +*/ +type PartialObjectDeep = { + [KeyType in keyof ObjectType]?: PartialDeep +}; diff --git a/node_modules/type-fest/source/promisable.d.ts b/node_modules/type-fest/source/promisable.d.ts new file mode 100644 index 0000000..71242a5 --- /dev/null +++ b/node_modules/type-fest/source/promisable.d.ts @@ -0,0 +1,23 @@ +/** +Create a type that represents either the value or the value wrapped in `PromiseLike`. + +Use-cases: +- A function accepts a callback that may either return a value synchronously or may return a promised value. +- This type could be the return type of `Promise#then()`, `Promise#catch()`, and `Promise#finally()` callbacks. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31394) if you want to have this type as a built-in in TypeScript. + +@example +``` +import {Promisable} from 'type-fest'; + +async function logger(getLogEntry: () => Promisable): Promise { + const entry = await getLogEntry(); + console.log(entry); +} + +logger(() => 'foo'); +logger(() => Promise.resolve('bar')); +``` +*/ +export type Promisable = T | PromiseLike; diff --git a/node_modules/type-fest/source/promise-value.d.ts b/node_modules/type-fest/source/promise-value.d.ts new file mode 100644 index 0000000..642ddeb --- /dev/null +++ b/node_modules/type-fest/source/promise-value.d.ts @@ -0,0 +1,27 @@ +/** +Returns the type that is wrapped inside a `Promise` type. +If the type is a nested Promise, it is unwrapped recursively until a non-Promise type is obtained. +If the type is not a `Promise`, the type itself is returned. + +@example +``` +import {PromiseValue} from 'type-fest'; + +type AsyncData = Promise; +let asyncData: PromiseValue = Promise.resolve('ABC'); + +type Data = PromiseValue; +let data: Data = await asyncData; + +// Here's an example that shows how this type reacts to non-Promise types. +type SyncData = PromiseValue; +let syncData: SyncData = getSyncData(); + +// Here's an example that shows how this type reacts to recursive Promise types. +type RecursiveAsyncData = Promise >; +let recursiveAsyncData: PromiseValue = Promise.resolve(Promise.resolve('ABC')); +``` +*/ +export type PromiseValue = PromiseType extends Promise + ? { 0: PromiseValue; 1: Value }[PromiseType extends Promise ? 0 : 1] + : Otherwise; diff --git a/node_modules/type-fest/source/readonly-deep.d.ts b/node_modules/type-fest/source/readonly-deep.d.ts new file mode 100644 index 0000000..b8c04de --- /dev/null +++ b/node_modules/type-fest/source/readonly-deep.d.ts @@ -0,0 +1,59 @@ +import {Primitive} from './basic'; + +/** +Convert `object`s, `Map`s, `Set`s, and `Array`s and all of their keys/elements into immutable structures recursively. + +This is useful when a deeply nested structure needs to be exposed as completely immutable, for example, an imported JSON module or when receiving an API response that is passed around. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/13923) if you want to have this type as a built-in in TypeScript. + +@example +``` +// data.json +{ + "foo": ["bar"] +} + +// main.ts +import {ReadonlyDeep} from 'type-fest'; +import dataJson = require('./data.json'); + +const data: ReadonlyDeep = dataJson; + +export default data; + +// test.ts +import data from './main'; + +data.foo.push('bar'); +//=> error TS2339: Property 'push' does not exist on type 'readonly string[]' +``` +*/ +export type ReadonlyDeep = T extends Primitive | ((...arguments: any[]) => unknown) + ? T + : T extends ReadonlyMap + ? ReadonlyMapDeep + : T extends ReadonlySet + ? ReadonlySetDeep + : T extends object + ? ReadonlyObjectDeep + : unknown; + +/** +Same as `ReadonlyDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `ReadonlyDeep`. +*/ +interface ReadonlyMapDeep + extends ReadonlyMap, ReadonlyDeep> {} + +/** +Same as `ReadonlyDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `ReadonlyDeep`. +*/ +interface ReadonlySetDeep + extends ReadonlySet> {} + +/** +Same as `ReadonlyDeep`, but accepts only `object`s as inputs. Internal helper for `ReadonlyDeep`. +*/ +type ReadonlyObjectDeep = { + readonly [KeyType in keyof ObjectType]: ReadonlyDeep +}; diff --git a/node_modules/type-fest/source/require-at-least-one.d.ts b/node_modules/type-fest/source/require-at-least-one.d.ts new file mode 100644 index 0000000..b3b8719 --- /dev/null +++ b/node_modules/type-fest/source/require-at-least-one.d.ts @@ -0,0 +1,33 @@ +import {Except} from './except'; + +/** +Create a type that requires at least one of the given keys. The remaining keys are kept as is. + +@example +``` +import {RequireAtLeastOne} from 'type-fest'; + +type Responder = { + text?: () => string; + json?: () => string; + + secure?: boolean; +}; + +const responder: RequireAtLeastOne = { + json: () => '{"message": "ok"}', + secure: true +}; +``` +*/ +export type RequireAtLeastOne< + ObjectType, + KeysType extends keyof ObjectType = keyof ObjectType +> = { + // For each `Key` in `KeysType` make a mapped type: + [Key in KeysType]-?: Required> & // 1. Make `Key`'s type required + // 2. Make all other keys in `KeysType` optional + Partial>>; +}[KeysType] & + // 3. Add the remaining keys not in `KeysType` + Except; diff --git a/node_modules/type-fest/source/require-exactly-one.d.ts b/node_modules/type-fest/source/require-exactly-one.d.ts new file mode 100644 index 0000000..c3e7e7e --- /dev/null +++ b/node_modules/type-fest/source/require-exactly-one.d.ts @@ -0,0 +1,35 @@ +// TODO: Remove this when we target TypeScript >=3.5. +type _Omit = Pick>; + +/** +Create a type that requires exactly one of the given keys and disallows more. The remaining keys are kept as is. + +Use-cases: +- Creating interfaces for components that only need one of the keys to display properly. +- Declaring generic keys in a single place for a single use-case that gets narrowed down via `RequireExactlyOne`. + +The caveat with `RequireExactlyOne` is that TypeScript doesn't always know at compile time every key that will exist at runtime. Therefore `RequireExactlyOne` can't do anything to prevent extra keys it doesn't know about. + +@example +``` +import {RequireExactlyOne} from 'type-fest'; + +type Responder = { + text: () => string; + json: () => string; + secure: boolean; +}; + +const responder: RequireExactlyOne = { + // Adding a `text` key here would cause a compile error. + + json: () => '{"message": "ok"}', + secure: true +}; +``` +*/ +export type RequireExactlyOne = + {[Key in KeysType]: ( + Required> & + Partial, never>> + )}[KeysType] & _Omit; diff --git a/node_modules/type-fest/source/set-optional.d.ts b/node_modules/type-fest/source/set-optional.d.ts new file mode 100644 index 0000000..3539899 --- /dev/null +++ b/node_modules/type-fest/source/set-optional.d.ts @@ -0,0 +1,34 @@ +import {Except} from './except'; + +/** +Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type. + +Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional. + +@example +``` +import {SetOptional} from 'type-fest'; + +type Foo = { + a: number; + b?: string; + c: boolean; +} + +type SomeOptional = SetOptional; +// type SomeOptional = { +// a: number; +// b?: string; // Was already optional and still is. +// c?: boolean; // Is now optional. +// } +``` +*/ +export type SetOptional = + // Pick just the keys that are not optional from the base type. + Except & + // Pick the keys that should be optional from the base type and make them optional. + Partial> extends + // If `InferredType` extends the previous, then for each key, use the inferred type key. + infer InferredType + ? {[KeyType in keyof InferredType]: InferredType[KeyType]} + : never; diff --git a/node_modules/type-fest/source/set-required.d.ts b/node_modules/type-fest/source/set-required.d.ts new file mode 100644 index 0000000..0a72330 --- /dev/null +++ b/node_modules/type-fest/source/set-required.d.ts @@ -0,0 +1,34 @@ +import {Except} from './except'; + +/** +Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type. + +Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required. + +@example +``` +import {SetRequired} from 'type-fest'; + +type Foo = { + a?: number; + b: string; + c?: boolean; +} + +type SomeRequired = SetRequired; +// type SomeRequired = { +// a?: number; +// b: string; // Was already required and still is. +// c: boolean; // Is now required. +// } +``` +*/ +export type SetRequired = + // Pick just the keys that are not required from the base type. + Except & + // Pick the keys that should be required from the base type and make them required. + Required> extends + // If `InferredType` extends the previous, then for each key, use the inferred type key. + infer InferredType + ? {[KeyType in keyof InferredType]: InferredType[KeyType]} + : never; diff --git a/node_modules/type-fest/source/set-return-type.d.ts b/node_modules/type-fest/source/set-return-type.d.ts new file mode 100644 index 0000000..98766b1 --- /dev/null +++ b/node_modules/type-fest/source/set-return-type.d.ts @@ -0,0 +1,29 @@ +type IsAny = 0 extends (1 & T) ? true : false; // https://stackoverflow.com/a/49928360/3406963 +type IsNever = [T] extends [never] ? true : false; +type IsUnknown = IsNever extends false ? T extends unknown ? unknown extends T ? IsAny extends false ? true : false : false : false : false; + +/** +Create a function type with a return type of your choice and the same parameters as the given function type. + +Use-case: You want to define a wrapped function that returns something different while receiving the same parameters. For example, you might want to wrap a function that can throw an error into one that will return `undefined` instead. + +@example +``` +import {SetReturnType} from 'type-fest'; + +type MyFunctionThatCanThrow = (foo: SomeType, bar: unknown) => SomeOtherType; + +type MyWrappedFunction = SetReturnType; +//=> type MyWrappedFunction = (foo: SomeType, bar: unknown) => SomeOtherType | undefined; +``` +*/ +export type SetReturnType any, TypeToReturn> = + // Just using `Parameters` isn't ideal because it doesn't handle the `this` fake parameter. + Fn extends (this: infer ThisArg, ...args: infer Arguments) => any ? ( + // If a function did not specify the `this` fake parameter, it will be inferred to `unknown`. + // We want to detect this situation just to display a friendlier type upon hovering on an IntelliSense-powered IDE. + IsUnknown extends true ? (...args: Arguments) => TypeToReturn : (this: ThisArg, ...args: Arguments) => TypeToReturn + ) : ( + // This part should be unreachable, but we make it meaningful just in case… + (...args: Parameters) => TypeToReturn + ); diff --git a/node_modules/type-fest/source/stringified.d.ts b/node_modules/type-fest/source/stringified.d.ts new file mode 100644 index 0000000..9688b67 --- /dev/null +++ b/node_modules/type-fest/source/stringified.d.ts @@ -0,0 +1,21 @@ +/** +Create a type with the keys of the given type changed to `string` type. + +Use-case: Changing interface values to strings in order to use them in a form model. + +@example +``` +import {Stringified} from 'type-fest'; + +type Car { + model: string; + speed: number; +} + +const carForm: Stringified = { + model: 'Foo', + speed: '101' +}; +``` +*/ +export type Stringified = {[KeyType in keyof ObjectType]: string}; diff --git a/node_modules/type-fest/source/tsconfig-json.d.ts b/node_modules/type-fest/source/tsconfig-json.d.ts new file mode 100644 index 0000000..89f6e9d --- /dev/null +++ b/node_modules/type-fest/source/tsconfig-json.d.ts @@ -0,0 +1,870 @@ +declare namespace TsConfigJson { + namespace CompilerOptions { + export type JSX = + | 'preserve' + | 'react' + | 'react-native'; + + export type Module = + | 'CommonJS' + | 'AMD' + | 'System' + | 'UMD' + | 'ES6' + | 'ES2015' + | 'ESNext' + | 'None' + // Lowercase alternatives + | 'commonjs' + | 'amd' + | 'system' + | 'umd' + | 'es6' + | 'es2015' + | 'esnext' + | 'none'; + + export type NewLine = + | 'CRLF' + | 'LF' + // Lowercase alternatives + | 'crlf' + | 'lf'; + + export type Target = + | 'ES3' + | 'ES5' + | 'ES6' + | 'ES2015' + | 'ES2016' + | 'ES2017' + | 'ES2018' + | 'ES2019' + | 'ES2020' + | 'ESNext' + // Lowercase alternatives + | 'es3' + | 'es5' + | 'es6' + | 'es2015' + | 'es2016' + | 'es2017' + | 'es2018' + | 'es2019' + | 'es2020' + | 'esnext'; + + export type Lib = + | 'ES5' + | 'ES6' + | 'ES7' + | 'ES2015' + | 'ES2015.Collection' + | 'ES2015.Core' + | 'ES2015.Generator' + | 'ES2015.Iterable' + | 'ES2015.Promise' + | 'ES2015.Proxy' + | 'ES2015.Reflect' + | 'ES2015.Symbol.WellKnown' + | 'ES2015.Symbol' + | 'ES2016' + | 'ES2016.Array.Include' + | 'ES2017' + | 'ES2017.Intl' + | 'ES2017.Object' + | 'ES2017.SharedMemory' + | 'ES2017.String' + | 'ES2017.TypedArrays' + | 'ES2018' + | 'ES2018.AsyncIterable' + | 'ES2018.Intl' + | 'ES2018.Promise' + | 'ES2018.Regexp' + | 'ES2019' + | 'ES2019.Array' + | 'ES2019.Object' + | 'ES2019.String' + | 'ES2019.Symbol' + | 'ES2020' + | 'ES2020.String' + | 'ES2020.Symbol.WellKnown' + | 'ESNext' + | 'ESNext.Array' + | 'ESNext.AsyncIterable' + | 'ESNext.BigInt' + | 'ESNext.Intl' + | 'ESNext.Symbol' + | 'DOM' + | 'DOM.Iterable' + | 'ScriptHost' + | 'WebWorker' + | 'WebWorker.ImportScripts' + // Lowercase alternatives + | 'es5' + | 'es6' + | 'es7' + | 'es2015' + | 'es2015.collection' + | 'es2015.core' + | 'es2015.generator' + | 'es2015.iterable' + | 'es2015.promise' + | 'es2015.proxy' + | 'es2015.reflect' + | 'es2015.symbol.wellknown' + | 'es2015.symbol' + | 'es2016' + | 'es2016.array.include' + | 'es2017' + | 'es2017.intl' + | 'es2017.object' + | 'es2017.sharedmemory' + | 'es2017.string' + | 'es2017.typedarrays' + | 'es2018' + | 'es2018.asynciterable' + | 'es2018.intl' + | 'es2018.promise' + | 'es2018.regexp' + | 'es2019' + | 'es2019.array' + | 'es2019.object' + | 'es2019.string' + | 'es2019.symbol' + | 'es2020' + | 'es2020.string' + | 'es2020.symbol.wellknown' + | 'esnext' + | 'esnext.array' + | 'esnext.asynciterable' + | 'esnext.bigint' + | 'esnext.intl' + | 'esnext.symbol' + | 'dom' + | 'dom.iterable' + | 'scripthost' + | 'webworker' + | 'webworker.importscripts'; + + export interface Plugin { + [key: string]: unknown; + /** + Plugin name. + */ + name?: string; + } + } + + export interface CompilerOptions { + /** + The character set of the input files. + + @default 'utf8' + */ + charset?: string; + + /** + Enables building for project references. + + @default true + */ + composite?: boolean; + + /** + Generates corresponding d.ts files. + + @default false + */ + declaration?: boolean; + + /** + Specify output directory for generated declaration files. + + Requires TypeScript version 2.0 or later. + */ + declarationDir?: string; + + /** + Show diagnostic information. + + @default false + */ + diagnostics?: boolean; + + /** + Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. + + @default false + */ + emitBOM?: boolean; + + /** + Only emit `.d.ts` declaration files. + + @default false + */ + emitDeclarationOnly?: boolean; + + /** + Enable incremental compilation. + + @default `composite` + */ + incremental?: boolean; + + /** + Specify file to store incremental compilation information. + + @default '.tsbuildinfo' + */ + tsBuildInfoFile?: string; + + /** + Emit a single file with source maps instead of having a separate file. + + @default false + */ + inlineSourceMap?: boolean; + + /** + Emit the source alongside the sourcemaps within a single file. + + Requires `--inlineSourceMap` to be set. + + @default false + */ + inlineSources?: boolean; + + /** + Specify JSX code generation: `'preserve'`, `'react'`, or `'react-native'`. + + @default 'preserve' + */ + jsx?: CompilerOptions.JSX; + + /** + Specifies the object invoked for `createElement` and `__spread` when targeting `'react'` JSX emit. + + @default 'React' + */ + reactNamespace?: string; + + /** + Print names of files part of the compilation. + + @default false + */ + listFiles?: boolean; + + /** + Specifies the location where debugger should locate map files instead of generated locations. + */ + mapRoot?: string; + + /** + Specify module code generation: 'None', 'CommonJS', 'AMD', 'System', 'UMD', 'ES6', 'ES2015' or 'ESNext'. Only 'AMD' and 'System' can be used in conjunction with `--outFile`. 'ES6' and 'ES2015' values may be used when targeting 'ES5' or lower. + + @default ['ES3', 'ES5'].includes(target) ? 'CommonJS' : 'ES6' + */ + module?: CompilerOptions.Module; + + /** + Specifies the end of line sequence to be used when emitting files: 'crlf' (Windows) or 'lf' (Unix). + + Default: Platform specific + */ + newLine?: CompilerOptions.NewLine; + + /** + Do not emit output. + + @default false + */ + noEmit?: boolean; + + /** + Do not generate custom helper functions like `__extends` in compiled output. + + @default false + */ + noEmitHelpers?: boolean; + + /** + Do not emit outputs if any type checking errors were reported. + + @default false + */ + noEmitOnError?: boolean; + + /** + Warn on expressions and declarations with an implied 'any' type. + + @default false + */ + noImplicitAny?: boolean; + + /** + Raise error on 'this' expressions with an implied any type. + + @default false + */ + noImplicitThis?: boolean; + + /** + Report errors on unused locals. + + Requires TypeScript version 2.0 or later. + + @default false + */ + noUnusedLocals?: boolean; + + /** + Report errors on unused parameters. + + Requires TypeScript version 2.0 or later. + + @default false + */ + noUnusedParameters?: boolean; + + /** + Do not include the default library file (lib.d.ts). + + @default false + */ + noLib?: boolean; + + /** + Do not add triple-slash references or module import targets to the list of compiled files. + + @default false + */ + noResolve?: boolean; + + /** + Disable strict checking of generic signatures in function types. + + @default false + */ + noStrictGenericChecks?: boolean; + + /** + @deprecated use `skipLibCheck` instead. + */ + skipDefaultLibCheck?: boolean; + + /** + Skip type checking of declaration files. + + Requires TypeScript version 2.0 or later. + + @default false + */ + skipLibCheck?: boolean; + + /** + Concatenate and emit output to single file. + */ + outFile?: string; + + /** + Redirect output structure to the directory. + */ + outDir?: string; + + /** + Do not erase const enum declarations in generated code. + + @default false + */ + preserveConstEnums?: boolean; + + /** + Do not resolve symlinks to their real path; treat a symlinked file like a real one. + + @default false + */ + preserveSymlinks?: boolean; + + /** + Keep outdated console output in watch mode instead of clearing the screen. + + @default false + */ + preserveWatchOutput?: boolean; + + /** + Stylize errors and messages using color and context (experimental). + + @default true // Unless piping to another program or redirecting output to a file. + */ + pretty?: boolean; + + /** + Do not emit comments to output. + + @default false + */ + removeComments?: boolean; + + /** + Specifies the root directory of input files. + + Use to control the output directory structure with `--outDir`. + */ + rootDir?: string; + + /** + Unconditionally emit imports for unresolved files. + + @default false + */ + isolatedModules?: boolean; + + /** + Generates corresponding '.map' file. + + @default false + */ + sourceMap?: boolean; + + /** + Specifies the location where debugger should locate TypeScript files instead of source locations. + */ + sourceRoot?: string; + + /** + Suppress excess property checks for object literals. + + @default false + */ + suppressExcessPropertyErrors?: boolean; + + /** + Suppress noImplicitAny errors for indexing objects lacking index signatures. + + @default false + */ + suppressImplicitAnyIndexErrors?: boolean; + + /** + Do not emit declarations for code that has an `@internal` annotation. + */ + stripInternal?: boolean; + + /** + Specify ECMAScript target version. + + @default 'es3' + */ + target?: CompilerOptions.Target; + + /** + Watch input files. + + @default false + */ + watch?: boolean; + + /** + Enables experimental support for ES7 decorators. + + @default false + */ + experimentalDecorators?: boolean; + + /** + Emit design-type metadata for decorated declarations in source. + + @default false + */ + emitDecoratorMetadata?: boolean; + + /** + Specifies module resolution strategy: 'node' (Node) or 'classic' (TypeScript pre 1.6). + + @default ['AMD', 'System', 'ES6'].includes(module) ? 'classic' : 'node' + */ + moduleResolution?: 'classic' | 'node'; + + /** + Do not report errors on unused labels. + + @default false + */ + allowUnusedLabels?: boolean; + + /** + Report error when not all code paths in function return a value. + + @default false + */ + noImplicitReturns?: boolean; + + /** + Report errors for fallthrough cases in switch statement. + + @default false + */ + noFallthroughCasesInSwitch?: boolean; + + /** + Do not report errors on unreachable code. + + @default false + */ + allowUnreachableCode?: boolean; + + /** + Disallow inconsistently-cased references to the same file. + + @default false + */ + forceConsistentCasingInFileNames?: boolean; + + /** + Base directory to resolve non-relative module names. + */ + baseUrl?: string; + + /** + Specify path mapping to be computed relative to baseUrl option. + */ + paths?: Record; + + /** + List of TypeScript language server plugins to load. + + Requires TypeScript version 2.3 or later. + */ + plugins?: CompilerOptions.Plugin[]; + + /** + Specify list of root directories to be used when resolving modules. + */ + rootDirs?: string[]; + + /** + Specify list of directories for type definition files to be included. + + Requires TypeScript version 2.0 or later. + */ + typeRoots?: string[]; + + /** + Type declaration files to be included in compilation. + + Requires TypeScript version 2.0 or later. + */ + types?: string[]; + + /** + Enable tracing of the name resolution process. + + @default false + */ + traceResolution?: boolean; + + /** + Allow javascript files to be compiled. + + @default false + */ + allowJs?: boolean; + + /** + Do not truncate error messages. + + @default false + */ + noErrorTruncation?: boolean; + + /** + Allow default imports from modules with no default export. This does not affect code emit, just typechecking. + + @default module === 'system' || esModuleInterop + */ + allowSyntheticDefaultImports?: boolean; + + /** + Do not emit `'use strict'` directives in module output. + + @default false + */ + noImplicitUseStrict?: boolean; + + /** + Enable to list all emitted files. + + Requires TypeScript version 2.0 or later. + + @default false + */ + listEmittedFiles?: boolean; + + /** + Disable size limit for JavaScript project. + + Requires TypeScript version 2.0 or later. + + @default false + */ + disableSizeLimit?: boolean; + + /** + List of library files to be included in the compilation. + + Requires TypeScript version 2.0 or later. + */ + lib?: CompilerOptions.Lib[]; + + /** + Enable strict null checks. + + Requires TypeScript version 2.0 or later. + + @default false + */ + strictNullChecks?: boolean; + + /** + The maximum dependency depth to search under `node_modules` and load JavaScript files. Only applicable with `--allowJs`. + + @default 0 + */ + maxNodeModuleJsDepth?: number; + + /** + Import emit helpers (e.g. `__extends`, `__rest`, etc..) from tslib. + + Requires TypeScript version 2.1 or later. + + @default false + */ + importHelpers?: boolean; + + /** + Specify the JSX factory function to use when targeting React JSX emit, e.g. `React.createElement` or `h`. + + Requires TypeScript version 2.1 or later. + + @default 'React.createElement' + */ + jsxFactory?: string; + + /** + Parse in strict mode and emit `'use strict'` for each source file. + + Requires TypeScript version 2.1 or later. + + @default false + */ + alwaysStrict?: boolean; + + /** + Enable all strict type checking options. + + Requires TypeScript version 2.3 or later. + + @default false + */ + strict?: boolean; + + /** + Enable stricter checking of of the `bind`, `call`, and `apply` methods on functions. + + @default false + */ + strictBindCallApply?: boolean; + + /** + Provide full support for iterables in `for-of`, spread, and destructuring when targeting `ES5` or `ES3`. + + Requires TypeScript version 2.3 or later. + + @default false + */ + downlevelIteration?: boolean; + + /** + Report errors in `.js` files. + + Requires TypeScript version 2.3 or later. + + @default false + */ + checkJs?: boolean; + + /** + Disable bivariant parameter checking for function types. + + Requires TypeScript version 2.6 or later. + + @default false + */ + strictFunctionTypes?: boolean; + + /** + Ensure non-undefined class properties are initialized in the constructor. + + Requires TypeScript version 2.7 or later. + + @default false + */ + strictPropertyInitialization?: boolean; + + /** + Emit `__importStar` and `__importDefault` helpers for runtime Babel ecosystem compatibility and enable `--allowSyntheticDefaultImports` for typesystem compatibility. + + Requires TypeScript version 2.7 or later. + + @default false + */ + esModuleInterop?: boolean; + + /** + Allow accessing UMD globals from modules. + + @default false + */ + allowUmdGlobalAccess?: boolean; + + /** + Resolve `keyof` to string valued property names only (no numbers or symbols). + + Requires TypeScript version 2.9 or later. + + @default false + */ + keyofStringsOnly?: boolean; + + /** + Emit ECMAScript standard class fields. + + Requires TypeScript version 3.7 or later. + + @default false + */ + useDefineForClassFields?: boolean; + + /** + Generates a sourcemap for each corresponding `.d.ts` file. + + Requires TypeScript version 2.9 or later. + + @default false + */ + declarationMap?: boolean; + + /** + Include modules imported with `.json` extension. + + Requires TypeScript version 2.9 or later. + + @default false + */ + resolveJsonModule?: boolean; + } + + /** + Auto type (.d.ts) acquisition options for this project. + + Requires TypeScript version 2.1 or later. + */ + export interface TypeAcquisition { + /** + Enable auto type acquisition. + */ + enable?: boolean; + + /** + Specifies a list of type declarations to be included in auto type acquisition. For example, `['jquery', 'lodash']`. + */ + include?: string[]; + + /** + Specifies a list of type declarations to be excluded from auto type acquisition. For example, `['jquery', 'lodash']`. + */ + exclude?: string[]; + } + + export interface References { + /** + A normalized path on disk. + */ + path: string; + + /** + The path as the user originally wrote it. + */ + originalPath?: string; + + /** + True if the output of this reference should be prepended to the output of this project. + + Only valid for `--outFile` compilations. + */ + prepend?: boolean; + + /** + True if it is intended that this reference form a circularity. + */ + circular?: boolean; + } +} + +export interface TsConfigJson { + /** + Instructs the TypeScript compiler how to compile `.ts` files. + */ + compilerOptions?: TsConfigJson.CompilerOptions; + + /** + Auto type (.d.ts) acquisition options for this project. + + Requires TypeScript version 2.1 or later. + */ + typeAcquisition?: TsConfigJson.TypeAcquisition; + + /** + Enable Compile-on-Save for this project. + */ + compileOnSave?: boolean; + + /** + Path to base configuration file to inherit from. + + Requires TypeScript version 2.1 or later. + */ + extends?: string; + + /** + If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`. When a `files` property is specified, only those files and those specified by `include` are included. + */ + files?: string[]; + + /** + Specifies a list of files to be excluded from compilation. The `exclude` property only affects the files included via the `include` property and not the `files` property. + + Glob patterns require TypeScript version 2.0 or later. + */ + exclude?: string[]; + + /** + Specifies a list of glob patterns that match files to be included in compilation. + + If no `files` or `include` property is present in a `tsconfig.json`, the compiler defaults to including all files in the containing directory and subdirectories except those specified by `exclude`. + + Requires TypeScript version 2.0 or later. + */ + include?: string[]; + + /** + Referenced projects. + + Requires TypeScript version 3.0 or later. + */ + references?: TsConfigJson.References[]; +} diff --git a/node_modules/type-fest/source/union-to-intersection.d.ts b/node_modules/type-fest/source/union-to-intersection.d.ts new file mode 100644 index 0000000..5f9837f --- /dev/null +++ b/node_modules/type-fest/source/union-to-intersection.d.ts @@ -0,0 +1,58 @@ +/** +Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). + +Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153). + +@example +``` +import {UnionToIntersection} from 'type-fest'; + +type Union = {the(): void} | {great(arg: string): void} | {escape: boolean}; + +type Intersection = UnionToIntersection; +//=> {the(): void; great(arg: string): void; escape: boolean}; +``` + +A more applicable example which could make its way into your library code follows. + +@example +``` +import {UnionToIntersection} from 'type-fest'; + +class CommandOne { + commands: { + a1: () => undefined, + b1: () => undefined, + } +} + +class CommandTwo { + commands: { + a2: (argA: string) => undefined, + b2: (argB: string) => undefined, + } +} + +const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands); +type Union = typeof union; +//=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void} + +type Intersection = UnionToIntersection; +//=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void} +``` +*/ +export type UnionToIntersection = ( + // `extends unknown` is always going to be the case and is used to convert the + // `Union` into a [distributive conditional + // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). + Union extends unknown + // The union type is used as the only argument to a function since the union + // of function arguments is an intersection. + ? (distributedUnion: Union) => void + // This won't happen. + : never + // Infer the `Intersection` type since TypeScript represents the positional + // arguments of unions of functions as an intersection of the union. + ) extends ((mergedIntersection: infer Intersection) => void) + ? Intersection + : never; diff --git a/node_modules/type-fest/source/utilities.d.ts b/node_modules/type-fest/source/utilities.d.ts new file mode 100644 index 0000000..0bd75e6 --- /dev/null +++ b/node_modules/type-fest/source/utilities.d.ts @@ -0,0 +1,3 @@ +export type UpperCaseCharacters = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' | 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' | 'Y' | 'Z'; + +export type WordSeparators = '-' | '_' | ' '; diff --git a/node_modules/type-fest/source/value-of.d.ts b/node_modules/type-fest/source/value-of.d.ts new file mode 100644 index 0000000..1279373 --- /dev/null +++ b/node_modules/type-fest/source/value-of.d.ts @@ -0,0 +1,40 @@ +/** +Create a union of the given object's values, and optionally specify which keys to get the values from. + +Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/31438) if you want to have this type as a built-in in TypeScript. + +@example +``` +// data.json +{ + 'foo': 1, + 'bar': 2, + 'biz': 3 +} + +// main.ts +import {ValueOf} from 'type-fest'; +import data = require('./data.json'); + +export function getData(name: string): ValueOf { + return data[name]; +} + +export function onlyBar(name: string): ValueOf { + return data[name]; +} + +// file.ts +import {getData, onlyBar} from './main'; + +getData('foo'); +//=> 1 + +onlyBar('foo'); +//=> TypeError ... + +onlyBar('bar'); +//=> 2 +``` +*/ +export type ValueOf = ObjectType[ValueType]; diff --git a/node_modules/type-fest/ts41/camel-case.d.ts b/node_modules/type-fest/ts41/camel-case.d.ts new file mode 100644 index 0000000..4476fd3 --- /dev/null +++ b/node_modules/type-fest/ts41/camel-case.d.ts @@ -0,0 +1,72 @@ +import {WordSeparators} from '../source/utilities'; + +/** +Recursively split a string literal into two parts on the first occurence of the given string, returning an array literal of all the separate parts. +*/ +export type Split = + string extends S ? string[] : + S extends '' ? [] : + S extends `${infer T}${D}${infer U}` ? [T, ...Split] : + [S]; + +/** +Step by step takes the first item in an array literal, formats it and adds it to a string literal, and then recursively appends the remainder. + +Only to be used by `CamelCaseStringArray<>`. + +@see CamelCaseStringArray +*/ +type InnerCamelCaseStringArray = + Parts extends [`${infer FirstPart}`, ...infer RemainingParts] + ? FirstPart extends undefined + ? '' + : FirstPart extends '' + ? InnerCamelCaseStringArray + : `${PreviousPart extends '' ? FirstPart : Capitalize}${InnerCamelCaseStringArray}` + : ''; + +/** +Starts fusing the output of `Split<>`, an array literal of strings, into a camel-cased string literal. + +It's separate from `InnerCamelCaseStringArray<>` to keep a clean API outwards to the rest of the code. + +@see Split +*/ +type CamelCaseStringArray = + Parts extends [`${infer FirstPart}`, ...infer RemainingParts] + ? Uncapitalize<`${FirstPart}${InnerCamelCaseStringArray}`> + : never; + +/** +Convert a string literal to camel-case. + +This can be useful when, for example, converting some kebab-cased command-line flags or a snake-cased database result. + +@example +``` +import {CamelCase} from 'type-fest'; + +// Simple + +const someVariable: CamelCase<'foo-bar'> = 'fooBar'; + +// Advanced + +type CamelCasedProps = { + [K in keyof T as CamelCase]: T[K] +}; + +interface RawOptions { + 'dry-run': boolean; + 'full_family_name': string; + foo: number; +} + +const dbResult: CamelCasedProps = { + dryRun: true, + fullFamilyName: 'bar.js', + foo: 123 +}; +``` +*/ +export type CamelCase = K extends string ? CamelCaseStringArray> : K; diff --git a/node_modules/type-fest/ts41/delimiter-case.d.ts b/node_modules/type-fest/ts41/delimiter-case.d.ts new file mode 100644 index 0000000..52f4eb9 --- /dev/null +++ b/node_modules/type-fest/ts41/delimiter-case.d.ts @@ -0,0 +1,85 @@ +import {UpperCaseCharacters, WordSeparators} from '../source/utilities'; + +/** +Unlike a simpler split, this one includes the delimiter splitted on in the resulting array literal. This is to enable splitting on, for example, upper-case characters. +*/ +export type SplitIncludingDelimiters = + Source extends '' ? [] : + Source extends `${infer FirstPart}${Delimiter}${infer SecondPart}` ? + ( + Source extends `${FirstPart}${infer UsedDelimiter}${SecondPart}` + ? UsedDelimiter extends Delimiter + ? Source extends `${infer FirstPart}${UsedDelimiter}${infer SecondPart}` + ? [...SplitIncludingDelimiters, UsedDelimiter, ...SplitIncludingDelimiters] + : never + : never + : never + ) : + [Source]; + +/** +Format a specific part of the splitted string literal that `StringArrayToDelimiterCase<>` fuses together, ensuring desired casing. + +@see StringArrayToDelimiterCase +*/ +type StringPartToDelimiterCase = + StringPart extends UsedWordSeparators ? Delimiter : + StringPart extends UsedUpperCaseCharacters ? `${Delimiter}${Lowercase}` : + StringPart; + +/** +Takes the result of a splitted string literal and recursively concatenates it together into the desired casing. + +It receives `UsedWordSeparators` and `UsedUpperCaseCharacters` as input to ensure it's fully encapsulated. + +@see SplitIncludingDelimiters +*/ +type StringArrayToDelimiterCase = + Parts extends [`${infer FirstPart}`, ...infer RemainingParts] + ? `${StringPartToDelimiterCase}${StringArrayToDelimiterCase}` + : ''; + +/** +Convert a string literal to a custom string delimiter casing. + +This can be useful when, for example, converting a camel-cased object property to an oddly cased one. + +@see KebabCase +@see SnakeCase + +@example +``` +import {DelimiterCase} from 'type-fest'; + +// Simple + +const someVariable: DelimiterCase<'fooBar', '#'> = 'foo#bar'; + +// Advanced + +type OddlyCasedProps = { + [K in keyof T as DelimiterCase]: T[K] +}; + +interface SomeOptions { + dryRun: boolean; + includeFile: string; + foo: number; +} + +const rawCliOptions: OddlyCasedProps = { + 'dry#run': true, + 'include#file': 'bar.js', + foo: 123 +}; +``` +*/ + +export type DelimiterCase = Value extends string + ? StringArrayToDelimiterCase< + SplitIncludingDelimiters, + WordSeparators, + UpperCaseCharacters, + Delimiter + > + : Value; diff --git a/node_modules/type-fest/ts41/index.d.ts b/node_modules/type-fest/ts41/index.d.ts new file mode 100644 index 0000000..fbaec82 --- /dev/null +++ b/node_modules/type-fest/ts41/index.d.ts @@ -0,0 +1,9 @@ +// These are all the basic types that's compatible with all supported TypeScript versions. +export * from '../base'; + +// These are special types that require at least TypeScript 4.1. +export {CamelCase} from './camel-case'; +export {KebabCase} from './kebab-case'; +export {PascalCase} from './pascal-case'; +export {SnakeCase} from './snake-case'; +export {DelimiterCase} from './delimiter-case'; diff --git a/node_modules/type-fest/ts41/kebab-case.d.ts b/node_modules/type-fest/ts41/kebab-case.d.ts new file mode 100644 index 0000000..ba6a99d --- /dev/null +++ b/node_modules/type-fest/ts41/kebab-case.d.ts @@ -0,0 +1,36 @@ +import {DelimiterCase} from './delimiter-case'; + +/** +Convert a string literal to kebab-case. + +This can be useful when, for example, converting a camel-cased object property to a kebab-cased CSS class name or a command-line flag. + +@example +``` +import {KebabCase} from 'type-fest'; + +// Simple + +const someVariable: KebabCase<'fooBar'> = 'foo-bar'; + +// Advanced + +type KebabCasedProps = { + [K in keyof T as KebabCase]: T[K] +}; + +interface CliOptions { + dryRun: boolean; + includeFile: string; + foo: number; +} + +const rawCliOptions: KebabCasedProps = { + 'dry-run': true, + 'include-file': 'bar.js', + foo: 123 +}; +``` +*/ + +export type KebabCase = DelimiterCase; diff --git a/node_modules/type-fest/ts41/pascal-case.d.ts b/node_modules/type-fest/ts41/pascal-case.d.ts new file mode 100644 index 0000000..bfb2a36 --- /dev/null +++ b/node_modules/type-fest/ts41/pascal-case.d.ts @@ -0,0 +1,36 @@ +import {CamelCase} from './camel-case'; + +/** +Converts a string literal to pascal-case. + +@example +``` +import {PascalCase} from 'type-fest'; + +// Simple + +const someVariable: PascalCase<'foo-bar'> = 'FooBar'; + +// Advanced + +type PascalCaseProps = { + [K in keyof T as PascalCase]: T[K] +}; + +interface RawOptions { + 'dry-run': boolean; + 'full_family_name': string; + foo: number; +} + +const dbResult: CamelCasedProps = { + DryRun: true, + FullFamilyName: 'bar.js', + Foo: 123 +}; +``` +*/ + +export type PascalCase = CamelCase extends string + ? Capitalize> + : CamelCase; diff --git a/node_modules/type-fest/ts41/snake-case.d.ts b/node_modules/type-fest/ts41/snake-case.d.ts new file mode 100644 index 0000000..272b3d3 --- /dev/null +++ b/node_modules/type-fest/ts41/snake-case.d.ts @@ -0,0 +1,35 @@ +import {DelimiterCase} from './delimiter-case'; + +/** +Convert a string literal to snake-case. + +This can be useful when, for example, converting a camel-cased object property to a snake-cased SQL column name. + +@example +``` +import {SnakeCase} from 'type-fest'; + +// Simple + +const someVariable: SnakeCase<'fooBar'> = 'foo_bar'; + +// Advanced + +type SnakeCasedProps = { + [K in keyof T as SnakeCase]: T[K] +}; + +interface ModelProps { + isHappy: boolean; + fullFamilyName: string; + foo: number; +} + +const dbResult: SnakeCasedProps = { + 'is_happy': true, + 'full_family_name': 'Carla Smith', + foo: 123 +}; +``` +*/ +export type SnakeCase = DelimiterCase; diff --git a/node_modules/typedarray-to-buffer/.airtap.yml b/node_modules/typedarray-to-buffer/.airtap.yml new file mode 100644 index 0000000..3417780 --- /dev/null +++ b/node_modules/typedarray-to-buffer/.airtap.yml @@ -0,0 +1,15 @@ +sauce_connect: true +loopback: airtap.local +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: latest + - name: microsoftedge + version: latest + - name: ie + version: latest + - name: iphone + version: latest diff --git a/node_modules/typedarray-to-buffer/.travis.yml b/node_modules/typedarray-to-buffer/.travis.yml new file mode 100644 index 0000000..f25afbd --- /dev/null +++ b/node_modules/typedarray-to-buffer/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - lts/* +addons: + sauce_connect: true + hosts: + - airtap.local +env: + global: + - secure: i51rE9rZGHbcZWlL58j3H1qtL23OIV2r0X4TcQKNI3pw2mubdHFJmfPNNO19ItfReu8wwQMxOehKamwaNvqMiKWyHfn/QcThFQysqzgGZ6AgnUbYx9od6XFNDeWd1sVBf7QBAL07y7KWlYGWCwFwWjabSVySzQhEBdisPcskfkI= + - secure: BKq6/5z9LK3KDkTjs7BGeBZ1KsWgz+MsAXZ4P64NSeVGFaBdXU45+ww1mwxXFt5l22/mhyOQZfebQl+kGVqRSZ+DEgQeCymkNZ6CD8c6w6cLuOJXiXwuu/cDM2DD0tfGeu2YZC7yEikP7BqEFwH3D324rRzSGLF2RSAAwkOI7bE= diff --git a/node_modules/typedarray-to-buffer/LICENSE b/node_modules/typedarray-to-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/typedarray-to-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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/typedarray-to-buffer/README.md b/node_modules/typedarray-to-buffer/README.md new file mode 100644 index 0000000..35761fb --- /dev/null +++ b/node_modules/typedarray-to-buffer/README.md @@ -0,0 +1,85 @@ +# typedarray-to-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/typedarray-to-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/typedarray-to-buffer +[npm-image]: https://img.shields.io/npm/v/typedarray-to-buffer.svg +[npm-url]: https://npmjs.org/package/typedarray-to-buffer +[downloads-image]: https://img.shields.io/npm/dm/typedarray-to-buffer.svg +[downloads-url]: https://npmjs.org/package/typedarray-to-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Convert a typed array to a [Buffer](https://github.com/feross/buffer) without a copy. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/typedarray-to-buffer.svg +[saucelabs-url]: https://saucelabs.com/u/typedarray-to-buffer + +Say you're using the ['buffer'](https://github.com/feross/buffer) module on npm, or +[browserify](http://browserify.org/) and you're working with lots of binary data. + +Unfortunately, sometimes the browser or someone else's API gives you a typed array like +`Uint8Array` to work with and you need to convert it to a `Buffer`. What do you do? + +Of course: `Buffer.from(uint8array)` + +But, alas, every time you do `Buffer.from(uint8array)` **the entire array gets copied**. +The `Buffer` constructor does a copy; this is +defined by the [node docs](http://nodejs.org/api/buffer.html) and the 'buffer' module +matches the node API exactly. + +So, how can we avoid this expensive copy in +[performance critical applications](https://github.com/feross/buffer/issues/22)? + +***Simply use this module, of course!*** + +If you have an `ArrayBuffer`, you don't need this module, because +`Buffer.from(arrayBuffer)` +[is already efficient](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length). + +## install + +```bash +npm install typedarray-to-buffer +``` + +## usage + +To convert a typed array to a `Buffer` **without a copy**, do this: + +```js +var toBuffer = require('typedarray-to-buffer') + +var arr = new Uint8Array([1, 2, 3]) +arr = toBuffer(arr) + +// arr is a buffer now! + +arr.toString() // '\u0001\u0002\u0003' +arr.readUInt16BE(0) // 258 +``` + +## how it works + +If the browser supports typed arrays, then `toBuffer` will **augment the typed array** you +pass in with the `Buffer` methods and return it. See [how does Buffer +work?](https://github.com/feross/buffer#how-does-it-work) for more about how augmentation +works. + +This module uses the typed array's underlying `ArrayBuffer` to back the new `Buffer`. This +respects the "view" on the `ArrayBuffer`, i.e. `byteOffset` and `byteLength`. In other +words, if you do `toBuffer(new Uint32Array([1, 2, 3]))`, then the new `Buffer` will +contain `[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]`, **not** `[1, 2, 3]`. And it still doesn't +require a copy. + +If the browser doesn't support typed arrays, then `toBuffer` will create a new `Buffer` +object, copy the data into it, and return it. There's no simple performance optimization +we can do for old browsers. Oh well. + +If this module is used in node, then it will just call `Buffer.from`. This is just for +the convenience of modules that work in both node and the browser. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). diff --git a/node_modules/typedarray-to-buffer/index.js b/node_modules/typedarray-to-buffer/index.js new file mode 100644 index 0000000..5fa394d --- /dev/null +++ b/node_modules/typedarray-to-buffer/index.js @@ -0,0 +1,25 @@ +/** + * Convert a typed array to a Buffer without a copy + * + * Author: Feross Aboukhadijeh + * License: MIT + * + * `npm install typedarray-to-buffer` + */ + +var isTypedArray = require('is-typedarray').strict + +module.exports = function typedarrayToBuffer (arr) { + if (isTypedArray(arr)) { + // To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer + var buf = Buffer.from(arr.buffer) + if (arr.byteLength !== arr.buffer.byteLength) { + // Respect the "view", i.e. byteOffset and byteLength, without doing a copy + buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength) + } + return buf + } else { + // Pass through all other types to `Buffer.from` + return Buffer.from(arr) + } +} diff --git a/node_modules/typedarray-to-buffer/package.json b/node_modules/typedarray-to-buffer/package.json new file mode 100644 index 0000000..31f9024 --- /dev/null +++ b/node_modules/typedarray-to-buffer/package.json @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "typedarray-to-buffer@3.1.5", + "/home/other/discord_bot" + ] + ], + "_from": "typedarray-to-buffer@3.1.5", + "_id": "typedarray-to-buffer@3.1.5", + "_inBundle": false, + "_integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "_location": "/typedarray-to-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "typedarray-to-buffer@3.1.5", + "name": "typedarray-to-buffer", + "escapedName": "typedarray-to-buffer", + "rawSpec": "3.1.5", + "saveSpec": null, + "fetchSpec": "3.1.5" + }, + "_requiredBy": [ + "/write-file-atomic" + ], + "_resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "_spec": "3.1.5", + "_where": "/home/other/discord_bot", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org/" + }, + "bugs": { + "url": "https://github.com/feross/typedarray-to-buffer/issues" + }, + "dependencies": { + "is-typedarray": "^1.0.0" + }, + "description": "Convert a typed array to a Buffer without a copy", + "devDependencies": { + "airtap": "0.0.4", + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "http://feross.org", + "keywords": [ + "buffer", + "typed array", + "convert", + "no copy", + "uint8array", + "uint16array", + "uint32array", + "int16array", + "int32array", + "float32array", + "float64array", + "browser", + "arraybuffer", + "dataview" + ], + "license": "MIT", + "main": "index.js", + "name": "typedarray-to-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/typedarray-to-buffer.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "version": "3.1.5" +} diff --git a/node_modules/typedarray-to-buffer/test/basic.js b/node_modules/typedarray-to-buffer/test/basic.js new file mode 100644 index 0000000..3521096 --- /dev/null +++ b/node_modules/typedarray-to-buffer/test/basic.js @@ -0,0 +1,50 @@ +var test = require('tape') +var toBuffer = require('../') + +test('convert to buffer from Uint8Array', function (t) { + if (typeof Uint8Array !== 'undefined') { + var arr = new Uint8Array([1, 2, 3]) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([1, 2, 3]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt8(0), 1) + t.equal(arr.readUInt8(1), 2) + t.equal(arr.readUInt8(2), 3) + } else { + t.pass('browser lacks Uint8Array support, skip test') + } + t.end() +}) + +test('convert to buffer from another arrayview type (Uint32Array)', function (t) { + if (typeof Uint32Array !== 'undefined' && Buffer.TYPED_ARRAY_SUPPORT !== false) { + var arr = new Uint32Array([1, 2, 3]) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt32LE(0), 1) + t.equal(arr.readUInt32LE(4), 2) + t.equal(arr.readUInt32LE(8), 3) + t.equal(arr instanceof Uint8Array, true) + } else { + t.pass('browser lacks Uint32Array support, skip test') + } + t.end() +}) + +test('convert to buffer from ArrayBuffer', function (t) { + if (typeof Uint32Array !== 'undefined' && Buffer.TYPED_ARRAY_SUPPORT !== false) { + var arr = new Uint32Array([1, 2, 3]).subarray(1, 2) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([2, 0, 0, 0]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt32LE(0), 2) + t.equal(arr instanceof Uint8Array, true) + } else { + t.pass('browser lacks ArrayBuffer support, skip test') + } + t.end() +}) diff --git a/node_modules/undefsafe/.github/workflows/release.yml b/node_modules/undefsafe/.github/workflows/release.yml new file mode 100644 index 0000000..e6ee886 --- /dev/null +++ b/node_modules/undefsafe/.github/workflows/release.yml @@ -0,0 +1,25 @@ +name: Release +on: + push: + branches: + - master +jobs: + release: + name: Release + runs-on: ubuntu-18.04 + steps: + - name: Checkout + uses: actions/checkout@v1 + - name: Setup Node.js + uses: actions/setup-node@v1 + with: + node-version: 16 + - name: Install dependencies + run: npm ci + - name: Test + run: npm run test + - name: Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + run: npx semantic-release diff --git a/node_modules/undefsafe/.jscsrc b/node_modules/undefsafe/.jscsrc new file mode 100644 index 0000000..9e01c9b --- /dev/null +++ b/node_modules/undefsafe/.jscsrc @@ -0,0 +1,13 @@ +{ + "preset": "node-style-guide", + "requireCapitalizedComments": null, + "requireSpacesInAnonymousFunctionExpression": { + "beforeOpeningCurlyBrace": true, + "beforeOpeningRoundBrace": true + }, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "excludeFiles": ["node_modules/**"], + "disallowSpacesInFunction": null +} diff --git a/node_modules/undefsafe/.jshintrc b/node_modules/undefsafe/.jshintrc new file mode 100644 index 0000000..b47f672 --- /dev/null +++ b/node_modules/undefsafe/.jshintrc @@ -0,0 +1,16 @@ +{ + "browser": false, + "camelcase": true, + "curly": true, + "devel": true, + "eqeqeq": true, + "forin": true, + "indent": 2, + "noarg": true, + "node": true, + "quotmark": "single", + "undef": true, + "strict": false, + "unused": true +} + diff --git a/node_modules/undefsafe/.travis.yml b/node_modules/undefsafe/.travis.yml new file mode 100644 index 0000000..a1ace24 --- /dev/null +++ b/node_modules/undefsafe/.travis.yml @@ -0,0 +1,18 @@ +sudo: false +language: node_js +cache: + directories: + - node_modules +notifications: + email: false +node_js: + - '4' +before_install: + - npm i -g npm@^2.0.0 +before_script: + - npm prune +after_success: + - npm run semantic-release +branches: + except: + - "/^v\\d+\\.\\d+\\.\\d+$/" diff --git a/node_modules/undefsafe/LICENSE b/node_modules/undefsafe/LICENSE new file mode 100644 index 0000000..caaf03a --- /dev/null +++ b/node_modules/undefsafe/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright © 2016 Remy Sharp, http://remysharp.com + +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/undefsafe/README.md b/node_modules/undefsafe/README.md new file mode 100644 index 0000000..46a706b --- /dev/null +++ b/node_modules/undefsafe/README.md @@ -0,0 +1,63 @@ +# undefsafe + +Simple *function* for retrieving deep object properties without getting "Cannot read property 'X' of undefined" + +Can also be used to safely set deep values. + +## Usage + +```js +var object = { + a: { + b: { + c: 1, + d: [1,2,3], + e: 'remy' + } + } +}; + +console.log(undefsafe(object, 'a.b.e')); // "remy" +console.log(undefsafe(object, 'a.b.not.found')); // undefined +``` + +Demo: [https://jsbin.com/eroqame/3/edit?js,console](https://jsbin.com/eroqame/3/edit?js,console) + +## Setting + +```js +var object = { + a: { + b: [1,2,3] + } +}; + +// modified object +var res = undefsafe(object, 'a.b.0', 10); + +console.log(object); // { a: { b: [10, 2, 3] } } +console.log(res); // 1 - previous value +``` + +## Star rules in paths + +As of 1.2.0, `undefsafe` supports a `*` in the path if you want to search all of the properties (or array elements) for a particular element. + +The function will only return a single result, either the 3rd argument validation value, or the first positive match. For example, the following github data: + +```js +const githubData = { + commits: [{ + modified: [ + "one", + "two" + ] + }, /* ... */ ] + }; + +// first modified file found in the first commit +console.log(undefsafe(githubData, 'commits.*.modified.0')); + +// returns `two` or undefined if not found +console.log(undefsafe(githubData, 'commits.*.modified.*', 'two')); +``` diff --git a/node_modules/undefsafe/example.js b/node_modules/undefsafe/example.js new file mode 100644 index 0000000..ed93c23 --- /dev/null +++ b/node_modules/undefsafe/example.js @@ -0,0 +1,14 @@ +var undefsafe = require('undefsafe'); + +var object = { + a: { + b: { + c: 1, + d: [1, 2, 3], + e: 'remy' + } + } +}; + +console.log(undefsafe(object, 'a.b.e')); // "remy" +console.log(undefsafe(object, 'a.b.not.found')); // undefined diff --git a/node_modules/undefsafe/lib/undefsafe.js b/node_modules/undefsafe/lib/undefsafe.js new file mode 100644 index 0000000..7446878 --- /dev/null +++ b/node_modules/undefsafe/lib/undefsafe.js @@ -0,0 +1,125 @@ +'use strict'; + +function undefsafe(obj, path, value, __res) { + // I'm not super keen on this private function, but it's because + // it'll also be use in the browser and I wont *one* function exposed + function split(path) { + var res = []; + var level = 0; + var key = ''; + + for (var i = 0; i < path.length; i++) { + var c = path.substr(i, 1); + + if (level === 0 && (c === '.' || c === '[')) { + if (c === '[') { + level++; + i++; + c = path.substr(i, 1); + } + + if (key) { + // the first value could be a string + res.push(key); + } + key = ''; + continue; + } + + if (c === ']') { + level--; + key = key.slice(0, -1); + continue; + } + + key += c; + } + + res.push(key); + + return res; + } + + // bail if there's nothing + if (obj === undefined || obj === null) { + return undefined; + } + + var parts = split(path); + var key = null; + var type = typeof obj; + var root = obj; + var parent = obj; + + var star = + parts.filter(function(_) { + return _ === '*'; + }).length > 0; + + // we're dealing with a primitive + if (type !== 'object' && type !== 'function') { + return obj; + } else if (path.trim() === '') { + return obj; + } + + key = parts[0]; + var i = 0; + for (; i < parts.length; i++) { + key = parts[i]; + parent = obj; + + if (key === '*') { + // loop through each property + var prop = ''; + var res = __res || []; + + for (prop in parent) { + var shallowObj = undefsafe( + obj[prop], + parts.slice(i + 1).join('.'), + value, + res + ); + if (shallowObj && shallowObj !== res) { + if ((value && shallowObj === value) || value === undefined) { + if (value !== undefined) { + return shallowObj; + } + + res.push(shallowObj); + } + } + } + + if (res.length === 0) { + return undefined; + } + + return res; + } + + if (Object.getOwnPropertyNames(obj).indexOf(key) == -1) { + return undefined; + } + + obj = obj[key]; + if (obj === undefined || obj === null) { + break; + } + } + + // if we have a null object, make sure it's the one the user was after, + // if it's not (i.e. parts has a length) then give undefined back. + if (obj === null && i !== parts.length - 1) { + obj = undefined; + } else if (!star && value) { + key = path.split('.').pop(); + parent[key] = value; + } + return obj; +} + +if (typeof module !== 'undefined') { + module.exports = undefsafe; +} diff --git a/node_modules/undefsafe/package.json b/node_modules/undefsafe/package.json new file mode 100644 index 0000000..8d2a4b1 --- /dev/null +++ b/node_modules/undefsafe/package.json @@ -0,0 +1,65 @@ +{ + "_from": "undefsafe@^2.0.5", + "_id": "undefsafe@2.0.5", + "_inBundle": false, + "_integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==", + "_location": "/undefsafe", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "undefsafe@^2.0.5", + "name": "undefsafe", + "escapedName": "undefsafe", + "rawSpec": "^2.0.5", + "saveSpec": null, + "fetchSpec": "^2.0.5" + }, + "_requiredBy": [ + "/nodemon" + ], + "_resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "_shasum": "38733b9327bdcd226db889fb723a6efd162e6e2c", + "_spec": "undefsafe@^2.0.5", + "_where": "/home/other/discord_bot/node_modules/nodemon", + "author": { + "name": "Remy Sharp" + }, + "bugs": { + "url": "https://github.com/remy/undefsafe/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Undefined safe way of extracting object properties", + "devDependencies": { + "semantic-release": "^18.0.0", + "tap": "^5.7.1", + "tap-only": "0.0.5" + }, + "directories": { + "test": "test" + }, + "homepage": "https://github.com/remy/undefsafe#readme", + "keywords": [ + "undefined" + ], + "license": "MIT", + "main": "lib/undefsafe.js", + "name": "undefsafe", + "prettier": { + "trailingComma": "none", + "singleQuote": true + }, + "repository": { + "type": "git", + "url": "git+https://github.com/remy/undefsafe.git" + }, + "scripts": { + "cover": "tap test/*.test.js --cov --coverage-report=lcov", + "semantic-release": "semantic-release", + "test": "tap test/**/*.test.js -R spec" + }, + "tonicExampleFilename": "example.js", + "version": "2.0.5" +} diff --git a/node_modules/undici/LICENSE b/node_modules/undici/LICENSE new file mode 100644 index 0000000..e7323bb --- /dev/null +++ b/node_modules/undici/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +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/undici/README.md b/node_modules/undici/README.md new file mode 100644 index 0000000..05a5d21 --- /dev/null +++ b/node_modules/undici/README.md @@ -0,0 +1,438 @@ +# undici + +[![Node CI](https://github.com/nodejs/undici/actions/workflows/nodejs.yml/badge.svg)](https://github.com/nodejs/undici/actions/workflows/nodejs.yml) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) [![npm version](https://badge.fury.io/js/undici.svg)](https://badge.fury.io/js/undici) [![codecov](https://codecov.io/gh/nodejs/undici/branch/main/graph/badge.svg?token=yZL6LtXkOA)](https://codecov.io/gh/nodejs/undici) + +An HTTP/1.1 client, written from scratch for Node.js. + +> Undici means eleven in Italian. 1.1 -> 11 -> Eleven -> Undici. +It is also a Stranger Things reference. + +Have a question about using Undici? Open a [Q&A Discussion](https://github.com/nodejs/undici/discussions/new) or join our official OpenJS [Slack](https://openjs-foundation.slack.com/archives/C01QF9Q31QD) channel. + +## Install + +``` +npm i undici +``` + +## Benchmarks + +The benchmark is a simple `hello world` [example](benchmarks/benchmark.js) using a +number of unix sockets (connections) with a pipelining depth of 10 running on Node 16. +The benchmarks below have the [simd](https://github.com/WebAssembly/simd) feature enabled. + +### Connections 1 + +| Tests | Samples | Result | Tolerance | Difference with slowest | +|---------------------|---------|---------------|-----------|-------------------------| +| http - no keepalive | 15 | 4.63 req/sec | ± 2.77 % | - | +| http - keepalive | 10 | 4.81 req/sec | ± 2.16 % | + 3.94 % | +| undici - stream | 25 | 62.22 req/sec | ± 2.67 % | + 1244.58 % | +| undici - dispatch | 15 | 64.33 req/sec | ± 2.47 % | + 1290.24 % | +| undici - request | 15 | 66.08 req/sec | ± 2.48 % | + 1327.88 % | +| undici - pipeline | 10 | 66.13 req/sec | ± 1.39 % | + 1329.08 % | + +### Connections 50 + +| Tests | Samples | Result | Tolerance | Difference with slowest | +|---------------------|---------|------------------|-----------|-------------------------| +| http - no keepalive | 50 | 3546.49 req/sec | ± 2.90 % | - | +| http - keepalive | 15 | 5692.67 req/sec | ± 2.48 % | + 60.52 % | +| undici - pipeline | 25 | 8478.71 req/sec | ± 2.62 % | + 139.07 % | +| undici - request | 20 | 9766.66 req/sec | ± 2.79 % | + 175.39 % | +| undici - stream | 15 | 10109.74 req/sec | ± 2.94 % | + 185.06 % | +| undici - dispatch | 25 | 10949.73 req/sec | ± 2.54 % | + 208.75 % | + +## Quick Start + +```js +import { request } from 'undici' + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) +console.log('headers', headers) + +for await (const data of body) { + console.log('data', data) +} + +console.log('trailers', trailers) +``` + +## Body Mixins + +The `body` mixins are the most common way to format the request/response body. Mixins include: + +- [`.formData()`](https://fetch.spec.whatwg.org/#dom-body-formdata) +- [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +- [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) + +Example usage: + +```js +import { request } from 'undici' + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) +console.log('headers', headers) +console.log('data', await body.json()) +console.log('trailers', trailers) +``` + +_Note: Once a mixin has been called then the body cannot be reused, thus calling additional mixins on `.body`, e.g. `.body.json(); .body.text()` will result in an error `TypeError: unusable` being thrown and returned through the `Promise` rejection._ + +Should you need to access the `body` in plain-text after using a mixin, the best practice is to use the `.text()` mixin first and then manually parse the text to the desired format. + +For more information about their behavior, please reference the body mixin from the [Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). + +## Common API Methods + +This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site. + +### `undici.request([url, options]): Promise` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`RequestOptions`](./docs/api/Dispatcher.md#parameter-requestoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` + +Returns a promise with the result of the `Dispatcher.request` method. + +Calls `options.dispatcher.request(options)`. + +See [Dispatcher.request](./docs/api/Dispatcher.md#dispatcherrequestoptions-callback) for more details. + +### `undici.stream([url, options, ]factory): Promise` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`StreamOptions`](./docs/api/Dispatcher.md#parameter-streamoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` +* **factory** `Dispatcher.stream.factory` + +Returns a promise with the result of the `Dispatcher.stream` method. + +Calls `options.dispatcher.stream(options, factory)`. + +See [Dispatcher.stream](docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback) for more details. + +### `undici.pipeline([url, options, ]handler): Duplex` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`PipelineOptions`](docs/api/Dispatcher.md#parameter-pipelineoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` +* **handler** `Dispatcher.pipeline.handler` + +Returns: `stream.Duplex` + +Calls `options.dispatch.pipeline(options, handler)`. + +See [Dispatcher.pipeline](docs/api/Dispatcher.md#dispatcherpipelineoptions-handler) for more details. + +### `undici.connect([url, options]): Promise` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`ConnectOptions`](docs/api/Dispatcher.md#parameter-connectoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **maxRedirections** `Integer` - Default: `0` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns a promise with the result of the `Dispatcher.connect` method. + +Calls `options.dispatch.connect(options)`. + +See [Dispatcher.connect](docs/api/Dispatcher.md#dispatcherconnectoptions-callback) for more details. + +### `undici.fetch(input[, init]): Promise` + +Implements [fetch](https://fetch.spec.whatwg.org/#fetch-method). + +* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch +* https://fetch.spec.whatwg.org/#fetch-method + +Only supported on Node 16.8+. + +Basic usage example: + +```js +import { fetch } from 'undici' + + +const res = await fetch('https://example.com') +const json = await res.json() +console.log(json) +``` + +You can pass an optional dispatcher to `fetch` as: + +```js +import { fetch, Agent } from 'undici' + +const res = await fetch('https://example.com', { + // Mocks are also supported + dispatcher: new Agent({ + keepAliveTimeout: 10, + keepAliveMaxTimeout: 10 + }) +}) +const json = await res.json() +console.log(json) +``` + +#### `request.body` + +A body can be of the following types: + +- ArrayBuffer +- ArrayBufferView +- AsyncIterables +- Blob +- Iterables +- String +- URLSearchParams +- FormData + +In this implementation of fetch, ```request.body``` now accepts ```Async Iterables```. It is not present in the [Fetch Standard.](https://fetch.spec.whatwg.org) + +```js +import { fetch } from 'undici' + +const data = { + async *[Symbol.asyncIterator]() { + yield 'hello' + yield 'world' + }, +} + +await fetch('https://example.com', { body: data, method: 'POST', duplex: 'half' }) +``` + +#### `request.duplex` + +- half + +In this implementation of fetch, `request.duplex` must be set if `request.body` is `ReadableStream` or `Async Iterables`. And fetch requests are currently always be full duplex. More detail refer to [Fetch Standard.](https://fetch.spec.whatwg.org/#dom-requestinit-duplex) + +#### `response.body` + +Nodejs has two kinds of streams: [web streams](https://nodejs.org/dist/latest-v16.x/docs/api/webstreams.html), which follow the API of the WHATWG web standard found in browsers, and an older Node-specific [streams API](https://nodejs.org/api/stream.html). `response.body` returns a readable web stream. If you would prefer to work with a Node stream you can convert a web stream using `.fromWeb()`. + +```js +import { fetch } from 'undici' +import { Readable } from 'node:stream' + +const response = await fetch('https://example.com') +const readableWebStream = response.body +const readableNodeStream = Readable.fromWeb(readableWebStream) +``` + +#### Specification Compliance + +This section documents parts of the [Fetch Standard](https://fetch.spec.whatwg.org) that Undici does +not support or does not fully implement. + +##### Garbage Collection + +* https://fetch.spec.whatwg.org/#garbage-collection + +The [Fetch Standard](https://fetch.spec.whatwg.org) allows users to skip consuming the response body by relying on +[garbage collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management#garbage_collection) to release connection resources. Undici does not do the same. Therefore, it is important to always either consume or cancel the response body. + +Garbage collection in Node is less aggressive and deterministic +(due to the lack of clear idle periods that browsers have through the rendering refresh rate) +which means that leaving the release of connection resources to the garbage collector can lead +to excessive connection usage, reduced performance (due to less connection re-use), and even +stalls or deadlocks when running out of connections. + +```js +// Do +const headers = await fetch(url) + .then(async res => { + for await (const chunk of res.body) { + // force consumption of body + } + return res.headers + }) + +// Do not +const headers = await fetch(url) + .then(res => res.headers) +``` + +However, if you want to get only headers, it might be better to use `HEAD` request method. Usage of this method will obviate the need for consumption or cancelling of the response body. See [MDN - HTTP - HTTP request methods - HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) for more details. + +```js +const headers = await fetch(url, { method: 'HEAD' }) + .then(res => res.headers) +``` + +##### Forbidden and Safelisted Header Names + +* https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name +* https://fetch.spec.whatwg.org/#forbidden-header-name +* https://fetch.spec.whatwg.org/#forbidden-response-header-name +* https://github.com/wintercg/fetch/issues/6 + +The [Fetch Standard](https://fetch.spec.whatwg.org) requires implementations to exclude certain headers from requests and responses. In browser environments, some headers are forbidden so the user agent remains in full control over them. In Undici, these constraints are removed to give more control to the user. + +### `undici.upgrade([url, options]): Promise` + +Upgrade to a different protocol. See [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`UpgradeOptions`](docs/api/Dispatcher.md#parameter-upgradeoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **maxRedirections** `Integer` - Default: `0` +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns a promise with the result of the `Dispatcher.upgrade` method. + +Calls `options.dispatcher.upgrade(options)`. + +See [Dispatcher.upgrade](docs/api/Dispatcher.md#dispatcherupgradeoptions-callback) for more details. + +### `undici.setGlobalDispatcher(dispatcher)` + +* dispatcher `Dispatcher` + +Sets the global dispatcher used by Common API Methods. + +### `undici.getGlobalDispatcher()` + +Gets the global dispatcher used by Common API Methods. + +Returns: `Dispatcher` + +### `undici.setGlobalOrigin(origin)` + +* origin `string | URL | undefined` + +Sets the global origin used in `fetch`. + +If `undefined` is passed, the global origin will be reset. This will cause `Response.redirect`, `new Request()`, and `fetch` to throw an error when a relative path is passed. + +```js +setGlobalOrigin('http://localhost:3000') + +const response = await fetch('/api/ping') + +console.log(response.url) // http://localhost:3000/api/ping +``` + +### `undici.getGlobalOrigin()` + +Gets the global origin used in `fetch`. + +Returns: `URL` + +### `UrlObject` + +* **port** `string | number` (optional) +* **path** `string` (optional) +* **pathname** `string` (optional) +* **hostname** `string` (optional) +* **origin** `string` (optional) +* **protocol** `string` (optional) +* **search** `string` (optional) + +## Specification Compliance + +This section documents parts of the HTTP/1.1 specification that Undici does +not support or does not fully implement. + +### Expect + +Undici does not support the `Expect` request header field. The request +body is always immediately sent and the `100 Continue` response will be +ignored. + +Refs: https://tools.ietf.org/html/rfc7231#section-5.1.1 + +### Pipelining + +Undici will only use pipelining if configured with a `pipelining` factor +greater than `1`. + +Undici always assumes that connections are persistent and will immediately +pipeline requests, without checking whether the connection is persistent. +Hence, automatic fallback to HTTP/1.0 or HTTP/1.1 without pipelining is +not supported. + +Undici will immediately pipeline when retrying requests after a failed +connection. However, Undici will not retry the first remaining requests in +the prior pipeline and instead error the corresponding callback/promise/stream. + +Undici will abort all running requests in the pipeline when any of them are +aborted. + +* Refs: https://tools.ietf.org/html/rfc2616#section-8.1.2.2 +* Refs: https://tools.ietf.org/html/rfc7230#section-6.3.2 + +### Manual Redirect + +Since it is not possible to manually follow an HTTP redirect on the server-side, +Undici returns the actual response instead of an `opaqueredirect` filtered one +when invoked with a `manual` redirect. This aligns `fetch()` with the other +implementations in Deno and Cloudflare Workers. + +Refs: https://fetch.spec.whatwg.org/#atomic-http-redirect-handling + +## Workarounds + +### Network address family autoselection. + +If you experience problem when connecting to a remote server that is resolved by your DNS servers to a IPv6 (AAAA record) +first, there are chances that your local router or ISP might have problem connecting to IPv6 networks. In that case +undici will throw an error with code `UND_ERR_CONNECT_TIMEOUT`. + +If the target server resolves to both a IPv6 and IPv4 (A records) address and you are using a compatible Node version +(18.3.0 and above), you can fix the problem by providing the `autoSelectFamily` option (support by both `undici.request` +and `undici.Agent`) which will enable the family autoselection algorithm when establishing the connection. + +## Collaborators + +* [__Daniele Belardi__](https://github.com/dnlup), +* [__Ethan Arrowood__](https://github.com/ethan-arrowood), +* [__Matteo Collina__](https://github.com/mcollina), +* [__Matthew Aitken__](https://github.com/KhafraDev), +* [__Robert Nagy__](https://github.com/ronag), +* [__Szymon Marczak__](https://github.com/szmarczak), +* [__Tomas Della Vedova__](https://github.com/delvedor), + +### Releasers + +* [__Ethan Arrowood__](https://github.com/ethan-arrowood), +* [__Matteo Collina__](https://github.com/mcollina), +* [__Robert Nagy__](https://github.com/ronag), + +## License + +MIT diff --git a/node_modules/undici/docs/api/Agent.md b/node_modules/undici/docs/api/Agent.md new file mode 100644 index 0000000..dd5d99b --- /dev/null +++ b/node_modules/undici/docs/api/Agent.md @@ -0,0 +1,80 @@ +# Agent + +Extends: `undici.Dispatcher` + +Agent allow dispatching requests against multiple different origins. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new undici.Agent([options])` + +Arguments: + +* **options** `AgentOptions` (optional) + +Returns: `Agent` + +### Parameter: `AgentOptions` + +Extends: [`PoolOptions`](Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` +* **maxRedirections** `Integer` - Default: `0`. The number of HTTP redirection to follow unless otherwise specified in `DispatchOptions`. +* **interceptors** `{ Agent: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. + +## Instance Properties + +### `Agent.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `Agent.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +## Instance Methods + +### `Agent.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Agent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` +* **maxRedirections** `Integer`. + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Agent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Agent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Agent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Agent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Agent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). diff --git a/node_modules/undici/docs/api/BalancedPool.md b/node_modules/undici/docs/api/BalancedPool.md new file mode 100644 index 0000000..290c734 --- /dev/null +++ b/node_modules/undici/docs/api/BalancedPool.md @@ -0,0 +1,99 @@ +# Class: BalancedPool + +Extends: `undici.Dispatcher` + +A pool of [Pool](Pool.md) instances connected to multiple upstreams. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new BalancedPool(upstreams [, options])` + +Arguments: + +* **upstreams** `URL | string | string[]` - It should only include the **protocol, hostname, and port**. +* **options** `BalancedPoolOptions` (optional) + +### Parameter: `BalancedPoolOptions` + +Extends: [`PoolOptions`](Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` + +The `PoolOptions` are passed to each of the `Pool` instances being created. +## Instance Properties + +### `BalancedPool.upstreams` + +Returns an array of upstreams that were previously added. + +### `BalancedPool.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `BalancedPool.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `BalancedPool.addUpstream(upstream)` + +Add an upstream. + +Arguments: + +* **upstream** `string` - It should only include the **protocol, hostname, and port**. + +### `BalancedPool.removeUpstream(upstream)` + +Removes an upstream that was previously addded. + +### `BalancedPool.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `BalancedPool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `BalancedPool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `BalancedPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `BalancedPool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `BalancedPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `BalancedPool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `BalancedPool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/api/Client.md b/node_modules/undici/docs/api/Client.md new file mode 100644 index 0000000..fc7c5d2 --- /dev/null +++ b/node_modules/undici/docs/api/Client.md @@ -0,0 +1,269 @@ +# Class: Client + +Extends: `undici.Dispatcher` + +A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Client(url[, options])` + +Arguments: + +* **url** `URL | string` - Should only include the **protocol, hostname, and port**. +* **options** `ClientOptions` (optional) + +Returns: `Client` + +### Parameter: `ClientOptions` + +* **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout` when overridden by *keep-alive* hints from the server. Defaults to 10 minutes. +* **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. +* **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `1e3` - A number subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 1 second. +* **maxHeaderSize** `number | null` (optional) - Default: `16384` - The maximum length of request headers in bytes. Defaults to 16KiB. +* **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. +* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections. +* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`. +* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. +* **interceptors** `{ Client: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. +* **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. +* **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. + +#### Parameter: `ConnectOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100. +* **timeout** `number | null` (optional) - Default `10e3` +* **servername** `string | null` (optional) +* **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled +* **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds + +### Example - Basic Client instantiation + +This will instantiate the undici Client, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`. + +```js +'use strict' +import { Client } from 'undici' + +const client = new Client('http://localhost:3000') +``` + +### Example - Custom connector + +This will allow you to perform some additional check on the socket that will be used for the next request. + +```js +'use strict' +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +## Instance Methods + +### `Client.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Client.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). + +### `Client.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Client.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Client.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Client.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Client.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Client.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Properties + +### `Client.closed` + +* `boolean` + +`true` after `client.close()` has been called. + +### `Client.destroyed` + +* `boolean` + +`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. + +### `Client.pipelining` + +* `number` + +Property to get and set the pipelining factor. + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +Emitted when a socket has been created and connected. The client will connect once `client.size > 0`. + +#### Example - Client connect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('connect', (origin) => { + console.log(`Connected to ${origin}`) // should print before the request body statement +}) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf-8') + body.on('data', console.log) + client.close() + server.close() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`. + +#### Example - Client disconnect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.destroy() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('disconnect', (origin) => { + console.log(`Disconnected from ${origin}`) +}) + +try { + await client.request({ + path: '/', + method: 'GET' + }) +} catch (error) { + console.error(error.message) + client.close() + server.close() +} +``` + +### Event: `'drain'` + +Emitted when pipeline is no longer busy. + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). + +#### Example - Client drain event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('drain', () => { + console.log('drain event') + client.close() + server.close() +}) + +const requests = [ + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }) +] + +await Promise.all(requests) + +console.log('requests completed') +``` + +### Event: `'error'` + +Invoked for users errors such as throwing in the `onError` handler. diff --git a/node_modules/undici/docs/api/Connector.md b/node_modules/undici/docs/api/Connector.md new file mode 100644 index 0000000..7c96650 --- /dev/null +++ b/node_modules/undici/docs/api/Connector.md @@ -0,0 +1,115 @@ +# Connector + +Undici creates the underlying socket via the connector builder. +Normally, this happens automatically and you don't need to care about this, +but if you need to perform some additional check over the currently used socket, +this is the right place. + +If you want to create a custom connector, you must import the `buildConnector` utility. + +#### Parameter: `buildConnector.BuildOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100. +* **timeout** `number | null` (optional) - Default `10e3` +* **servername** `string | null` (optional) + +Once you call `buildConnector`, it will return a connector function, which takes the following parameters. + +#### Parameter: `connector.Options` + +* **hostname** `string` (required) +* **host** `string` (optional) +* **protocol** `string` (required) +* **port** `string` (required) +* **servername** `string` (optional) +* **localAddress** `string | null` (optional) Local address the socket should connect from. +* **httpSocket** `Socket` (optional) Establish secure connection on a given socket rather than creating a new socket. It can only be sent on TLS update. + +### Basic example + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +### Example: validate the CA fingerprint + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const caFingerprint = 'FO:OB:AR' +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) { + socket.destroy() + cb(new Error('Fingerprint does not match or malformed certificate')) + } else { + cb(null, socket) + } + }) + } +}) + +client.request({ + path: '/', + method: 'GET' +}, (err, data) => { + if (err) throw err + + const bufs = [] + data.body.on('data', (buf) => { + bufs.push(buf) + }) + data.body.on('end', () => { + console.log(Buffer.concat(bufs).toString('utf8')) + client.close() + }) +}) + +function getIssuerCertificate (socket) { + let certificate = socket.getPeerCertificate(true) + while (certificate && Object.keys(certificate).length > 0) { + // invalid certificate + if (certificate.issuerCertificate == null) { + return null + } + + // We have reached the root certificate. + // In case of self-signed certificates, `issuerCertificate` may be a circular reference. + if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) { + break + } + + // continue the loop + certificate = certificate.issuerCertificate + } + return certificate +} +``` diff --git a/node_modules/undici/docs/api/ContentType.md b/node_modules/undici/docs/api/ContentType.md new file mode 100644 index 0000000..2bcc9f7 --- /dev/null +++ b/node_modules/undici/docs/api/ContentType.md @@ -0,0 +1,57 @@ +# MIME Type Parsing + +## `MIMEType` interface + +* **type** `string` +* **subtype** `string` +* **parameters** `Map` +* **essence** `string` + +## `parseMIMEType(input)` + +Implements [parse a MIME type](https://mimesniff.spec.whatwg.org/#parse-a-mime-type). + +Parses a MIME type, returning its type, subtype, and any associated parameters. If the parser can't parse an input it returns the string literal `'failure'`. + +```js +import { parseMIMEType } from 'undici' + +parseMIMEType('text/html; charset=gbk') +// { +// type: 'text', +// subtype: 'html', +// parameters: Map(1) { 'charset' => 'gbk' }, +// essence: 'text/html' +// } +``` + +Arguments: + +* **input** `string` + +Returns: `MIMEType|'failure'` + +## `serializeAMimeType(input)` + +Implements [serialize a MIME type](https://mimesniff.spec.whatwg.org/#serialize-a-mime-type). + +Serializes a MIMEType object. + +```js +import { serializeAMimeType } from 'undici' + +serializeAMimeType({ + type: 'text', + subtype: 'html', + parameters: new Map([['charset', 'gbk']]), + essence: 'text/html' +}) +// text/html;charset=gbk + +``` + +Arguments: + +* **mimeType** `MIMEType` + +Returns: `string` diff --git a/node_modules/undici/docs/api/Cookies.md b/node_modules/undici/docs/api/Cookies.md new file mode 100644 index 0000000..0cad379 --- /dev/null +++ b/node_modules/undici/docs/api/Cookies.md @@ -0,0 +1,101 @@ +# Cookie Handling + +## `Cookie` interface + +* **name** `string` +* **value** `string` +* **expires** `Date|number` (optional) +* **maxAge** `number` (optional) +* **domain** `string` (optional) +* **path** `string` (optional) +* **secure** `boolean` (optional) +* **httpOnly** `boolean` (optional) +* **sameSite** `'String'|'Lax'|'None'` (optional) +* **unparsed** `string[]` (optional) Left over attributes that weren't parsed. + +## `deleteCookie(headers, name[, attributes])` + +Sets the expiry time of the cookie to the unix epoch, causing browsers to delete it when received. + +```js +import { deleteCookie, Headers } from 'undici' + +const headers = new Headers() +deleteCookie(headers, 'name') + +console.log(headers.get('set-cookie')) // name=; Expires=Thu, 01 Jan 1970 00:00:00 GMT +``` + +Arguments: + +* **headers** `Headers` +* **name** `string` +* **attributes** `{ path?: string, domain?: string }` (optional) + +Returns: `void` + +## `getCookies(headers)` + +Parses the `Cookie` header and returns a list of attributes and values. + +```js +import { getCookies, Headers } from 'undici' + +const headers = new Headers({ + cookie: 'get=cookies; and=attributes' +}) + +console.log(getCookies(headers)) // { get: 'cookies', and: 'attributes' } +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Record` + +## `getSetCookies(headers)` + +Parses all `Set-Cookie` headers. + +```js +import { getSetCookies, Headers } from 'undici' + +const headers = new Headers({ 'set-cookie': 'undici=getSetCookies; Secure' }) + +console.log(getSetCookies(headers)) +// [ +// { +// name: 'undici', +// value: 'getSetCookies', +// secure: true +// } +// ] + +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Cookie[]` + +## `setCookie(headers, cookie)` + +Appends a cookie to the `Set-Cookie` header. + +```js +import { setCookie, Headers } from 'undici' + +const headers = new Headers() +setCookie(headers, { name: 'undici', value: 'setCookie' }) + +console.log(headers.get('Set-Cookie')) // undici=setCookie +``` + +Arguments: + +* **headers** `Headers` +* **cookie** `Cookie` + +Returns: `void` diff --git a/node_modules/undici/docs/api/DiagnosticsChannel.md b/node_modules/undici/docs/api/DiagnosticsChannel.md new file mode 100644 index 0000000..0aa0b9a --- /dev/null +++ b/node_modules/undici/docs/api/DiagnosticsChannel.md @@ -0,0 +1,204 @@ +# Diagnostics Channel Support + +Stability: Experimental. + +Undici supports the [`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html) (currently available only on Node.js v16+). +It is the preferred way to instrument Undici and retrieve internal information. + +The channels available are the following. + +## `undici:request:create` + +This message is published when a new outgoing request is created. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:create').subscribe(({ request }) => { + console.log('origin', request.origin) + console.log('completed', request.completed) + console.log('method', request.method) + console.log('path', request.path) + console.log('headers') // raw text, e.g: 'bar: bar\r\n' + request.addHeader('hello', 'world') + console.log('headers', request.headers) // e.g. 'bar: bar\r\nhello: world\r\n' +}) +``` + +Note: a request is only loosely completed to a given socket. + + +## `undici:request:bodySent` + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodySent').subscribe(({ request }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:headers` + +This message is published after the response headers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:headers').subscribe(({ request, response }) => { + // request is the same object undici:request:create + console.log('statusCode', response.statusCode) + console.log(response.statusText) + // response.headers are buffers. + console.log(response.headers.map((x) => x.toString())) +}) +``` + +## `undici:request:trailers` + +This message is published after the response body and trailers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:trailers').subscribe(({ request, trailers }) => { + // request is the same object undici:request:create + console.log('completed', request.completed) + // trailers are buffers. + console.log(trailers.map((x) => x.toString())) +}) +``` + +## `undici:request:error` + +This message is published if the request is going to error, but it has not errored yet. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:error').subscribe(({ request, error }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:client:sendHeaders` + +This message is published right before the first byte of the request is written to the socket. + +*Note*: It will publish the exact headers that will be sent to the server in raw format. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(({ request, headers, socket }) => { + // request is the same object undici:request:create + console.log(`Full headers list ${headers.split('\r\n')}`); +}) +``` + +## `undici:client:beforeConnect` + +This message is published before creating a new connection for **any** request. +You can not assume that this event is related to any specific request. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(({ connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connected` + +This message is published after a connection is established. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connected').subscribe(({ socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connectError` + +This message is published if it did not succeed to create new connection + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connectError').subscribe(({ error, socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket + console.log(`Connect failed with ${error.message}`) +}) +``` + +## `undici:websocket:open` + +This message is published after the client has successfully connected to a server. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:open').subscribe(({ address, protocol, extensions }) => { + console.log(address) // address, family, and port + console.log(protocol) // negotiated subprotocols + console.log(extensions) // negotiated extensions +}) +``` + +## `undici:websocket:close` + +This message is published after the connection has closed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:close').subscribe(({ websocket, code, reason }) => { + console.log(websocket) // the WebSocket object + console.log(code) // the closing status code + console.log(reason) // the closing reason +}) +``` + +## `undici:websocket:socket_error` + +This message is published if the socket experiences an error. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:socket_error').subscribe((error) => { + console.log(error) +}) +``` + +## `undici:websocket:ping` + +This message is published after the client receives a ping frame, if the connection is not closing. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:ping').subscribe(({ payload }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) +}) +``` + +## `undici:websocket:pong` + +This message is published after the client receives a pong frame. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:pong').subscribe(({ payload }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) +}) +``` diff --git a/node_modules/undici/docs/api/DispatchInterceptor.md b/node_modules/undici/docs/api/DispatchInterceptor.md new file mode 100644 index 0000000..652b2e8 --- /dev/null +++ b/node_modules/undici/docs/api/DispatchInterceptor.md @@ -0,0 +1,60 @@ +#Interface: DispatchInterceptor + +Extends: `Function` + +A function that can be applied to the `Dispatcher.Dispatch` function before it is invoked with a dispatch request. + +This allows one to write logic to intercept both the outgoing request, and the incoming response. + +### Parameter: `Dispatcher.Dispatch` + +The base dispatch function you are decorating. + +### ReturnType: `Dispatcher.Dispatch` + +A dispatch function that has been altered to provide additional logic + +### Basic Example + +Here is an example of an interceptor being used to provide a JWT bearer token + +```js +'use strict' + +const insertHeaderInterceptor = dispatch => { + return function InterceptedDispatch(opts, handler){ + opts.headers.push('Authorization', 'Bearer [Some token]') + return dispatch(opts, handler) + } +} + +const client = new Client('https://localhost:3000', { + interceptors: { Client: [insertHeaderInterceptor] } +}) + +``` + +### Basic Example 2 + +Here is a contrived example of an interceptor stripping the headers from a response. + +```js +'use strict' + +const clearHeadersInterceptor = dispatch => { + const { DecoratorHandler } = require('undici') + class ResultInterceptor extends DecoratorHandler { + onHeaders (statusCode, headers, resume) { + return super.onHeaders(statusCode, [], resume) + } + } + return function InterceptedDispatch(opts, handler){ + return dispatch(opts, new ResultInterceptor(handler)) + } +} + +const client = new Client('https://localhost:3000', { + interceptors: { Client: [clearHeadersInterceptor] } +}) + +``` diff --git a/node_modules/undici/docs/api/Dispatcher.md b/node_modules/undici/docs/api/Dispatcher.md new file mode 100644 index 0000000..a506429 --- /dev/null +++ b/node_modules/undici/docs/api/Dispatcher.md @@ -0,0 +1,886 @@ +# Dispatcher + +Extends: `events.EventEmitter` + +Dispatcher is the core API used to dispatch requests. + +Requests are not guaranteed to be dispatched in order of invocation. + +## Instance Methods + +### `Dispatcher.close([callback]): Promise` + +Closes the dispatcher and gracefully waits for enqueued requests to complete before resolving. + +Arguments: + +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.close() // -> Promise +dispatcher.close(() => {}) // -> void +``` + +#### Example - Request resolves before Client closes + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('undici') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf8') + body.on('data', console.log) +} catch (error) {} + +await client.close() + +console.log('Client closed') +server.close() +``` + +### `Dispatcher.connect(options[, callback])` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **options** `ConnectOptions` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `ConnectOptions` + +* **path** `string` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null` +* **opaque** `unknown` (optional) - This argument parameter is passed through to `ConnectData` + +#### Parameter: `ConnectData` + +* **statusCode** `number` +* **headers** `Record` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example - Connect request with echo + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + throw Error('should never get here') +}).listen() + +server.on('connect', (req, socket, head) => { + socket.write('HTTP/1.1 200 Connection established\r\n\r\n') + + let data = head.toString() + socket.on('data', (buf) => { + data += buf.toString() + }) + + socket.on('end', () => { + socket.end(data) + }) +}) + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { socket } = await client.connect({ + path: '/' + }) + const wanted = 'Body' + let data = '' + socket.on('data', d => { data += d }) + socket.on('end', () => { + console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) + client.close() + server.close() + }) + socket.write(wanted) + socket.end() +} catch (error) { } +``` + +### `Dispatcher.destroy([error, callback]): Promise` + +Destroy the dispatcher abruptly with the given error. All the pending and running requests will be asynchronously aborted and error. Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. + +Both arguments are optional; the method can be called in four different ways: + +Arguments: + +* **error** `Error | null` (optional) +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.destroy() // -> Promise +dispatcher.destroy(new Error()) // -> Promise +dispatcher.destroy(() => {}) // -> void +dispatcher.destroy(new Error(), () => {}) // -> void +``` + +#### Example - Request is aborted when Client is destroyed + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const request = client.request({ + path: '/', + method: 'GET' + }) + client.destroy() + .then(() => { + console.log('Client destroyed') + server.close() + }) + await request +} catch (error) { + console.error(error) +} +``` + +### `Dispatcher.dispatch(options, handler)` + +This is the low level API which all the preceding APIs are implemented on top of. +This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. +It is primarily intended for library developers who implement higher level APIs on top of this. + +Arguments: + +* **options** `DispatchOptions` +* **handler** `DispatchHandler` + +Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls won't make any progress until the `'drain'` event has been emitted. + +#### Parameter: `DispatchOptions` + +* **origin** `string | URL` +* **path** `string` +* **method** `string` +* **reset** `boolean` (optional) - Default: `false` - If `false`, the request will attempt to create a long-living connection by sending the `connection: keep-alive` header,otherwise will attempt to close it immediately after response by sending `connection: close` within the request and closing the socket afterwards. +* **body** `string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null` (optional) - Default: `null` +* **headers** `UndiciHeaders | string[]` (optional) - Default: `null`. +* **query** `Record | null` (optional) - Default: `null` - Query string params to be embedded in the request URL. Note that both keys and values of query are encoded using `encodeURIComponent`. If for some reason you need to send them unencoded, embed query params into path directly instead. +* **idempotent** `boolean` (optional) - Default: `true` if `method` is `'HEAD'` or `'GET'` - Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline has completed. +* **blocking** `boolean` (optional) - Default: `false` - Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. +* **upgrade** `string | null` (optional) - Default: `null` - Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. +* **bodyTimeout** `number | null` (optional) - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - The amount of time the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **throwOnError** `boolean` (optional) - Default: `false` - Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. + +#### Parameter: `DispatchHandler` + +* **onConnect** `(abort: () => void, context: object) => void` - Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. +* **onError** `(error: Error) => void` - Invoked when an error has occurred. May not throw. +* **onUpgrade** `(statusCode: number, headers: Buffer[], socket: Duplex) => void` (optional) - Invoked when request is upgraded. Required if `DispatchOptions.upgrade` is defined or `DispatchOptions.method === 'CONNECT'`. +* **onHeaders** `(statusCode: number, headers: Buffer[], resume: () => void, statusText: string) => boolean` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests. +* **onData** `(chunk: Buffer) => boolean` - Invoked when response payload data is received. Not required for `upgrade` requests. +* **onComplete** `(trailers: Buffer[]) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests. +* **onBodySent** `(chunk: string | Buffer | Uint8Array) => void` - Invoked when a body chunk is sent to the server. Not required. For a stream or iterable body this will be invoked for every chunk. For other body types, it will be invoked once after the body is sent. + +#### Example 1 - Dispatch GET request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'GET', + headers: { + 'x-foo': 'bar' + } +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Data: ${res}`) + client.close() + server.close() + } +}) +``` + +#### Example 2 - Dispatch Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +server.on('upgrade', (request, socket, head) => { + console.log('Node.js Server - upgrade event') + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n') + socket.write('Upgrade: WebSocket\r\n') + socket.write('Connection: Upgrade\r\n') + socket.write('\r\n') + socket.end() +}) + +const client = new Client(`http://localhost:${server.address().port}`) + +client.dispatch({ + path: '/', + method: 'GET', + upgrade: 'websocket' +}, { + onConnect: () => { + console.log('Undici Client - onConnect') + }, + onError: (error) => { + console.log('onError') // shouldn't print + }, + onUpgrade: (statusCode, headers, socket) => { + console.log('Undici Client - onUpgrade') + console.log(`onUpgrade Headers: ${headers}`) + socket.on('data', buffer => { + console.log(buffer.toString('utf8')) + }) + socket.on('end', () => { + client.close() + server.close() + }) + socket.end() + } +}) +``` + +#### Example 3 - Dispatch POST request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.on('data', (data) => { + console.log(`Request Data: ${data.toString('utf8')}`) + const body = JSON.parse(data) + body.message = 'World' + response.end(JSON.stringify(body)) + }) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify({ message: 'Hello' }) +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Response Data: ${res}`) + client.close() + server.close() + } +}) +``` + +### `Dispatcher.pipeline(options, handler)` + +For easy use with [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback). The `handler` argument should return a `Readable` from which the result will be read. Usually it should just return the `body` argument unless some kind of transformation needs to be performed based on e.g. `headers` or `statusCode`. The `handler` should validate the response and save any required state. If there is an error, it should be thrown. The function returns a `Duplex` which writes to the request and reads from the response. + +Arguments: + +* **options** `PipelineOptions` +* **handler** `(data: PipelineHandlerData) => stream.Readable` + +Returns: `stream.Duplex` + +#### Parameter: PipelineOptions + +Extends: [`RequestOptions`](#parameter-requestoptions) + +* **objectMode** `boolean` (optional) - Default: `false` - Set to `true` if the `handler` will return an object stream. + +#### Parameter: PipelineHandlerData + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **body** `stream.Readable` +* **context** `object` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Example 1 - Pipeline Echo + +```js +import { Readable, Writable, PassThrough, pipeline } from 'stream' +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.pipe(response) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +let res = '' + +pipeline( + new Readable({ + read () { + this.push(Buffer.from('undici')) + this.push(null) + } + }), + client.pipeline({ + path: '/', + method: 'GET' + }, ({ statusCode, headers, body }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return pipeline(body, new PassThrough(), () => {}) + }), + new Writable({ + write (chunk, _, callback) { + res += chunk.toString() + callback() + }, + final (callback) { + console.log(`Response pipelined to writable: ${res}`) + callback() + } + }), + error => { + if (error) { + console.error(error) + } + + client.close() + server.close() + } +) +``` + +### `Dispatcher.request(options[, callback])` + +Performs a HTTP request. + +Non-idempotent requests will not be pipelined in order +to avoid indirect failures. + +Idempotent requests will be automatically retried if +they fail due to indirect failure from the request +at the head of the pipeline. This does not apply to +idempotent requests with a stream request body. + +All response bodies must always be fully consumed or destroyed. + +Arguments: + +* **options** `RequestOptions` +* **callback** `(error: Error | null, data: ResponseData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed. + +#### Parameter: `RequestOptions` + +Extends: [`DispatchOptions`](#parameter-dispatchoptions) + +* **opaque** `unknown` (optional) - Default: `null` - Used for passing through context to `ResponseData`. +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null`. +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +The `RequestOptions.method` property should not be value `'CONNECT'`. + +#### Parameter: `ResponseData` + +* **statusCode** `number` +* **headers** `Record` - Note that all header keys are lower-cased, e. g. `content-type`. +* **body** `stream.Readable` which also implements [the body mixin from the Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). +* **trailers** `Record` - This object starts out + as empty and will be mutated to contain trailers after `body` has emitted `'end'`. +* **opaque** `unknown` +* **context** `object` + +`body` contains the following additional [body mixin](https://fetch.spec.whatwg.org/#body-mixin) methods and properties: + +- `text()` +- `json()` +- `arrayBuffer()` +- `body` +- `bodyUsed` + +`body` can not be consumed twice. For example, calling `text()` after `json()` throws `TypeError`. + +`body` contains the following additional extensions: + +- `dump({ limit: Integer })`, dump the response by reading up to `limit` bytes without killing the socket (optional) - Default: 262144. + +Note that body will still be a `Readable` even if it is empty, but attempting to deserialize it with `json()` will result in an exception. Recommended way to ensure there is a body to deserialize is to check if status code is not 204, and `content-type` header starts with `application/json`. + +#### Example 1 - Basic GET Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body, headers, statusCode, trailers } = await client.request({ + path: '/', + method: 'GET' + }) + console.log(`response received ${statusCode}`) + console.log('headers', headers) + body.setEncoding('utf8') + body.on('data', console.log) + body.on('end', () => { + console.log('trailers', trailers) + }) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Aborting a request + +> Node.js v15+ is required to run this example + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const abortController = new AbortController() + +try { + client.request({ + path: '/', + method: 'GET', + signal: abortController.signal + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +abortController.abort() +``` + +Alternatively, any `EventEmitter` that emits an `'abort'` event may be used as an abort controller: + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import EventEmitter, { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const ee = new EventEmitter() + +try { + client.request({ + path: '/', + method: 'GET', + signal: ee + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +ee.emit('abort') +``` + +Destroying the request or response body will have the same effect. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.destroy() +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} +``` + +### `Dispatcher.stream(options, factory[, callback])` + +A faster version of `Dispatcher.request`. This method expects the second argument `factory` to return a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream which the response will be written to. This improves performance by avoiding creating an intermediate [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams) stream when the user expects to directly pipe the response body to a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream. + +As demonstrated in [Example 1 - Basic GET stream request](#example-1---basic-get-stream-request), it is recommended to use the `option.opaque` property to avoid creating a closure for the `factory` method. This pattern works well with Node.js Web Frameworks such as [Fastify](https://fastify.io). See [Example 2 - Stream to Fastify Response](#example-2---stream-to-fastify-response) for more details. + +Arguments: + +* **options** `RequestOptions` +* **factory** `(data: StreamFactoryData) => stream.Writable` +* **callback** `(error: Error | null, data: StreamData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `StreamFactoryData` + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Parameter: `StreamData` + +* **opaque** `unknown` +* **trailers** `Record` +* **context** `object` + +#### Example 1 - Basic GET stream request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import { Writable } from 'stream' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const bufs = [] + +try { + await client.stream({ + path: '/', + method: 'GET', + opaque: { bufs } + }, ({ statusCode, headers, opaque: { bufs } }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return new Writable({ + write (chunk, encoding, callback) { + bufs.push(chunk) + callback() + } + }) + }) + + console.log(Buffer.concat(bufs).toString('utf-8')) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Stream to Fastify Response + +In this example, a (fake) request is made to the fastify server using `fastify.inject()`. This request then executes the fastify route handler which makes a subsequent request to the raw Node.js http server using `undici.dispatcher.stream()`. The fastify response is passed to the `opaque` option so that undici can tap into the underlying writable stream using `response.raw`. This methodology demonstrates how one could use undici and fastify together to create fast-as-possible requests from one backend server to another. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import fastify from 'fastify' + +const nodeServer = createServer((request, response) => { + response.end('Hello, World! From Node.js HTTP Server') +}).listen() + +await once(nodeServer, 'listening') + +console.log('Node Server listening') + +const nodeServerUndiciClient = new Client(`http://localhost:${nodeServer.address().port}`) + +const fastifyServer = fastify() + +fastifyServer.route({ + url: '/', + method: 'GET', + handler: (request, response) => { + nodeServerUndiciClient.stream({ + path: '/', + method: 'GET', + opaque: response + }, ({ opaque }) => opaque.raw) + } +}) + +await fastifyServer.listen() + +console.log('Fastify Server listening') + +const fastifyServerUndiciClient = new Client(`http://localhost:${fastifyServer.server.address().port}`) + +try { + const { statusCode, body } = await fastifyServerUndiciClient.request({ + path: '/', + method: 'GET' + }) + + console.log(`response received ${statusCode}`) + body.setEncoding('utf8') + body.on('data', console.log) + + nodeServerUndiciClient.close() + fastifyServerUndiciClient.close() + fastifyServer.close() + nodeServer.close() +} catch (error) { } +``` + +### `Dispatcher.upgrade(options[, callback])` + +Upgrade to a different protocol. Visit [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **options** `UpgradeOptions` + +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `UpgradeOptions` + +* **path** `string` +* **method** `string` (optional) - Default: `'GET'` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **protocol** `string` (optional) - Default: `'Websocket'` - A string of comma separated protocols, in descending preference order. +* **signal** `AbortSignal | EventEmitter | null` (optional) - Default: `null` + +#### Parameter: `UpgradeData` + +* **headers** `http.IncomingHeaders` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example 1 - Basic Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.statusCode = 101 + response.setHeader('connection', 'upgrade') + response.setHeader('upgrade', request.headers.upgrade) + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { headers, socket } = await client.upgrade({ + path: '/', + }) + socket.on('end', () => { + console.log(`upgrade: ${headers.upgrade}`) // upgrade: Websocket + client.close() + server.close() + }) + socket.end() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +## Instance Events + +### Event: `'connect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +### Event: `'disconnect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +### Event: `'connectionError'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when dispatcher fails to connect to +origin. + +### Event: `'drain'` + +Parameters: + +* **origin** `URL` + +Emitted when dispatcher is no longer busy. + +## Parameter: `UndiciHeaders` + +* `Record | string[] | null` + +Header arguments such as `options.headers` in [`Client.dispatch`](Client.md#clientdispatchoptions-handlers) can be specified in two forms; either as an object specified by the `Record` (`IncomingHttpHeaders`) type, or an array of strings. An array representation of a header list must have an even length or an `InvalidArgumentError` will be thrown. + +Keys are lowercase and values are not modified. + +Response headers will derive a `host` from the `url` of the [Client](Client.md#class-client) instance if no `host` header was previously specified. + +### Example 1 - Object + +```js +{ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +} +``` + +### Example 2 - Array + +```js +[ + 'content-length', '123', + 'content-type', 'text/plain', + 'connection', 'keep-alive', + 'host', 'mysite.com', + 'accept', '*/*' +] +``` diff --git a/node_modules/undici/docs/api/Errors.md b/node_modules/undici/docs/api/Errors.md new file mode 100644 index 0000000..fba0e8c --- /dev/null +++ b/node_modules/undici/docs/api/Errors.md @@ -0,0 +1,41 @@ +# Errors + +Undici exposes a variety of error objects that you can use to enhance your error handling. +You can find all the error objects inside the `errors` key. + +```js +import { errors } from 'undici' +``` + +| Error | Error Codes | Description | +| ------------------------------------ | ------------------------------------- | -------------------------------------------------- | +| `InvalidArgumentError` | `UND_ERR_INVALID_ARG` | passed an invalid argument. | +| `InvalidReturnValueError` | `UND_ERR_INVALID_RETURN_VALUE` | returned an invalid value. | +| `RequestAbortedError` | `UND_ERR_ABORTED` | the request has been aborted by the user | +| `ClientDestroyedError` | `UND_ERR_DESTROYED` | trying to use a destroyed client. | +| `ClientClosedError` | `UND_ERR_CLOSED` | trying to use a closed client. | +| `SocketError` | `UND_ERR_SOCKET` | there is an error with the socket. | +| `NotSupportedError` | `UND_ERR_NOT_SUPPORTED` | encountered unsupported functionality. | +| `RequestContentLengthMismatchError` | `UND_ERR_REQ_CONTENT_LENGTH_MISMATCH` | request body does not match content-length header | +| `ResponseContentLengthMismatchError` | `UND_ERR_RES_CONTENT_LENGTH_MISMATCH` | response body does not match content-length header | +| `InformationalError` | `UND_ERR_INFO` | expected error with reason | +| `ResponseExceededMaxSizeError` | `UND_ERR_RES_EXCEEDED_MAX_SIZE` | response body exceed the max size allowed | + +### `SocketError` + +The `SocketError` has a `.socket` property which holds socket metadata: + +```ts +interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number +} +``` + +Be aware that in some cases the `.socket` property can be `null`. diff --git a/node_modules/undici/docs/api/Fetch.md b/node_modules/undici/docs/api/Fetch.md new file mode 100644 index 0000000..0a5c3d0 --- /dev/null +++ b/node_modules/undici/docs/api/Fetch.md @@ -0,0 +1,25 @@ +# Fetch + +Undici exposes a fetch() method starts the process of fetching a resource from the network. + +Documentation and examples can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch). + +## File + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/File) + +## FormData + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FormData) + +## Response + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response) + +## Request + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request) + +## Header + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Headers) diff --git a/node_modules/undici/docs/api/MockAgent.md b/node_modules/undici/docs/api/MockAgent.md new file mode 100644 index 0000000..85ae690 --- /dev/null +++ b/node_modules/undici/docs/api/MockAgent.md @@ -0,0 +1,540 @@ +# Class: MockAgent + +Extends: `undici.Dispatcher` + +A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. + +## `new MockAgent([options])` + +Arguments: + +* **options** `MockAgentOptions` (optional) - It extends the `Agent` options. + +Returns: `MockAgent` + +### Parameter: `MockAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **agent** `Agent` (optional) - Default: `new Agent([options])` - a custom agent encapsulated by the MockAgent. + +### Example - Basic MockAgent instantiation + +This will instantiate the MockAgent. It will not do anything until registered as the agent to use with requests and mock interceptions are added. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +``` + +### Example - Basic MockAgent instantiation with custom agent + +```js +import { Agent, MockAgent } from 'undici' + +const agent = new Agent() + +const mockAgent = new MockAgent({ agent }) +``` + +## Instance Methods + +### `MockAgent.get(origin)` + +This method creates and retrieves MockPool or MockClient instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. + +For subsequent `MockAgent.get` calls on the same origin, the same mock instance will be returned. + +Arguments: + +* **origin** `string | RegExp | (value) => boolean` - a matcher for the pool origin to be retrieved from the MockAgent. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Returns: `MockClient | MockPool`. + +| `MockAgentOptions` | Mock instance returned | +| -------------------- | ---------------------- | +| `connections === 1` | `MockClient` | +| `connections` > `1` | `MockPool` | + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock agent dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock pool dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockPool }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock client dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockClient }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') +mockPool.intercept({ path: '/hello'}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` +#### Example - Mock different requests within the same file +```js +const { MockAgent, setGlobalDispatcher } = require('undici'); +const agent = new MockAgent(); +agent.disableNetConnect(); +setGlobalDispatcher(agent); +describe('Test', () => { + it('200', async () => { + const mockAgent = agent.get('http://test.com'); + // your test + }); + it('200', async () => { + const mockAgent = agent.get('http://testing.com'); + // your test + }); +}); +``` + +#### Example - Mocked request with query body, headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2' +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2' +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request with origin regex + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get(new RegExp('http://localhost:3000')) +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with origin function + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get((origin) => origin === 'http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.close()` + +Closes the mock agent and waits for registered mock pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +await mockAgent.close() +``` + +### `MockAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](Agent.md#parameter-agentdispatchoptions). + +### `MockAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockAgent request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockAgent.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.deactivate()` + +This method disables mocking in MockAgent. + +Returns: `void` + +#### Example - Deactivate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +``` + +### `MockAgent.activate()` + +This method enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. + +Returns: `void` + +#### Example - Activate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +// No mocking will occur + +// Later +mockAgent.activate() +``` + +### `MockAgent.enableNetConnect([host])` + +When requests are not matched in a MockAgent intercept, a real HTTP request is attempted. We can control this further through the use of `enableNetConnect`. This is achieved by defining host matchers so only matching requests will be attempted. + +When using a string, it should only include the **hostname and optionally, the port**. In addition, calling this method multiple times with a string will allow all HTTP requests that match these values. + +Arguments: + +* **host** `string | RegExp | (value) => boolean` - (optional) + +Returns: `void` + +#### Example - Allow all non-matching urls to be dispatched in a real HTTP request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect() + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host string to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect('example-1.com') +mockAgent.enableNetConnect('example-2.com:8080') + +await request('http://example-1.com') +// A real request is made + +await request('http://example-2.com:8080') +// A real request is made + +await request('http://example-3.com') +// Will throw +``` + +#### Example - Allow requests matching a host regex to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect(new RegExp('example.com')) + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host function to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect((value) => value === 'example.com') + +await request('http://example.com') +// A real request is made +``` + +### `MockAgent.disableNetConnect()` + +This method causes all requests to throw when requests are not matched in a MockAgent intercept. + +Returns: `void` + +#### Example - Disable all non-matching requests by throwing an error for each + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +mockAgent.disableNetConnect() + +await request('http://example.com') +// Will throw +``` + +### `MockAgent.pendingInterceptors()` + +This method returns any pending interceptors registered on a mock agent. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +Returns: `PendingInterceptor[]` (where `PendingInterceptor` is a `MockDispatch` with an additional `origin: string`) + +#### Example - List all pending inteceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +const pendingInterceptors = agent.pendingInterceptors() +// Returns [ +// { +// timesInvoked: 0, +// times: 1, +// persist: false, +// consumed: false, +// pending: true, +// path: '/', +// method: 'GET', +// body: undefined, +// headers: undefined, +// data: { +// error: null, +// statusCode: 200, +// data: '', +// headers: {}, +// trailers: {} +// }, +// origin: 'https://example.com' +// } +// ] +``` + +### `MockAgent.assertNoPendingInterceptors([options])` + +This method throws if the mock agent has any pending interceptors. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +#### Example - Check that there are no pending interceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +agent.assertNoPendingInterceptors() +// Throws an UndiciError with the following message: +// +// 1 interceptor is pending: +// +// ┌─────────┬────────┬───────────────────────┬──────┬─────────────┬────────────┬─────────────┬───────────┐ +// │ (index) │ Method │ Origin │ Path │ Status code │ Persistent │ Invocations │ Remaining │ +// ├─────────┼────────┼───────────────────────┼──────┼─────────────┼────────────┼─────────────┼───────────┤ +// │ 0 │ 'GET' │ 'https://example.com' │ '/' │ 200 │ '❌' │ 0 │ 1 │ +// └─────────┴────────┴───────────────────────┴──────┴─────────────┴────────────┴─────────────┴───────────┘ +``` diff --git a/node_modules/undici/docs/api/MockClient.md b/node_modules/undici/docs/api/MockClient.md new file mode 100644 index 0000000..ac54691 --- /dev/null +++ b/node_modules/undici/docs/api/MockClient.md @@ -0,0 +1,77 @@ +# Class: MockClient + +Extends: `undici.Client` + +A mock client class that implements the same api as [MockPool](MockPool.md). + +## `new MockClient(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockClientOptions` - It extends the `Client` options. + +Returns: `MockClient` + +### Parameter: `MockClientOptions` + +Extends: `ClientOptions` + +* **agent** `Agent` - the agent to associate this MockClient with. + +### Example - Basic MockClient instantiation + +We can use MockAgent to instantiate a MockClient ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +// Connections must be set to 1 to return a MockClient instance +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockClient.intercept(options)` + +Implements: [`MockPool.intercept(options)`](MockPool.md#mockpoolinterceptoptions) + +### `MockClient.close()` + +Implements: [`MockPool.close()`](MockPool.md#mockpoolclose) + +### `MockClient.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockClient.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockClient request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockClient.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/api/MockErrors.md b/node_modules/undici/docs/api/MockErrors.md new file mode 100644 index 0000000..c1aa3db --- /dev/null +++ b/node_modules/undici/docs/api/MockErrors.md @@ -0,0 +1,12 @@ +# MockErrors + +Undici exposes a variety of mock error objects that you can use to enhance your mock error handling. +You can find all the mock error objects inside the `mockErrors` key. + +```js +import { mockErrors } from 'undici' +``` + +| Mock Error | Mock Error Codes | Description | +| --------------------- | ------------------------------- | ---------------------------------------------------------- | +| `MockNotMatchedError` | `UND_MOCK_ERR_MOCK_NOT_MATCHED` | The request does not match any registered mock dispatches. | diff --git a/node_modules/undici/docs/api/MockPool.md b/node_modules/undici/docs/api/MockPool.md new file mode 100644 index 0000000..923c157 --- /dev/null +++ b/node_modules/undici/docs/api/MockPool.md @@ -0,0 +1,512 @@ +# Class: MockPool + +Extends: `undici.Pool` + +A mock Pool class that implements the Pool API and is used by MockAgent to intercept real requests and return mocked responses. + +## `new MockPool(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockPoolOptions` - It extends the `Pool` options. + +Returns: `MockPool` + +### Parameter: `MockPoolOptions` + +Extends: `PoolOptions` + +* **agent** `Agent` - the agent to associate this MockPool with. + +### Example - Basic MockPool instantiation + +We can use MockAgent to instantiate a MockPool ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockPool.intercept(options)` + +This method defines the interception rules for matching against requests for a MockPool or MockPool. We can intercept multiple times on a single instance. + +When defining interception rules, all the rules must pass for a request to be intercepted. If a request is not intercepted, a real request will be attempted. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Arguments: + +* **options** `MockPoolInterceptOptions` - Interception options. + +Returns: `MockInterceptor` corresponding to the input options. + +### Parameter: `MockPoolInterceptOptions` + +* **path** `string | RegExp | (path: string) => boolean` - a matcher for the HTTP request path. +* **method** `string | RegExp | (method: string) => boolean` - (optional) - a matcher for the HTTP request method. Defaults to `GET`. +* **body** `string | RegExp | (body: string) => boolean` - (optional) - a matcher for the HTTP request body. +* **headers** `Record boolean`> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way. +* **query** `Record | null` - (optional) - a matcher for the HTTP request query string params. + +### Return: `MockInterceptor` + +We can define the behaviour of an intercepted request with the following options. + +* **reply** `(statusCode: number, replyData: string | Buffer | object | MockInterceptor.MockResponseDataHandler, responseOptions?: MockResponseOptions) => MockScope` - define a reply for a matching request. You can define the replyData as a callback to read incoming request data. Default for `responseOptions` is `{}`. +* **reply** `(callback: MockInterceptor.MockReplyOptionsCallback) => MockScope` - define a reply for a matching request, allowing dynamic mocking of all reply options rather than just the data. +* **replyWithError** `(error: Error) => MockScope` - define an error for a matching request to throw. +* **defaultReplyHeaders** `(headers: Record) => MockInterceptor` - define default headers to be included in subsequent replies. These are in addition to headers on a specific reply. +* **defaultReplyTrailers** `(trailers: Record) => MockInterceptor` - define default trailers to be included in subsequent replies. These are in addition to trailers on a specific reply. +* **replyContentLength** `() => MockInterceptor` - define automatically calculated `content-length` headers to be included in subsequent replies. + +The reply data of an intercepted request may either be a string, buffer, or JavaScript object. Objects are converted to JSON while strings and buffers are sent as-is. + +By default, `reply` and `replyWithError` define the behaviour for the first matching request only. Subsequent requests will not be affected (this can be changed using the returned `MockScope`). + +### Parameter: `MockResponseOptions` + +* **headers** `Record` - headers to be included on the mocked reply. +* **trailers** `Record` - trailers to be included on the mocked reply. + +### Return: `MockScope` + +A `MockScope` is associated with a single `MockInterceptor`. With this, we can configure the default behaviour of a intercepted reply. + +* **delay** `(waitInMs: number) => MockScope` - delay the associated reply by a set amount in ms. +* **persist** `() => MockScope` - any matching request will always reply with the defined response indefinitely. +* **times** `(repeatTimes: number) => MockScope` - any matching request will reply with the defined response a fixed amount of times. This is overridden by **persist**. + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +// MockPool +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request using reply data callbacks + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, ({ headers }) => ({ message: headers.get('message') })) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Mocked request using reply options callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(({ headers }) => ({ statusCode: 200, data: { message: headers.get('message') }}))) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo') + +mockPool.intercept({ + path: '/hello', + method: 'GET', +}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` + +#### Example - Mocked request with query body, request headers and response headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } + }) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request using different matchers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: /^GET$/, + body: (value) => value === 'form=data', + headers: { + 'User-Agent': 'undici', + Host: /^example.com$/ + } +}).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { + method: 'GET', + body: 'form=data', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with reply with a defined error + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyWithError(new Error('kaboom')) + +try { + await request('http://localhost:3000/foo', { + method: 'GET' + }) +} catch (error) { + console.error(error) // Error: kaboom +} +``` + +#### Example - Mocked request with defaultReplyHeaders + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyHeaders({ foo: 'bar' }) + .reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { foo: 'bar' } +``` + +#### Example - Mocked request with defaultReplyTrailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyTrailers({ foo: 'bar' }) + .reply(200, 'foo') + +const { trailers } = await request('http://localhost:3000/foo') + +console.log('trailers', trailers) // trailers { foo: 'bar' } +``` + +#### Example - Mocked request with automatic content-length calculation + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '3' } +``` + +#### Example - Mocked request with automatic content-length calculation on an object + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, { foo: 'bar' }) + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '13' } +``` + +#### Example - Mocked request with persist enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').persist() + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +// Etc +``` + +#### Example - Mocked request with times enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').times(2) + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result3 = await request('http://localhost:3000/foo') +// Will not match and make attempt a real request +``` + +### `MockPool.close()` + +Closes the mock pool and de-registers from associated MockAgent. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +const mockPool = mockAgent.get('http://localhost:3000') + +await mockPool.close() +``` + +### `MockPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockPool request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ + path: '/foo', + method: 'GET', +}).reply(200, 'foo') + +const { + statusCode, + body +} = await mockPool.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/api/Pool.md b/node_modules/undici/docs/api/Pool.md new file mode 100644 index 0000000..8fcabac --- /dev/null +++ b/node_modules/undici/docs/api/Pool.md @@ -0,0 +1,84 @@ +# Class: Pool + +Extends: `undici.Dispatcher` + +A pool of [Client](Client.md) instances connected to the same upstream target. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Pool(url[, options])` + +Arguments: + +* **url** `URL | string` - It should only include the **protocol, hostname, and port**. +* **options** `PoolOptions` (optional) + +### Parameter: `PoolOptions` + +Extends: [`ClientOptions`](Client.md#parameter-clientoptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)` +* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `Pool` instance will create an unlimited amount of `Client` instances. +* **interceptors** `{ Pool: DispatchInterceptor[] } }` - Default: `{ Pool: [] }` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). + +## Instance Properties + +### `Pool.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `Pool.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `Pool.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Pool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Pool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Pool.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Pool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Pool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Pool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Pool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/api/PoolStats.md b/node_modules/undici/docs/api/PoolStats.md new file mode 100644 index 0000000..16b6dc2 --- /dev/null +++ b/node_modules/undici/docs/api/PoolStats.md @@ -0,0 +1,35 @@ +# Class: PoolStats + +Aggregate stats for a [Pool](Pool.md) or [BalancedPool](BalancedPool.md). + +## `new PoolStats(pool)` + +Arguments: + +* **pool** `Pool` - Pool or BalancedPool from which to return stats. + +## Instance Properties + +### `PoolStats.connected` + +Number of open socket connections in this pool. + +### `PoolStats.free` + +Number of open socket connections in this pool that do not have an active request. + +### `PoolStats.pending` + +Number of pending requests across all clients in this pool. + +### `PoolStats.queued` + +Number of queued requests across all clients in this pool. + +### `PoolStats.running` + +Number of currently active requests across all clients in this pool. + +### `PoolStats.size` + +Number of active, pending, or queued requests across all clients in this pool. diff --git a/node_modules/undici/docs/api/ProxyAgent.md b/node_modules/undici/docs/api/ProxyAgent.md new file mode 100644 index 0000000..6a8b07f --- /dev/null +++ b/node_modules/undici/docs/api/ProxyAgent.md @@ -0,0 +1,124 @@ +# Class: ProxyAgent + +Extends: `undici.Dispatcher` + +A Proxy Agent class that implements the Agent API. It allows the connection through proxy in a simple way. + +## `new ProxyAgent([options])` + +Arguments: + +* **options** `ProxyAgentOptions` (required) - It extends the `Agent` options. + +Returns: `ProxyAgent` + +### Parameter: `ProxyAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **uri** `string` (required) - It can be passed either by a string or a object containing `uri` as string. +* **token** `string` (optional) - It can be passed by a string of token for authentication. +* **auth** `string` (**deprecated**) - Use token. +* **clientFactory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` + +Examples: + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +// or +const proxyAgent = new ProxyAgent({ uri: 'my.proxy.server' }) +``` + +#### Example - Basic ProxyAgent instantiation + +This will instantiate the ProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { ProxyAgent, request } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: proxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with authentication + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici'; + +const proxyAgent = new ProxyAgent({ + uri: 'my.proxy.server', + // token: 'Bearer xxxx' + token: `Basic ${Buffer.from('username:password').toString('base64')}` +}); +setGlobalDispatcher(proxyAgent); + +const { statusCode, body } = await request('http://localhost:3000/foo'); + +console.log('response received', statusCode); // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')); // data foo +} +``` + +### `ProxyAgent.close()` + +Closes the proxy agent and waits for registered pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { ProxyAgent, setGlobalDispatcher } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +await proxyAgent.close() +``` + +### `ProxyAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](Agent.md#parameter-agentdispatchoptions). + +### `ProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). diff --git a/node_modules/undici/docs/api/WebSocket.md b/node_modules/undici/docs/api/WebSocket.md new file mode 100644 index 0000000..639a533 --- /dev/null +++ b/node_modules/undici/docs/api/WebSocket.md @@ -0,0 +1,20 @@ +# Class: WebSocket + +> ⚠️ Warning: the WebSocket API is experimental and has known bugs. + +Extends: [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) + +The WebSocket object provides a way to manage a WebSocket connection to a server, allowing bidirectional communication. The API follows the [WebSocket spec](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). + +## `new WebSocket(url[, protocol])` + +Arguments: + +* **url** `URL | string` - The url's protocol *must* be `ws` or `wss`. +* **protocol** `string | string[]` (optional) - Subprotocol(s) to request the server use. + +## Read More + +- [MDN - WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +- [The WebSocket Specification](https://www.rfc-editor.org/rfc/rfc6455) +- [The WHATWG WebSocket Specification](https://websockets.spec.whatwg.org/) diff --git a/node_modules/undici/docs/api/api-lifecycle.md b/node_modules/undici/docs/api/api-lifecycle.md new file mode 100644 index 0000000..d158126 --- /dev/null +++ b/node_modules/undici/docs/api/api-lifecycle.md @@ -0,0 +1,62 @@ +# Client Lifecycle + +An Undici [Client](Client.md) can be best described as a state machine. The following list is a summary of the various state transitions the `Client` will go through in its lifecycle. This document also contains detailed breakdowns of each state. + +> This diagram is not a perfect representation of the undici Client. Since the Client class is not actually implemented as a state-machine, actual execution may deviate slightly from what is described below. Consider this as a general resource for understanding the inner workings of the Undici client rather than some kind of formal specification. + +## State Transition Overview + +* A `Client` begins in the **idle** state with no socket connection and no requests in queue. + * The *connect* event transitions the `Client` to the **pending** state where requests can be queued prior to processing. + * The *close* and *destroy* events transition the `Client` to the **destroyed** state. Since there are no requests in the queue, the *close* event immediately transitions to the **destroyed** state. +* The **pending** state indicates the underlying socket connection has been successfully established and requests are queueing. + * The *process* event transitions the `Client` to the **processing** state where requests are processed. + * If requests are queued, the *close* event transitions to the **processing** state; otherwise, it transitions to the **destroyed** state. + * The *destroy* event transitions to the **destroyed** state. +* The **processing** state initializes to the **processing.running** state. + * If the current request requires draining, the *needDrain* event transitions the `Client` into the **processing.busy** state which will return to the **processing.running** state with the *drainComplete* event. + * After all queued requests are completed, the *keepalive* event transitions the `Client` back to the **pending** state. If no requests are queued during the timeout, the **close** event transitions the `Client` to the **destroyed** state. + * If the *close* event is fired while the `Client` still has queued requests, the `Client` transitions to the **process.closing** state where it will complete all existing requests before firing the *done* event. + * The *done* event gracefully transitions the `Client` to the **destroyed** state. + * At any point in time, the *destroy* event will transition the `Client` from the **processing** state to the **destroyed** state, destroying any queued requests. +* The **destroyed** state is a final state and the `Client` is no longer functional. + +![A state diagram representing an Undici Client instance](../assets/lifecycle-diagram.png) + +> The diagram was generated using Mermaid.js Live Editor. Modify the state diagram [here](https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoic3RhdGVEaWFncmFtLXYyXG4gICAgWypdIC0tPiBpZGxlXG4gICAgaWRsZSAtLT4gcGVuZGluZyA6IGNvbm5lY3RcbiAgICBpZGxlIC0tPiBkZXN0cm95ZWQgOiBkZXN0cm95L2Nsb3NlXG4gICAgXG4gICAgcGVuZGluZyAtLT4gaWRsZSA6IHRpbWVvdXRcbiAgICBwZW5kaW5nIC0tPiBkZXN0cm95ZWQgOiBkZXN0cm95XG5cbiAgICBzdGF0ZSBjbG9zZV9mb3JrIDw8Zm9yaz4-XG4gICAgcGVuZGluZyAtLT4gY2xvc2VfZm9yayA6IGNsb3NlXG4gICAgY2xvc2VfZm9yayAtLT4gcHJvY2Vzc2luZ1xuICAgIGNsb3NlX2ZvcmsgLS0-IGRlc3Ryb3llZFxuXG4gICAgcGVuZGluZyAtLT4gcHJvY2Vzc2luZyA6IHByb2Nlc3NcblxuICAgIHByb2Nlc3NpbmcgLS0-IHBlbmRpbmcgOiBrZWVwYWxpdmVcbiAgICBwcm9jZXNzaW5nIC0tPiBkZXN0cm95ZWQgOiBkb25lXG4gICAgcHJvY2Vzc2luZyAtLT4gZGVzdHJveWVkIDogZGVzdHJveVxuXG4gICAgc3RhdGUgcHJvY2Vzc2luZyB7XG4gICAgICAgIHJ1bm5pbmcgLS0-IGJ1c3kgOiBuZWVkRHJhaW5cbiAgICAgICAgYnVzeSAtLT4gcnVubmluZyA6IGRyYWluQ29tcGxldGVcbiAgICAgICAgcnVubmluZyAtLT4gWypdIDoga2VlcGFsaXZlXG4gICAgICAgIHJ1bm5pbmcgLS0-IGNsb3NpbmcgOiBjbG9zZVxuICAgICAgICBjbG9zaW5nIC0tPiBbKl0gOiBkb25lXG4gICAgICAgIFsqXSAtLT4gcnVubmluZ1xuICAgIH1cbiAgICAiLCJtZXJtYWlkIjp7InRoZW1lIjoiYmFzZSJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ) + +## State details + +### idle + +The **idle** state is the initial state of a `Client` instance. While an `origin` is required for instantiating a `Client` instance, the underlying socket connection will not be established until a request is queued using [`Client.dispatch()`](Client.md#clientdispatchoptions-handlers). By calling `Client.dispatch()` directly or using one of the multiple implementations ([`Client.connect()`](Client.md#clientconnectoptions-callback), [`Client.pipeline()`](Client.md#clientpipelineoptions-handler), [`Client.request()`](Client.md#clientrequestoptions-callback), [`Client.stream()`](Client.md#clientstreamoptions-factory-callback), and [`Client.upgrade()`](Client.md#clientupgradeoptions-callback)), the `Client` instance will transition from **idle** to [**pending**](#pending) and then most likely directly to [**processing**](#processing). + +Calling [`Client.close()`](Client.md#clientclosecallback) or [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](#destroyed) state since the `Client` instance will have no queued requests in this state. + +### pending + +The **pending** state signifies a non-processing `Client`. Upon entering this state, the `Client` establishes a socket connection and emits the [`'connect'`](Client.md#event-connect) event signalling a connection was successfully established with the `origin` provided during `Client` instantiation. The internal queue is initially empty, and requests can start queueing. + +Calling [`Client.close()`](Client.md#clientclosecallback) with queued requests, transitions the `Client` to the [**processing**](#processing) state. Without queued requests, it transitions to the [**destroyed**](#destroyed) state. + +Calling [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](#destroyed) state regardless of existing requests. + +### processing + +The **processing** state is a state machine within itself. It initializes to the [**processing.running**](#running) state. The [`Client.dispatch()`](Client.md#clientdispatchoptions-handlers), [`Client.close()`](Client.md#clientclosecallback), and [`Client.destroy()`](Client.md#clientdestroyerror-callback) can be called at any time while the `Client` is in this state. `Client.dispatch()` will add more requests to the queue while existing requests continue to be processed. `Client.close()` will transition to the [**processing.closing**](#closing) state. And `Client.destroy()` will transition to [**destroyed**](#destroyed). + +#### running + +In the **processing.running** sub-state, queued requests are being processed in a FIFO order. If a request body requires draining, the *needDrain* event transitions to the [**processing.busy**](#busy) sub-state. The *close* event transitions the Client to the [**process.closing**](#closing) sub-state. If all queued requests are processed and neither [`Client.close()`](Client.md#clientclosecallback) nor [`Client.destroy()`](Client.md#clientdestroyerror-callback) are called, then the [**processing**](#processing) machine will trigger a *keepalive* event transitioning the `Client` back to the [**pending**](#pending) state. During this time, the `Client` is waiting for the socket connection to timeout, and once it does, it triggers the *timeout* event and transitions to the [**idle**](#idle) state. + +#### busy + +This sub-state is only entered when a request body is an instance of [Stream](https://nodejs.org/api/stream.html) and requires draining. The `Client` cannot process additional requests while in this state and must wait until the currently processing request body is completely drained before transitioning back to [**processing.running**](#running). + +#### closing + +This sub-state is only entered when a `Client` instance has queued requests and the [`Client.close()`](Client.md#clientclosecallback) method is called. In this state, the `Client` instance continues to process requests as usual, with the one exception that no additional requests can be queued. Once all of the queued requests are processed, the `Client` will trigger the *done* event gracefully entering the [**destroyed**](#destroyed) state without an error. + +### destroyed + +The **destroyed** state is a final state for the `Client` instance. Once in this state, a `Client` is nonfunctional. Calling any other `Client` methods will result in an `ClientDestroyedError`. diff --git a/node_modules/undici/docs/assets/lifecycle-diagram.png b/node_modules/undici/docs/assets/lifecycle-diagram.png new file mode 100644 index 0000000..4ef17b5 Binary files /dev/null and b/node_modules/undici/docs/assets/lifecycle-diagram.png differ diff --git a/node_modules/undici/docs/best-practices/client-certificate.md b/node_modules/undici/docs/best-practices/client-certificate.md new file mode 100644 index 0000000..4fc84ec --- /dev/null +++ b/node_modules/undici/docs/best-practices/client-certificate.md @@ -0,0 +1,64 @@ +# Client certificate + +Client certificate authentication can be configured with the `Client`, the required options are passed along through the `connect` option. + +The client certificates must be signed by a trusted CA. The Node.js default is to trust the well-known CAs curated by Mozilla. + +Setting the server option `requestCert: true` tells the server to request the client certificate. + +The server option `rejectUnauthorized: false` allows us to handle any invalid certificate errors in client code. The `authorized` property on the socket of the incoming request will show if the client certificate was valid. The `authorizationError` property will give the reason if the certificate was not valid. + +### Client Certificate Authentication + +```js +const { readFileSync } = require('fs') +const { join } = require('path') +const { createServer } = require('https') +const { Client } = require('undici') + +const serverOptions = { + ca: [ + readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'), + requestCert: true, + rejectUnauthorized: false +} + +const server = createServer(serverOptions, (req, res) => { + // true if client cert is valid + if(req.client.authorized === true) { + console.log('valid') + } else { + console.error(req.client.authorizationError) + } + res.end() +}) + +server.listen(0, function () { + const tls = { + ca: [ + readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'), + rejectUnauthorized: false, + servername: 'agent1' + } + const client = new Client(`https://localhost:${server.address().port}`, { + connect: tls + }) + + client.request({ + path: '/', + method: 'GET' + }, (err, { body }) => { + body.on('data', (buf) => {}) + body.on('end', () => { + client.close() + server.close() + }) + }) +}) +``` diff --git a/node_modules/undici/docs/best-practices/mocking-request.md b/node_modules/undici/docs/best-practices/mocking-request.md new file mode 100644 index 0000000..6954392 --- /dev/null +++ b/node_modules/undici/docs/best-practices/mocking-request.md @@ -0,0 +1,136 @@ +# Mocking Request + +Undici has its own mocking [utility](../api/MockAgent.md). It allow us to intercept undici HTTP requests and return mocked values instead. It can be useful for testing purposes. + +Example: + +```js +// bank.mjs +import { request } from 'undici' + +export async function bankTransfer(recipient, amount) { + const { body } = await request('http://localhost:3000/bank-transfer', + { + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient, + amount + }) + } + ) + return await body.json() +} +``` + +And this is what the test file looks like: + +```js +// index.test.mjs +import { strict as assert } from 'assert' +import { MockAgent, setGlobalDispatcher, } from 'undici' +import { bankTransfer } from './bank.mjs' + +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +// intercept the request +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, { + message: 'transaction processed' +}) + +const success = await bankTransfer('1234567890', '100') + +assert.deepEqual(success, { message: 'transaction processed' }) + +// if you dont want to check whether the body or the headers contain the same value +// just remove it from interceptor +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(400, { + message: 'bank account not found' +}) + +const badRequest = await bankTransfer('1234567890', '100') + +assert.deepEqual(badRequest, { message: 'bank account not found' }) +``` + +Explore other MockAgent functionality [here](../api/MockAgent.md) + +## Debug Mock Value + +When the interceptor and the request options are not the same, undici will automatically make a real HTTP request. To prevent real requests from being made, use `mockAgent.disableNetConnect()`: + +```js +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); +mockAgent.disableNetConnect() + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(200, { + message: 'transaction processed' +}) + +const badRequest = await bankTransfer('1234567890', '100') +// Will throw an error +// MockNotMatchedError: Mock dispatch not matched for path '/bank-transfer': +// subsequent request to origin http://localhost:3000 was not allowed (net.connect disabled) +``` + +## Reply with data based on request + +If the mocked response needs to be dynamically derived from the request parameters, you can provide a function instead of an object to `reply`: + +```js +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, (opts) => { + // do something with opts + + return { message: 'transaction processed' } +}) +``` + +in this case opts will be + +``` +{ + method: 'POST', + headers: { 'X-TOKEN-SECRET': 'SuperSecretToken' }, + body: '{"recipient":"1234567890","amount":"100"}', + origin: 'http://localhost:3000', + path: '/bank-transfer' +} +``` diff --git a/node_modules/undici/docs/best-practices/proxy.md b/node_modules/undici/docs/best-practices/proxy.md new file mode 100644 index 0000000..bf10295 --- /dev/null +++ b/node_modules/undici/docs/best-practices/proxy.md @@ -0,0 +1,127 @@ +# Connecting through a proxy + +Connecting through a proxy is possible by: + +- Using [AgentProxy](../api/ProxyAgent.md). +- Configuring `Client` or `Pool` constructor. + +The proxy url should be passed to the `Client` or `Pool` constructor, while the upstream server url +should be added to every request call in the `path`. +For instance, if you need to send a request to the `/hello` route of your upstream server, +the `path` should be `path: 'http://upstream.server:port/hello?foo=bar'`. + +If you proxy requires basic authentication, you can send it via the `proxy-authorization` header. + +### Connect without authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import proxy from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar' +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = proxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + +### Connect with authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import proxy from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +proxyServer.authenticate = function (req, fn) { + fn(null, req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}`) +} + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar', + headers: { + 'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}` + } +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = proxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + diff --git a/node_modules/undici/docs/best-practices/writing-tests.md b/node_modules/undici/docs/best-practices/writing-tests.md new file mode 100644 index 0000000..57549de --- /dev/null +++ b/node_modules/undici/docs/best-practices/writing-tests.md @@ -0,0 +1,20 @@ +# Writing tests + +Undici is tuned for a production use case and its default will keep +a socket open for a few seconds after an HTTP request is completed to +remove the overhead of opening up a new socket. These settings that makes +Undici shine in production are not a good fit for using Undici in automated +tests, as it will result in longer execution times. + +The following are good defaults that will keep the socket open for only 10ms: + +```js +import { request, setGlobalDispatcher, Agent } from 'undici' + +const agent = new Agent({ + keepAliveTimeout: 10, // milliseconds + keepAliveMaxTimeout: 10 // milliseconds +}) + +setGlobalDispatcher(agent) +``` diff --git a/node_modules/undici/index-fetch.js b/node_modules/undici/index-fetch.js new file mode 100644 index 0000000..0d59d25 --- /dev/null +++ b/node_modules/undici/index-fetch.js @@ -0,0 +1,16 @@ +'use strict' + +const fetchImpl = require('./lib/fetch').fetch + +module.exports.fetch = async function fetch (resource) { + try { + return await fetchImpl(...arguments) + } catch (err) { + Error.captureStackTrace(err, this) + throw err + } +} +module.exports.FormData = require('./lib/fetch/formdata').FormData +module.exports.Headers = require('./lib/fetch/headers').Headers +module.exports.Response = require('./lib/fetch/response').Response +module.exports.Request = require('./lib/fetch/request').Request diff --git a/node_modules/undici/index.d.ts b/node_modules/undici/index.d.ts new file mode 100644 index 0000000..d67de97 --- /dev/null +++ b/node_modules/undici/index.d.ts @@ -0,0 +1,55 @@ +import Dispatcher from'./types/dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './types/global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './types/global-origin' +import Pool from'./types/pool' +import { RedirectHandler, DecoratorHandler } from './types/handlers' + +import BalancedPool from './types/balanced-pool' +import Client from'./types/client' +import buildConnector from'./types/connector' +import errors from'./types/errors' +import Agent from'./types/agent' +import MockClient from'./types/mock-client' +import MockPool from'./types/mock-pool' +import MockAgent from'./types/mock-agent' +import mockErrors from'./types/mock-errors' +import ProxyAgent from'./types/proxy-agent' +import { request, pipeline, stream, connect, upgrade } from './types/api' + +export * from './types/cookies' +export * from './types/fetch' +export * from './types/file' +export * from './types/filereader' +export * from './types/formdata' +export * from './types/diagnostics-channel' +export * from './types/websocket' +export * from './types/content-type' +export { Interceptable } from './types/mock-interceptor' + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, RedirectHandler, DecoratorHandler } +export default Undici + +declare namespace Undici { + var Dispatcher: typeof import('./types/dispatcher').default + var Pool: typeof import('./types/pool').default; + var RedirectHandler: typeof import ('./types/handlers').RedirectHandler + var DecoratorHandler: typeof import ('./types/handlers').DecoratorHandler + var createRedirectInterceptor: typeof import ('./types/interceptors').createRedirectInterceptor + var BalancedPool: typeof import('./types/balanced-pool').default; + var Client: typeof import('./types/client').default; + var buildConnector: typeof import('./types/connector').default; + var errors: typeof import('./types/errors').default; + var Agent: typeof import('./types/agent').default; + var setGlobalDispatcher: typeof import('./types/global-dispatcher').setGlobalDispatcher; + var getGlobalDispatcher: typeof import('./types/global-dispatcher').getGlobalDispatcher; + var request: typeof import('./types/api').request; + var stream: typeof import('./types/api').stream; + var pipeline: typeof import('./types/api').pipeline; + var connect: typeof import('./types/api').connect; + var upgrade: typeof import('./types/api').upgrade; + var MockClient: typeof import('./types/mock-client').default; + var MockPool: typeof import('./types/mock-pool').default; + var MockAgent: typeof import('./types/mock-agent').default; + var mockErrors: typeof import('./types/mock-errors').default; + var fetch: typeof import('./types/fetch').fetch; +} diff --git a/node_modules/undici/index.js b/node_modules/undici/index.js new file mode 100644 index 0000000..02ac246 --- /dev/null +++ b/node_modules/undici/index.js @@ -0,0 +1,155 @@ +'use strict' + +const Client = require('./lib/client') +const Dispatcher = require('./lib/dispatcher') +const errors = require('./lib/core/errors') +const Pool = require('./lib/pool') +const BalancedPool = require('./lib/balanced-pool') +const Agent = require('./lib/agent') +const util = require('./lib/core/util') +const { InvalidArgumentError } = errors +const api = require('./lib/api') +const buildConnector = require('./lib/core/connect') +const MockClient = require('./lib/mock/mock-client') +const MockAgent = require('./lib/mock/mock-agent') +const MockPool = require('./lib/mock/mock-pool') +const mockErrors = require('./lib/mock/mock-errors') +const ProxyAgent = require('./lib/proxy-agent') +const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global') +const DecoratorHandler = require('./lib/handler/DecoratorHandler') +const RedirectHandler = require('./lib/handler/RedirectHandler') +const createRedirectInterceptor = require('./lib/interceptor/redirectInterceptor') + +let hasCrypto +try { + require('crypto') + hasCrypto = true +} catch { + hasCrypto = false +} + +Object.assign(Dispatcher.prototype, api) + +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent + +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor + +module.exports.buildConnector = buildConnector +module.exports.errors = errors + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } + + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } + + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } + + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } + + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } + + url = util.parseURL(url) + } + + const { agent, dispatcher = getGlobalDispatcher() } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } + + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } +} + +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher + +if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { + let fetchImpl = null + module.exports.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = require('./lib/fetch').fetch + } + + try { + return await fetchImpl(...arguments) + } catch (err) { + Error.captureStackTrace(err, this) + throw err + } + } + module.exports.Headers = require('./lib/fetch/headers').Headers + module.exports.Response = require('./lib/fetch/response').Response + module.exports.Request = require('./lib/fetch/request').Request + module.exports.FormData = require('./lib/fetch/formdata').FormData + module.exports.File = require('./lib/fetch/file').File + module.exports.FileReader = require('./lib/fileapi/filereader').FileReader + + const { setGlobalOrigin, getGlobalOrigin } = require('./lib/fetch/global') + + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin +} + +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = require('./lib/cookies') + + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie + + const { parseMIMEType, serializeAMimeType } = require('./lib/fetch/dataURL') + + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType +} + +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = require('./lib/websocket/websocket') + + module.exports.WebSocket = WebSocket +} + +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) + +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors diff --git a/node_modules/undici/lib/agent.js b/node_modules/undici/lib/agent.js new file mode 100644 index 0000000..0b18f2a --- /dev/null +++ b/node_modules/undici/lib/agent.js @@ -0,0 +1,148 @@ +'use strict' + +const { InvalidArgumentError } = require('./core/errors') +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('./core/symbols') +const DispatcherBase = require('./dispatcher-base') +const Pool = require('./pool') +const Client = require('./client') +const util = require('./core/util') +const createRedirectInterceptor = require('./interceptor/redirectInterceptor') +const { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')() + +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kMaxRedirections = Symbol('maxRedirections') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kFinalizer = Symbol('finalizer') +const kOptions = Symbol('options') + +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} + +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super() + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } + + this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] + + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kMaxRedirections] = maxRedirections + this[kFactory] = factory + this[kClients] = new Map() + this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { + const ref = this[kClients].get(key) + if (ref !== undefined && ref.deref() === undefined) { + this[kClients].delete(key) + } + }) + + const agent = this + + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) + } + + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } + } + + get [kRunning] () { + let ret = 0 + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore next: gc is undeterministic */ + if (client) { + ret += client[kRunning] + } + } + return ret + } + + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } + + const ref = this[kClients].get(key) + + let dispatcher = ref ? ref.deref() : null + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) + } + + return dispatcher.dispatch(opts, handler) + } + + async [kClose] () { + const closePromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + closePromises.push(client.close()) + } + } + + await Promise.all(closePromises) + } + + async [kDestroy] (err) { + const destroyPromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + destroyPromises.push(client.destroy(err)) + } + } + + await Promise.all(destroyPromises) + } +} + +module.exports = Agent diff --git a/node_modules/undici/lib/api/abort-signal.js b/node_modules/undici/lib/api/abort-signal.js new file mode 100644 index 0000000..895629a --- /dev/null +++ b/node_modules/undici/lib/api/abort-signal.js @@ -0,0 +1,57 @@ +const { RequestAbortedError } = require('../core/errors') + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) + } +} + +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self) + return + } + + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } + + if ('addEventListener' in self[kSignal]) { + self[kSignal].addEventListener('abort', self[kListener]) + } else { + self[kSignal].addListener('abort', self[kListener]) + } +} + +function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } + + self[kSignal] = null + self[kListener] = null +} + +module.exports = { + addSignal, + removeSignal +} diff --git a/node_modules/undici/lib/api/api-connect.js b/node_modules/undici/lib/api/api-connect.js new file mode 100644 index 0000000..0503b1a --- /dev/null +++ b/node_modules/undici/lib/api/api-connect.js @@ -0,0 +1,98 @@ +'use strict' + +const { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors') +const { AsyncResource } = require('async_hooks') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = connect diff --git a/node_modules/undici/lib/api/api-pipeline.js b/node_modules/undici/lib/api/api-pipeline.js new file mode 100644 index 0000000..af4a180 --- /dev/null +++ b/node_modules/undici/lib/api/api-pipeline.js @@ -0,0 +1,249 @@ +'use strict' + +const { + Readable, + Duplex, + PassThrough +} = require('stream') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') +const assert = require('assert') + +const kResume = Symbol('resume') + +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) + + this[kResume] = null + } + + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() + } + } + + _destroy (err, callback) { + this._read() + + callback(err) + } +} + +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } + + _read () { + this[kResume]() + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + callback(err) + } +} + +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_PIPELINE') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null + + this.req = new PipelineRequest().on('error', util.nop) + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this + + if (body && body.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (abort && err) { + abort() + } + + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) + + removeSignal(this) + + callback(err) + } + }).on('prefinish', () => { + const { req } = this + + // Node < 15 does not call _final in same tick. + req.push(null) + }) + + this.res = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + const { ret, res } = this + + assert(!res, 'pipeline cannot be retried') + + if (ret.destroyed) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + this.res = new PipelineResponse(resume) + + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', util.nop) + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this + + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + res.push(null) + } + + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} + +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } +} + +module.exports = pipeline diff --git a/node_modules/undici/lib/api/api-request.js b/node_modules/undici/lib/api/api-request.js new file mode 100644 index 0000000..b467487 --- /dev/null +++ b/node_modules/undici/lib/api/api-request.js @@ -0,0 +1,203 @@ +'use strict' + +const Readable = require('./readable') +const { + InvalidArgumentError, + RequestAbortedError, + ResponseStatusCodeError +} = require('../core/errors') +const util = require('../core/util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.throwOnError = throwOnError + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + const parsedHeaders = util.parseHeaders(rawHeaders) + const contentType = parsedHeaders['content-type'] + const body = new Readable(resume, abort, contentType) + + this.callback = null + this.res = body + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body, contentType, statusCode, statusMessage, headers } + ) + return + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body, + context + }) + } + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + util.parseHeaders(trailers, this.trailers) + + res.push(null) + } + + onError (err) { + const { res, callback, body, opaque } = this + + removeSignal(this) + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + if (statusCode === 204 || !contentType) { + body.dump() + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return + } + + try { + if (contentType.startsWith('application/json')) { + const payload = await body.json() + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + + if (contentType.startsWith('text/')) { + const payload = await body.text() + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + } catch (err) { + // Process in a fallback if error + } + + body.dump() + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) +} + +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = request diff --git a/node_modules/undici/lib/api/api-stream.js b/node_modules/undici/lib/api/api-stream.js new file mode 100644 index 0000000..7560a2e --- /dev/null +++ b/node_modules/undici/lib/api/api-stream.js @@ -0,0 +1,223 @@ +'use strict' + +const { finished, PassThrough } = require('stream') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ResponseStatusCodeError +} = require('../core/errors') +const util = require('../core/util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + this.throwOnError = throwOnError || false + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + this.factory = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + const res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) + + if (this.throwOnError && statusCode >= 400) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + const chunks = [] + const pt = new PassThrough() + pt + .on('data', (chunk) => chunks.push(chunk)) + .on('end', () => { + const payload = Buffer.concat(chunks).toString('utf8') + this.runInAsyncScope( + callback, + null, + new ResponseStatusCodeError( + `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, + statusCode, + headers, + payload + ) + ) + }) + .on('error', (err) => { + this.onError(err) + }) + this.res = pt + return + } + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + res.on('drain', resume) + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this + + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } + + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain + + return needDrain !== true + } + + onData (chunk) { + const { res } = this + + return res.write(chunk) + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + this.trailers = util.parseHeaders(trailers) + + res.end() + } + + onError (err) { + const { res, callback, opaque, body } = this + + removeSignal(this) + + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream diff --git a/node_modules/undici/lib/api/api-upgrade.js b/node_modules/undici/lib/api/api-upgrade.js new file mode 100644 index 0000000..ef783e8 --- /dev/null +++ b/node_modules/undici/lib/api/api-upgrade.js @@ -0,0 +1,105 @@ +'use strict' + +const { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors') +const { AsyncResource } = require('async_hooks') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') +const assert = require('assert') + +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = null + } + + onHeaders () { + throw new SocketError('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + assert.strictEqual(statusCode, 101) + + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = upgrade diff --git a/node_modules/undici/lib/api/index.js b/node_modules/undici/lib/api/index.js new file mode 100644 index 0000000..8983a5e --- /dev/null +++ b/node_modules/undici/lib/api/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports.request = require('./api-request') +module.exports.stream = require('./api-stream') +module.exports.pipeline = require('./api-pipeline') +module.exports.upgrade = require('./api-upgrade') +module.exports.connect = require('./api-connect') diff --git a/node_modules/undici/lib/api/readable.js b/node_modules/undici/lib/api/readable.js new file mode 100644 index 0000000..a184e8e --- /dev/null +++ b/node_modules/undici/lib/api/readable.js @@ -0,0 +1,299 @@ +// Ported from https://github.com/nodejs/undici/pull/907 + +'use strict' + +const assert = require('assert') +const { Readable } = require('stream') +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = require('../core/errors') +const util = require('../core/util') +const { ReadableStreamFrom, toUSVString } = require('../core/util') + +let Blob + +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') + +module.exports = class BodyReadable extends Readable { + constructor (resume, abort, contentType = '') { + super({ + autoDestroy: true, + read: resume, + highWaterMark: 64 * 1024 // Same as nodejs fs streams. + }) + + this._readableState.dataEmitted = false + + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false + } + + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this + } + + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (err) { + this[kAbort]() + } + + return super.destroy(err) + } + + emit (ev, ...args) { + if (ev === 'data') { + // Node < 16.7 + this._readableState.dataEmitted = true + } else if (ev === 'error') { + // Node < 16 + this._readableState.errorEmitted = true + } + return super.emit(ev, ...args) + } + + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true + } + return super.on(ev, ...args) + } + + addListener (ev, ...args) { + return this.on(ev, ...args) + } + + off (ev, ...args) { + const ret = super.off(ev, ...args) + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) + } + return ret + } + + removeListener (ev, ...args) { + return this.off(ev, ...args) + } + + push (chunk) { + if (this[kConsume] && chunk !== null && this.readableLength === 0) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } + + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } + + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } + + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } + + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } + + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } + } + return this[kBody] + } + + async dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal + const abortFn = () => { + this.destroy() + } + if (signal) { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + util.throwIfAborted(signal) + signal.addEventListener('abort', abortFn, { once: true }) + } + try { + for await (const chunk of this) { + util.throwIfAborted(signal) + limit -= Buffer.byteLength(chunk) + if (limit < 0) { + return + } + } + } catch { + util.throwIfAborted(signal) + } finally { + if (signal) { + signal.removeEventListener('abort', abortFn) + } + } + } +} + +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] +} + +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} + +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') + } + + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + process.nextTick(consumeStart, stream[kConsume]) + }) +} + +function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream + + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } + + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } + + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop + } +} + +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume + + try { + if (type === 'text') { + resolve(toUSVString(Buffer.concat(body))) + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))) + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length) + + let pos = 0 + for (const buf of body) { + dst.set(buf, pos) + pos += buf.byteLength + } + + resolve(dst) + } else if (type === 'blob') { + if (!Blob) { + Blob = require('buffer').Blob + } + resolve(new Blob(body, { type: stream[kContentType] })) + } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) + } +} + +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} + +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err) + } else { + consume.resolve() + } + + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} diff --git a/node_modules/undici/lib/balanced-pool.js b/node_modules/undici/lib/balanced-pool.js new file mode 100644 index 0000000..10bc6a4 --- /dev/null +++ b/node_modules/undici/lib/balanced-pool.js @@ -0,0 +1,190 @@ +'use strict' + +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = require('./core/errors') +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = require('./pool-base') +const Pool = require('./pool') +const { kUrl, kInterceptors } = require('./core/symbols') +const { parseOrigin } = require('./core/util') +const kFactory = Symbol('factory') + +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') + +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() + + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory + + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) + + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } + + this._updateBalancedPoolStats() + + return this + } + + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) + } + + return this + } + + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) + + if (allClientsBusy) { + return + } + + let counter = 0 + + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) + + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] + } +} + +module.exports = BalancedPool diff --git a/node_modules/undici/lib/client.js b/node_modules/undici/lib/client.js new file mode 100644 index 0000000..b230c36 --- /dev/null +++ b/node_modules/undici/lib/client.js @@ -0,0 +1,1777 @@ +// @ts-check + +'use strict' + +/* global WebAssembly */ + +const assert = require('assert') +const net = require('net') +const util = require('./core/util') +const timers = require('./timers') +const Request = require('./core/request') +const DispatcherBase = require('./dispatcher-base') +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError +} = require('./core/errors') +const buildConnector = require('./core/connect') +const { + kUrl, + kReset, + kServerName, + kClient, + kBusy, + kParser, + kConnect, + kBlocking, + kResuming, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize +} = require('./core/symbols') +const FastBuffer = Buffer[Symbol.species] + +const kClosedResolve = Symbol('kClosedResolve') + +const channels = {} + +try { + const diagnosticsChannel = require('diagnostics_channel') + channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') + channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') + channels.connectError = diagnosticsChannel.channel('undici:client:connectError') + channels.connected = diagnosticsChannel.channel('undici:client:connected') +} catch { + channels.sendHeaders = { hasSubscribers: false } + channels.beforeConnect = { hasSubscribers: false } + channels.connectError = { hasSubscribers: false } + channels.connected = { hasSubscribers: false } +} + +/** + * @type {import('../types/client').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../types/client').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout + } = {}) { + super() + + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) + ? interceptors.Client + : [createRedirectInterceptor({ maxRedirections })] + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kSocket] = null + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize || 16384 + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRedirections] = maxRedirections + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value + resume(this, true) + } + + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } + + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } + + get [kConnected] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed + } + + get [kBusy] () { + const socket = this[kSocket] + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize] >= (this[kPipelining] || 1)) || + this[kPending] > 0 + ) + } + + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } + + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin + + const request = new Request(origin, opts, handler) + + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + process.nextTick(resume, this) + } else { + resume(this, true) + } + + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } + + return this[kNeedDrain] < 2 + } + + async [kClose] () { + return new Promise((resolve) => { + if (!this[kSize]) { + this.destroy(resolve) + } else { + this[kClosedResolve] = resolve + } + }) + } + + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) + } + + const callback = () => { + if (this[kClosedResolve]) { + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve() + } + + if (!this[kSocket]) { + queueMicrotask(callback) + } else { + util.destroy(this[kSocket].on('close', callback), err) + } + + resume(this) + }) + } +} + +const constants = require('./llhttp/constants') +const createRedirectInterceptor = require('./interceptor/redirectInterceptor') +const EMPTY_BUF = Buffer.alloc(0) + +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? require('./llhttp/llhttp.wasm.js') : undefined + + let mod + try { + mod = await WebAssembly.compile(Buffer.from(require('./llhttp/llhttp_simd.wasm.js'), 'base64')) + } catch (e) { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || require('./llhttp/llhttp.wasm.js'), 'base64')) + } + + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ + + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageComplete() || 0 + } + + /* eslint-enable camelcase */ + } + }) +} + +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() + +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null + +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 + +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) + + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = null + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (value, type) { + this.timeoutType = type + if (value !== this.timeoutValue) { + timers.clearTimeout(this.timeout) + if (value) { + this.timeout = timers.setTimeout(onParserTimeout, value, this) + // istanbul ignore else: only for jest + if (this.timeout.unref) { + this.timeout.unref() + } + } else { + this.timeout = null + } + this.timeoutValue = value + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_resume(this.ptr) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } + + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) + + const { socket, llhttp } = this + + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret + + try { + currentBufferRef = data + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(data.slice(offset)) + } else if (ret !== constants.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + /* istanbul ignore else: difficult to make a test case for */ + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = Buffer.from(llhttp.memory.buffer, ptr, len).toString() + } + throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) + } + } catch (err) { + util.destroy(socket, err) + } + } + + destroy () { + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_free(this.ptr) + this.ptr = null + + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + + this.paused = false + } + + onStatus (buf) { + this.statusText = buf.toString() + } + + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 + } + } + + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + this.trackHeader(buf.length) + } + + onHeaderValue (buf) { + let len = this.headers.length + + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + const key = this.headers[len - 2] + if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { + this.connection += buf.toString() + } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { + this.contentLength += buf.toString() + } + + this.trackHeader(buf.length) + } + + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } + + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this + + assert(upgrade) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') + + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + socket.unshift(head) + + socket[kParser].destroy() + socket[kParser] = null + + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) + + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } + + resume(client) + } + + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert(!this.upgrade) + assert(this.statusCode < 200) + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } + + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) + + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true + } + + let pause + try { + pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + } catch (err) { + util.destroy(socket, err) + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) + } + + return pause ? constants.ERROR.PAUSED : 0 + } + + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert.strictEqual(this.timeoutType, TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } + + this.bytesRead += buf.length + + try { + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } catch (err) { + util.destroy(socket, err) + return -1 + } + } + + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(statusCode >= 100) + + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (statusCode < 200) { + return + } + + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + try { + request.onComplete(headers) + } catch (err) { + errorRequest(client, request, err) + } + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert.strictEqual(client[kRunning], 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(resume, client) + } else { + resume(client) + } + } +} + +function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!parser.paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!parser.paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_IDLE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) + } +} + +function onSocketReadable () { + const { [kParser]: parser } = this + parser.readMore() +} + +function onSocketError (err) { + const { [kParser]: parser } = this + + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete() + return + } + + this[kError] = err + + onError(this[kClient], err) +} + +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + assert(client[kSize] === 0) + } +} + +function onSocketEnd () { + const { [kParser]: parser } = this + + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return + } + + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onSocketClose () { + const { [kClient]: client } = this + + if (!this[kError] && this[kParser].statusCode && !this[kParser].shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + this[kParser].onMessageComplete() + } + + this[kParser].destroy() + this[kParser] = null + + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + client[kSocket] = null + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + resume(client) +} + +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) + + let { host, hostname, protocol, port } = client[kUrl] + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') + + assert(idx !== -1) + const ip = hostname.substr(1, idx - 1) + + assert(net.isIP(ip)) + hostname = ip + } + + client[kConnecting] = true + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err) + } else { + resolve(socket) + } + }) + }) + + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = null + } + + client[kConnecting] = false + + assert(socket) + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kError] = null + socket[kParser] = new Parser(client, socket, llhttpInstance) + socket[kClient] = client + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) + + client[kSocket] = socket + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) + } + client.emit('connect', client[kUrl], [client]) + } catch (err) { + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + errorRequest(client, request, err) + } + } else { + onError(client, err) + } + + client.emit('connectionError', client[kUrl], [client], err) + } + + resume(client) +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } + + if (client.closed && !client[kSize]) { + client.destroy() + return + } + + const socket = client[kSocket] + + if (socket && !socket.destroyed) { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) + } + } + } + + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) + } else { + emitDrain(client) + } + continue + } + + if (client[kPending] === 0) { + return + } + + if (client[kRunning] >= (client[kPipelining] || 1)) { + return + } + + const request = client[kQueue][client[kPendingIdx]] + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } + + client[kServerName] = request.servername + + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return + } + } + + if (client[kConnecting]) { + return + } + + if (!socket) { + connect(client) + return + } + + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return + } + + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return + } + + if (util.isStream(request.body) && util.bodyLength(request.body) === 0) { + request.body + .on('data', /* istanbul ignore next */ function () { + /* istanbul ignore next */ + assert(false) + }) + .on('error', function (err) { + errorRequest(client, request, err) + }) + .on('end', function () { + util.destroy(this) + }) + + request.body = null + } + + if (client[kRunning] > 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } + } +} + +function write (client, request) { + const { body, method, path, host, upgrade, headers, blocking, reset } = request + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + let contentLength = util.bodyLength(body) + + if (contentLength === null) { + contentLength = request.contentLength + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + if (request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + const socket = client[kSocket] + + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError()) + + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true + } + + if (reset != null) { + socket[kReset] = reset + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } + + if (blocking) { + socket[kBlocking] = true + } + + let header = `${method} ${path} HTTP/1.1\r\n` + + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } + + if (headers) { + header += headers + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + /* istanbul ignore else: assertion */ + if (!body) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'ascii') + } else { + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'ascii') + } + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'ascii') + socket.write(body) + socket.uncork() + request.onBodySent(body) + request.onRequestSent() + if (!expectsPayload) { + socket[kReset] = true + } + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) + } else { + writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) + } + } else if (util.isStream(body)) { + writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) + } else if (util.isIterable(body)) { + writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) + } else { + assert(false) + } + + return true +} + +function writeStream ({ body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + let finished = false + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + + const onData = function (chunk) { + try { + assert(!finished) + + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } + } + const onDrain = function () { + assert(!finished) + + if (body.resume) { + body.resume() + } + } + const onAbort = function () { + onFinished(new RequestAbortedError()) + } + const onFinished = function (err) { + if (finished) { + return + } + + finished = true + + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + + socket + .off('drain', onDrain) + .off('error', onFinished) + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) + + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } + + writer.destroy(err) + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) + + if (body.resume) { + body.resume() + } + + socket + .on('drain', onDrain) + .on('error', onFinished) +} + +async function writeBlob ({ body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') + + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'ascii') + socket.write(buffer) + socket.uncork() + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + resume(client) + } catch (err) { + util.destroy(socket, err) + } +} + +async function writeIterable ({ body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + socket + .on('close', onDrain) + .on('drain', onDrain) + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain() + } + } + + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} + +class AsyncWriter { + constructor ({ socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header + + socket[kWriting] = true + } + + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + socket.cork() + + if (bytesWritten === 0) { + if (!expectsPayload) { + socket[kReset] = true + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'ascii') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'ascii') + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'ascii') + } + + this.bytesWritten += len + + const ret = socket.write(chunk) + + socket.uncork() + + request.onBodySent(chunk) + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + } + + return ret + } + + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() + + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'ascii') + } else { + socket.write(`${header}\r\n`, 'ascii') + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'ascii') + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + + resume(client) + } + + destroy (err) { + const { socket, client } = this + + socket[kWriting] = false + + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + util.destroy(socket, err) + } + } +} + +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} + +module.exports = Client diff --git a/node_modules/undici/lib/compat/dispatcher-weakref.js b/node_modules/undici/lib/compat/dispatcher-weakref.js new file mode 100644 index 0000000..dbca858 --- /dev/null +++ b/node_modules/undici/lib/compat/dispatcher-weakref.js @@ -0,0 +1,38 @@ +'use strict' + +/* istanbul ignore file: only for Node 12 */ + +const { kConnected, kSize } = require('../core/symbols') + +class CompatWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} + +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer + } + + register (dispatcher, key) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } +} + +module.exports = function () { + return { + WeakRef: global.WeakRef || CompatWeakRef, + FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer + } +} diff --git a/node_modules/undici/lib/cookies/constants.js b/node_modules/undici/lib/cookies/constants.js new file mode 100644 index 0000000..85f1fec --- /dev/null +++ b/node_modules/undici/lib/cookies/constants.js @@ -0,0 +1,12 @@ +'use strict' + +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 + +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} diff --git a/node_modules/undici/lib/cookies/index.js b/node_modules/undici/lib/cookies/index.js new file mode 100644 index 0000000..c9c1f28 --- /dev/null +++ b/node_modules/undici/lib/cookies/index.js @@ -0,0 +1,184 @@ +'use strict' + +const { parseSetCookie } = require('./parse') +const { stringify, getHeadersList } = require('./util') +const { webidl } = require('../fetch/webidl') +const { Headers } = require('../fetch/headers') + +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ + +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookie = headers.get('cookie') + const out = {} + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') + + out[name.trim()] = value.join('=') + } + + return out +} + +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + name = webidl.converters.DOMString(name) + attributes = webidl.converters.DeleteCookieAttributes(attributes) + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} + +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookies = getHeadersList(headers).cookies + + if (!cookies) { + return [] + } + + // In older versions of undici, cookies is a list of name:value. + return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair)) +} + +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + cookie = webidl.converters.Cookie(cookie) + + const str = stringify(cookie) + + if (str) { + headers.append('Set-Cookie', stringify(cookie)) + } +} + +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + } +]) + +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: [] + } +]) + +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie +} diff --git a/node_modules/undici/lib/cookies/parse.js b/node_modules/undici/lib/cookies/parse.js new file mode 100644 index 0000000..aae2750 --- /dev/null +++ b/node_modules/undici/lib/cookies/parse.js @@ -0,0 +1,317 @@ +'use strict' + +const { maxNameValuePairSize, maxAttributeValueSize } = require('./constants') +const { isCTLExcludingHtab } = require('./util') +const { collectASequenceOfCodePointsFast } = require('../fetch/dataURL') +const assert = require('assert') + +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } +} + +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = '' + let attributeValue = '' + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} + +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} diff --git a/node_modules/undici/lib/cookies/util.js b/node_modules/undici/lib/cookies/util.js new file mode 100644 index 0000000..2290329 --- /dev/null +++ b/node_modules/undici/lib/cookies/util.js @@ -0,0 +1,291 @@ +'use strict' + +const assert = require('assert') +const { kHeadersList } = require('../core/symbols') + +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } + + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false + } + } +} + +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) + + if ( + (code <= 0x20 || code > 0x7F) || + char === '(' || + char === ')' || + char === '>' || + char === '<' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' + ) { + throw new Error('Invalid cookie name') + } + } +} + +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || // exclude CTLs (0-31) + code === 0x22 || + code === 0x2C || + code === 0x3B || + code === 0x5C || + code > 0x7E // non-ascii + ) { + throw new Error('Invalid header value') + } + } +} + +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) + + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') + } + } +} + +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } + + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ] + + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ] + + const dayName = days[date.getUTCDay()] + const day = date.getUTCDate().toString().padStart(2, '0') + const month = months[date.getUTCMonth()] + const year = date.getUTCFullYear() + const hour = date.getUTCHours().toString().padStart(2, '0') + const minute = date.getUTCMinutes().toString().padStart(2, '0') + const second = date.getUTCSeconds().toString().padStart(2, '0') + + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name) + validateCookieValue(cookie.value) + + const out = [`${cookie.name}=${cookie.value}`] + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } + + if (cookie.secure) { + out.push('Secure') + } + + if (cookie.httpOnly) { + out.push('HttpOnly') + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } + + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('=') + + out.push(`${key.trim()}=${value.join('=')}`) + } + + return out.join('; ') +} + +let kHeadersListNode + +function getHeadersList (headers) { + if (headers[kHeadersList]) { + return headers[kHeadersList] + } + + if (!kHeadersListNode) { + kHeadersListNode = Object.getOwnPropertySymbols(headers).find( + (symbol) => symbol.description === 'headers list' + ) + + assert(kHeadersListNode, 'Headers cannot be parsed') + } + + const headersList = headers[kHeadersListNode] + assert(headersList) + + return headersList +} + +module.exports = { + isCTLExcludingHtab, + stringify, + getHeadersList +} diff --git a/node_modules/undici/lib/core/connect.js b/node_modules/undici/lib/core/connect.js new file mode 100644 index 0000000..f3b5cc3 --- /dev/null +++ b/node_modules/undici/lib/core/connect.js @@ -0,0 +1,185 @@ +'use strict' + +const net = require('net') +const assert = require('assert') +const util = require('./util') +const { InvalidArgumentError, ConnectTimeoutError } = require('./errors') + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +let SessionCache +if (global.FinalizationRegistry) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new global.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } + } +} else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + } + + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } + + this._sessionCache.set(sessionKey, session) + } + } +} + +function buildConnector ({ maxCachedSessions, socketPath, timeout, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = require('tls') + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null + + assert(sessionKey) + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + socket: httpSocket, // upgrade socket connection + port: port || 443, + host: hostname + }) + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port: port || 80, + host: hostname + }) + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket + } +} + +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} + } + + let s1 = null + let s2 = null + const timeoutId = setTimeout(() => { + // setImmediate is added to make sure that we priotorise socket error events over timeouts + s1 = setImmediate(() => { + if (process.platform === 'win32') { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout()) + } else { + onConnectTimeout() + } + }) + }, timeout) + return () => { + clearTimeout(timeoutId) + clearImmediate(s1) + clearImmediate(s2) + } +} + +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) +} + +module.exports = buildConnector diff --git a/node_modules/undici/lib/core/errors.js b/node_modules/undici/lib/core/errors.js new file mode 100644 index 0000000..653782d --- /dev/null +++ b/node_modules/undici/lib/core/errors.js @@ -0,0 +1,216 @@ +'use strict' + +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } +} + +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ConnectTimeoutError) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' + } +} + +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersTimeoutError) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' + } +} + +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersOverflowError) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } +} + +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, BodyTimeoutError) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } +} + +class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message) + Error.captureStackTrace(this, ResponseStatusCodeError) + this.name = 'ResponseStatusCodeError' + this.message = message || 'Response Status Code Error' + this.code = 'UND_ERR_RESPONSE_STATUS_CODE' + this.body = body + this.status = statusCode + this.statusCode = statusCode + this.headers = headers + } +} + +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidArgumentError) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } +} + +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidReturnValueError) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } +} + +class RequestAbortedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestAbortedError) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } +} + +class InformationalError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InformationalError) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } +} + +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestContentLengthMismatchError) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } +} + +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseContentLengthMismatchError) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } +} + +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientDestroyedError) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } +} + +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientClosedError) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' + } +} + +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + Error.captureStackTrace(this, SocketError) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } +} + +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } +} + +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } +} + +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + Error.captureStackTrace(this, HTTPParserError) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } +} + +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseExceededMaxSizeError) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } +} + +module.exports = { + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError +} diff --git a/node_modules/undici/lib/core/request.js b/node_modules/undici/lib/core/request.js new file mode 100644 index 0000000..c82159e --- /dev/null +++ b/node_modules/undici/lib/core/request.js @@ -0,0 +1,367 @@ +'use strict' + +const { + InvalidArgumentError, + NotSupportedError +} = require('./errors') +const assert = require('assert') +const util = require('./util') + +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js + +/** + * Verifies that the given val is a valid HTTP token + * per the rules defined in RFC 7230 + * See https://tools.ietf.org/html/rfc7230#section-3.2.6 + */ +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ + +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ + +const kHandler = Symbol('handler') + +const channels = {} + +let extractBody + +try { + const diagnosticsChannel = require('diagnostics_channel') + channels.create = diagnosticsChannel.channel('undici:request:create') + channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') + channels.headers = diagnosticsChannel.channel('undici:request:headers') + channels.trailers = diagnosticsChannel.channel('undici:request:trailers') + channels.error = diagnosticsChannel.channel('undici:request:error') +} catch { + channels.create = { hasSubscribers: false } + channels.bodySent = { hasSubscribers: false } + channels.headers = { hasSubscribers: false } + channels.trailers = { hasSubscribers: false } + channels.error = { hasSubscribers: false } +} + +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.exec(path) !== null) { + throw new InvalidArgumentError('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + this.headersTimeout = headersTimeout + + this.bodyTimeout = bodyTimeout + + this.throwOnError = throwOnError === true + + this.method = method + + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body + } else if (util.isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false + + this.aborted = false + + this.upgrade = upgrade || null + + this.path = query ? util.buildURL(path, query) : path + + this.origin = origin + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent + + this.blocking = blocking == null ? false : blocking + + this.reset = reset == null ? null : reset + + this.host = null + + this.contentLength = null + + this.contentType = null + + this.headers = '' + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(this, key, headers[key]) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + if (util.isFormDataLike(this.body)) { + if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { + throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') + } + + if (!extractBody) { + extractBody = require('../fetch/body.js').extractBody + } + + const [bodyStream, contentType] = extractBody(body) + if (this.contentType == null) { + this.contentType = contentType + this.headers += `content-type: ${contentType}\r\n` + } + this.body = bodyStream.stream + } else if (util.isBlobLike(body) && this.contentType == null && body.type) { + this.contentType = body.type + this.headers += `content-type: ${body.type}\r\n` + } + + util.validateHandler(handler, method, upgrade) + + this.servername = util.getServerName(this.host) + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } + + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + this[kHandler].onBodySent(chunk) + } catch (err) { + this.onError(err) + } + } + } + + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } + } + + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onConnect(abort) + } + + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } + + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onData(chunk) + } + + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + assert(!this.aborted) + + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } + return this[kHandler].onComplete(trailers) + } + + onError (error) { + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + + if (this.aborted) { + return + } + this.aborted = true + return this[kHandler].onError(error) + } + + addHeader (key, value) { + processHeader(this, key, value) + return this + } +} + +function processHeaderValue (key, val) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + val = val != null ? `${val}` : '' + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + return `${key}: ${val}\r\n` +} + +function processHeader (request, key, val) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + if ( + request.host === null && + key.length === 4 && + key.toLowerCase() === 'host' + ) { + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + // Consumed by Client + request.host = val + } else if ( + request.contentLength === null && + key.length === 14 && + key.toLowerCase() === 'content-length' + ) { + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if ( + request.contentType === null && + key.length === 12 && + key.toLowerCase() === 'content-type' + ) { + request.contentType = val + request.headers += processHeaderValue(key, val) + } else if ( + key.length === 17 && + key.toLowerCase() === 'transfer-encoding' + ) { + throw new InvalidArgumentError('invalid transfer-encoding header') + } else if ( + key.length === 10 && + key.toLowerCase() === 'connection' + ) { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } else if (value === 'close') { + request.reset = true + } + } else if ( + key.length === 10 && + key.toLowerCase() === 'keep-alive' + ) { + throw new InvalidArgumentError('invalid keep-alive header') + } else if ( + key.length === 7 && + key.toLowerCase() === 'upgrade' + ) { + throw new InvalidArgumentError('invalid upgrade header') + } else if ( + key.length === 6 && + key.toLowerCase() === 'expect' + ) { + throw new NotSupportedError('expect header not supported') + } else if (tokenRegExp.exec(key) === null) { + throw new InvalidArgumentError('invalid header key') + } else { + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + request.headers += processHeaderValue(key, val[i]) + } + } else { + request.headers += processHeaderValue(key, val) + } + } +} + +module.exports = Request diff --git a/node_modules/undici/lib/core/symbols.js b/node_modules/undici/lib/core/symbols.js new file mode 100644 index 0000000..6d6b629 --- /dev/null +++ b/node_modules/undici/lib/core/symbols.js @@ -0,0 +1,55 @@ +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kHeadersList: Symbol('headers list'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelinig'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size') +} diff --git a/node_modules/undici/lib/core/util.js b/node_modules/undici/lib/core/util.js new file mode 100644 index 0000000..ab94bcf --- /dev/null +++ b/node_modules/undici/lib/core/util.js @@ -0,0 +1,447 @@ +'use strict' + +const assert = require('assert') +const { kDestroyed, kBodyUsed } = require('./symbols') +const { IncomingMessage } = require('http') +const stream = require('stream') +const net = require('net') +const { InvalidArgumentError } = require('./errors') +const { Blob } = require('buffer') +const nodeUtil = require('util') +const { stringify } = require('querystring') + +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + +function nop () {} + +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} + +// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) +function isBlobLike (object) { + return (Blob && object instanceof Blob) || ( + object && + typeof object === 'object' && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) +} + +function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified + } + + return url +} + +function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url) + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('invalid protocol') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('invalid url') + } + + if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { + throw new InvalidArgumentError('invalid port') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('invalid path') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('invalid pathname') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('invalid hostname') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('invalid origin') + } + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('invalid protocol') + } + + if (!(url instanceof URL)) { + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol}//${url.hostname}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` + + if (origin.endsWith('/')) { + origin = origin.substring(0, origin.length - 1) + } + + if (path && !path.startsWith('/')) { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + url = new URL(origin + path) + } + + return url +} + +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url +} + +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substr(1, idx - 1) + } + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substr(0, idx) +} + +// IP addresses are not valid server names per RFC6066 +// > Currently, the only server names supported are DNS hostnames +function getServerName (host) { + if (!host) { + return null + } + + assert.strictEqual(typeof host, 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } + + return servername +} + +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} + +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} + +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} + +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null +} + +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) +} + +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted +} + +function destroy (stream, err) { + if (!isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } + stream.destroy(err) + } else if (err) { + process.nextTick((stream, err) => { + stream.emit('error', err) + }, stream, err) + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } +} + +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} + +function parseHeaders (headers, obj = {}) { + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase() + let val = obj[key] + + const encoding = key.length === 19 && key === 'content-disposition' + ? 'latin1' + : 'utf8' + + if (!val) { + if (Array.isArray(headers[i + 1])) { + obj[key] = headers[i + 1] + } else { + obj[key] = headers[i + 1].toString(encoding) + } + } else { + if (!Array.isArray(val)) { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString(encoding)) + } + } + return obj +} + +function parseRawHeaders (headers) { + const ret = [] + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString() + + const encoding = key.length === 19 && key.toLowerCase() === 'content-disposition' + ? 'latin1' + : 'utf8' + + const val = headers[n + 1].toString(encoding) + + ret.push(key, val) + } + return ret +} + +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} + +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } + } +} + +// A body is disturbed if it has been read from and it cannot +// be re-used without losing state or data. +function isDisturbed (body) { + return !!(body && ( + stream.isDisturbed + ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? + : body[kBodyUsed] || + body.readableDidRead || + (body._readableState && body._readableState.dataEmitted) || + isReadableAborted(body) + )) +} + +function isErrored (body) { + return !!(body && ( + stream.isErrored + ? stream.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) +} + +function isReadable (body) { + return !!(body && ( + stream.isReadable + ? stream.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) +} + +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} + +let ReadableStream +function ReadableStreamFrom (iterable) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + if (ReadableStream.from) { + // https://github.com/whatwg/streams/pull/1083 + return ReadableStream.from(iterable) + } + + let iterator + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator]() + }, + async pull (controller) { + const { done, value } = await iterator.next() + if (done) { + queueMicrotask(() => { + controller.close() + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + controller.enqueue(new Uint8Array(buf)) + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + } + }, + 0 + ) +} + +// The chunk should be a FormData instance and contains +// all the required methods. +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function throwIfAborted (signal) { + if (!signal) { return } + if (typeof signal.throwIfAborted === 'function') { + signal.throwIfAborted() + } else { + if (signal.aborted) { + // DOMException not available < v17.0.0 + const err = new Error('The operation was aborted') + err.name = 'AbortError' + throw err + } + } +} + +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true + +module.exports = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString: nodeUtil.toUSVString || ((val) => `${val}`), + isReadableAborted, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + throwIfAborted, + nodeMajor, + nodeMinor, + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13) +} diff --git a/node_modules/undici/lib/dispatcher-base.js b/node_modules/undici/lib/dispatcher-base.js new file mode 100644 index 0000000..14a5c0a --- /dev/null +++ b/node_modules/undici/lib/dispatcher-base.js @@ -0,0 +1,191 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = require('./core/errors') +const { kDestroy, kClose, kDispatch, kInterceptors } = require('./core/symbols') + +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') + +class DispatcherBase extends Dispatcher { + constructor () { + super() + + this[kDestroyed] = false + this[kOnDestroyed] = [] + this[kClosed] = false + this[kOnClosed] = [] + } + + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + get interceptors () { + return this[kInterceptors] + } + + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors][i] + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError('interceptor must be an function') + } + } + } + + this[kInterceptors] = newInterceptors + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + this[kClosed] = true + this[kOnClosed].push(callback) + + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + if (!err) { + err = new ClientDestroyedError() + } + + this[kDestroyed] = true + this[kOnDestroyed].push(callback) + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) + } + + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) + } + + let dispatch = this[kDispatch].bind(this) + for (let i = this[kInterceptors].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors][i](dispatch) + } + this[kInterceptedDispatch] = dispatch + return dispatch(opts, handler) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } + + if (this[kDestroyed]) { + throw new ClientDestroyedError() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err) + + return false + } + } +} + +module.exports = DispatcherBase diff --git a/node_modules/undici/lib/dispatcher.js b/node_modules/undici/lib/dispatcher.js new file mode 100644 index 0000000..9b809d8 --- /dev/null +++ b/node_modules/undici/lib/dispatcher.js @@ -0,0 +1,19 @@ +'use strict' + +const EventEmitter = require('events') + +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } +} + +module.exports = Dispatcher diff --git a/node_modules/undici/lib/fetch/LICENSE b/node_modules/undici/lib/fetch/LICENSE new file mode 100644 index 0000000..2943500 --- /dev/null +++ b/node_modules/undici/lib/fetch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Ethan Arrowood + +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/undici/lib/fetch/body.js b/node_modules/undici/lib/fetch/body.js new file mode 100644 index 0000000..c291afa --- /dev/null +++ b/node_modules/undici/lib/fetch/body.js @@ -0,0 +1,595 @@ +'use strict' + +const Busboy = require('busboy') +const util = require('../core/util') +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = require('./util') +const { FormData } = require('./formdata') +const { kState } = require('./symbols') +const { webidl } = require('./webidl') +const { DOMException, structuredClone } = require('./constants') +const { Blob, File: NativeFile } = require('buffer') +const { kBodyUsed } = require('../core/symbols') +const assert = require('assert') +const { isErrored } = require('../core/util') +const { isUint8Array, isArrayBuffer } = require('util/types') +const { File: UndiciFile } = require('./file') +const { parseMIMEType, serializeAMimeType } = require('./dataURL') + +let ReadableStream = globalThis.ReadableStream + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile + +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream. + stream = new ReadableStream({ + async pull (controller) { + controller.enqueue( + typeof source === 'string' ? new TextEncoder().encode(source) : source + ) + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: undefined + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-${Math.random()}`.replace('.', '').slice(0, 32) + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const enc = new TextEncoder() + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = enc.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = enc.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + length += chunk.byteLength + value.size + rn.byteLength + } + } + + const chunk = enc.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = 'multipart/form-data; boundary=' + boundary + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + async pull (controller) { + const { value, done } = await iterator.next() + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + controller.enqueue(new Uint8Array(value)) + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: undefined + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = require('stream/web').ReadableStream + } + + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.') + // istanbul ignore next + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee() + const out2Clone = structuredClone(out2, { transfer: [out2] }) + // This, for whatever reasons, unrefs out2Clone which allows + // the process to exit by itself. + const [, finalClone] = out2Clone.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } +} + +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body + } else { + const stream = body.stream + + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } + + if (stream.locked) { + throw new TypeError('The stream is locked.') + } + + // Compat. + stream[kBodyUsed] = true + + yield * stream + } + } +} + +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } +} + +function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return specConsumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this) + + if (mimeType === 'failure') { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return specConsumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return specConsumeBody(this, utf8DecodeBytes, instance) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return specConsumeBody(this, parseJSONFromBytes, instance) + }, + + async formData () { + webidl.brandCheck(this, instance) + + throwIfAborted(this[kState]) + + const contentType = this.headers.get('Content-Type') + + // If mimeType’s essence is "multipart/form-data", then: + if (/multipart\/form-data/.test(contentType)) { + const headers = {} + for (const [key, value] of this.headers) headers[key.toLowerCase()] = value + + const responseFormData = new FormData() + + let busboy + + try { + busboy = Busboy({ + headers, + defParamCharset: 'utf8' + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') + } + + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, info) => { + const { filename, encoding, mimeType } = info + const chunks = [] + + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' + + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') + + const end = base64chunk.length - base64chunk.length % 4 + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) + + base64chunk = base64chunk.slice(end) + }) + value.on('end', () => { + chunks.push(Buffer.from(base64chunk, 'base64')) + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } else { + value.on('data', (chunk) => { + chunks.push(chunk) + }) + value.on('end', () => { + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } + }) + + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve) + busboy.on('error', (err) => reject(new TypeError(err))) + }) + + if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) + busboy.end() + await busboyResolve + + return responseFormData + } else if (/application\/x-www-form-urlencoded/.test(contentType)) { + // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: + + // 1. Let entries be the result of parsing bytes. + let entries + try { + let text = '' + // application/x-www-form-urlencoded parser will keep the BOM. + // https://url.spec.whatwg.org/#concept-urlencoded-parser + const textDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) + for await (const chunk of consumeBody(this[kState].body)) { + if (!isUint8Array(chunk)) { + throw new TypeError('Expected Uint8Array chunk') + } + text += textDecoder.decode(chunk, { stream: true }) + } + text += textDecoder.decode() + entries = new URLSearchParams(text) + } catch (err) { + // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. + // 2. If entries is failure, then throw a TypeError. + throw Object.assign(new TypeError(), { cause: err }) + } + + // 3. Return a new FormData object whose entries are entries. + const formData = new FormData() + for (const [name, value] of entries) { + formData.append(name, value) + } + return formData + } else { + // Wait a tick before checking if the request has been aborted. + // Otherwise, a TypeError can be thrown when an AbortError should. + await Promise.resolve() + + throwIfAborted(this[kState]) + + // Otherwise, throw a TypeError. + throw webidl.errors.exception({ + header: `${instance.name}.formData`, + message: 'Could not parse content as FormData.' + }) + } + } + } + + return methods +} + +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ +async function specConsumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance) + + throwIfAborted(object[kState]) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') + } + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error) + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) + } + } + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(new Uint8Array()) + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + fullyReadBody(object[kState].body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +// https://fetch.spec.whatwg.org/#body-unusable +function bodyUnusable (body) { + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = new TextDecoder().decode(buffer) + + // 4. Return output. + return output +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} object + */ +function bodyMimeType (object) { + const { headersList } = object[kState] + const contentType = headersList.get('content-type') + + if (contentType === null) { + return 'failure' + } + + return parseMIMEType(contentType) +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody +} diff --git a/node_modules/undici/lib/fetch/constants.js b/node_modules/undici/lib/fetch/constants.js new file mode 100644 index 0000000..bc90a03 --- /dev/null +++ b/node_modules/undici/lib/fetch/constants.js @@ -0,0 +1,130 @@ +'use strict' + +const { MessageChannel, receiveMessageOnPort } = require('worker_threads') + +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] + +const nullBodyStatus = [101, 204, 205, 304] + +const redirectStatus = [301, 302, 303, 307, 308] + +// https://fetch.spec.whatwg.org/#block-bad-port +const badPorts = [ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', + '10080' +] + +// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies +const referrerPolicy = [ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +] + +const requestRedirect = ['follow', 'manual', 'error'] + +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] + +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + +const requestCredentials = ['omit', 'same-origin', 'include'] + +const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +] + +const requestBodyHeader = [ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type' +] + +// https://fetch.spec.whatwg.org/#enumdef-requestduplex +const requestDuplex = [ + 'half' +] + +// http://fetch.spec.whatwg.org/#forbidden-method +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] + +const subresource = [ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +] + +/** @type {globalThis['DOMException']} */ +const DOMException = globalThis.DOMException ?? (() => { + // DOMException was only made a global in Node v17.0.0, + // but fetch supports >= v16.8. + try { + atob('~') + } catch (err) { + return Object.getPrototypeOf(err).constructor + } +})() + +let channel + +/** @type {globalThis['structuredClone']} */ +const structuredClone = + globalThis.structuredClone ?? + // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js + // structuredClone was added in v17.0.0, but fetch supports v16.8 + function structuredClone (value, options = undefined) { + if (arguments.length === 0) { + throw new TypeError('missing argument') + } + + if (!channel) { + channel = new MessageChannel() + } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message + } + +module.exports = { + DOMException, + structuredClone, + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex +} diff --git a/node_modules/undici/lib/fetch/dataURL.js b/node_modules/undici/lib/fetch/dataURL.js new file mode 100644 index 0000000..beefad1 --- /dev/null +++ b/node_modules/undici/lib/fetch/dataURL.js @@ -0,0 +1,573 @@ +const assert = require('assert') +const { atob } = require('buffer') +const { isValidHTTPToken, isomorphicDecode } = require('./util') + +const encoder = new TextEncoder() + +// Regex +const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-z0-9]+$/ +const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line +// https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point +const HTTP_QUOTED_STRING_TOKENS = /^(\u0009|\x{0020}-\x{007E}|\x{0080}-\x{00FF})+$/ // eslint-disable-line + +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) + + // 3. Remove the leading "data:" string from input. + input = input.slice(5) + + // 4. Let position point at the start of input. + const position = { position: 0 } + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Note: This will only remove U+0020 SPACE code + // points, if any. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = mimeType.replace(/^(\u0020)+|(\u0020)+$/g, '') + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++ + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} + +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + const href = url.href + + if (!excludeFragment) { + return href + } + + const hash = href.lastIndexOf('#') + if (hash === -1) { + return href + } + return href.slice(0, hash) +} + +// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] + + // 2. Advance position by 1. + position.position++ + } + + // 3. Return result. + return result +} + +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position + + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + // 1. Let output be an empty byte sequence. + /** @type {number[]} */ + const output = [] + + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) + ) { + output.push(0x25) + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) + const bytePoint = Number.parseInt(nextTwoBytes, 16) + + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) + + // 3. Skip the next two bytes in input. + i += 2 + } + } + + // 3. Return output. + return Uint8Array.from(output) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = input.trim() + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = subtype.trimEnd() + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: type.toLowerCase(), + subtype: subtype.toLowerCase(), + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${type}/${subtype}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + // Note: it says "trailing" whitespace; leading is fine. + parameterValue = parameterValue.trimEnd() + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + !HTTP_QUOTED_STRING_TOKENS.test(parameterValue) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } + } + + // 12. Return mimeType. + return mimeType +} + +// https://infra.spec.whatwg.org/#forgiving-base64-decode +/** @param {string} data */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line + + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (data.length % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + data = data.replace(/=?=$/, '') + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (data.length % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data)) { + return 'failure' + } + + const binary = atob(data) + const bytes = new Uint8Array(binary.length) + + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) + } + + return bytes +} + +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ +function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position + + // 2. Let value be the empty string. + let value = '' + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + + // 4. Advance position by 1. + position.position++ + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] + + // 4. Advance position by 1. + position.position++ + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position] + + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} + +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { type, subtype, parameters } = mimeType + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = `${type}/${subtype}` + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' + + // 2. Append name to serialization. + serialization += name + + // 3. Append U+003D (=) to serialization. + serialization += '=' + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!isValidHTTPToken(value)) { + // 1. Precede each occurence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value + } + + // 3. Return serialization. + return serialization +} + +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} diff --git a/node_modules/undici/lib/fetch/file.js b/node_modules/undici/lib/fetch/file.js new file mode 100644 index 0000000..81bb7b2 --- /dev/null +++ b/node_modules/undici/lib/fetch/file.js @@ -0,0 +1,343 @@ +'use strict' + +const { Blob, File: NativeFile } = require('buffer') +const { types } = require('util') +const { kState } = require('./symbols') +const { isBlobLike } = require('./util') +const { webidl } = require('./webidl') +const { parseMIMEType, serializeAMimeType } = require('./dataURL') +const { kEnumerableProperty } = require('../core/util') + +class File extends Blob { + constructor (fileBits, fileName, options = {}) { + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) + + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // 2. Convert every character in t to ASCII lowercase. + let t = options.type + let d + + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) + + if (t === 'failure') { + t = '' + // eslint-disable-next-line no-labels + break substep + } + + t = serializeAMimeType(t).toLowerCase() + } + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + d = options.lastModified + } + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t + } + } + + get name () { + webidl.brandCheck(this, File) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, File) + + return this[kState].lastModified + } + + get type () { + webidl.brandCheck(this, File) + + return this[kState].type + } +} + +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check + + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type + + // 2. Convert every character in t to ASCII lowercase. + // TODO + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now() + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } + + stream (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.stream(...args) + } + + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.arrayBuffer(...args) + } + + slice (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.slice(...args) + } + + text (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.text(...args) + } + + get size () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.size + } + + get type () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.type + } + + get name () { + webidl.brandCheck(this, FileLike) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, FileLike) + + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } +} + +Object.defineProperties(File.prototype, { + [Symbol.toStringTag]: { + value: 'File', + configurable: true + }, + name: kEnumerableProperty, + lastModified: kEnumerableProperty +}) + +webidl.converters.Blob = webidl.interfaceConverter(Blob) + +webidl.converters.BlobPart = function (V, opts) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) + ) { + return webidl.converters.BufferSource(V, opts) + } + } + + return webidl.converters.USVString(V, opts) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.BlobPart +) + +// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag +webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ + { + key: 'lastModified', + converter: webidl.converters['long long'], + get defaultValue () { + return Date.now() + } + }, + { + key: 'type', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'endings', + converter: (value) => { + value = webidl.converters.DOMString(value) + value = value.toLowerCase() + + if (value !== 'native') { + value = 'transparent' + } + + return value + }, + defaultValue: 'transparent' + } +]) + +/** + * @see https://www.w3.org/TR/FileAPI/#process-blob-parts + * @param {(NodeJS.TypedArray|Blob|string)[]} parts + * @param {{ type: string, endings: string }} options + */ +function processBlobParts (parts, options) { + // 1. Let bytes be an empty sequence of bytes. + /** @type {NodeJS.TypedArray[]} */ + const bytes = [] + + // 2. For each element in parts: + for (const element of parts) { + // 1. If element is a USVString, run the following substeps: + if (typeof element === 'string') { + // 1. Let s be element. + let s = element + + // 2. If the endings member of options is "native", set s + // to the result of converting line endings to native + // of element. + if (options.endings === 'native') { + s = convertLineEndingsNative(s) + } + + // 3. Append the result of UTF-8 encoding s to bytes. + bytes.push(new TextEncoder().encode(s)) + } else if ( + types.isAnyArrayBuffer(element) || + types.isTypedArray(element) + ) { + // 2. If element is a BufferSource, get a copy of the + // bytes held by the buffer source, and append those + // bytes to bytes. + if (!element.buffer) { // ArrayBuffer + bytes.push(new Uint8Array(element)) + } else { + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ) + } + } else if (isBlobLike(element)) { + // 3. If element is a Blob, append the bytes it represents + // to bytes. + bytes.push(element) + } + } + + // 3. Return bytes. + return bytes +} + +/** + * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native + * @param {string} s + */ +function convertLineEndingsNative (s) { + // 1. Let native line ending be be the code point U+000A LF. + let nativeLineEnding = '\n' + + // 2. If the underlying platform’s conventions are to + // represent newlines as a carriage return and line feed + // sequence, set native line ending to the code point + // U+000D CR followed by the code point U+000A LF. + if (process.platform === 'win32') { + nativeLineEnding = '\r\n' + } + + return s.replace(/\r?\n/g, nativeLineEnding) +} + +// If this function is moved to ./util.js, some tools (such as +// rollup) will warn about circular dependencies. See: +// https://github.com/nodejs/undici/issues/1629 +function isFileLike (object) { + return ( + (NativeFile && object instanceof NativeFile) || + object instanceof File || ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) +} + +module.exports = { File, FileLike, isFileLike } diff --git a/node_modules/undici/lib/fetch/formdata.js b/node_modules/undici/lib/fetch/formdata.js new file mode 100644 index 0000000..a957a80 --- /dev/null +++ b/node_modules/undici/lib/fetch/formdata.js @@ -0,0 +1,272 @@ +'use strict' + +const { isBlobLike, toUSVString, makeIterator } = require('./util') +const { kState } = require('./symbols') +const { File: UndiciFile, FileLike, isFileLike } = require('./file') +const { webidl } = require('./webidl') +const { Blob, File: NativeFile } = require('buffer') + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile + +// https://xhr.spec.whatwg.org/#formdata +class FormData { + constructor (form) { + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + + this[kState] = [] + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? webidl.converters.USVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) + + // 3. Append entry to this’s entry list. + this[kState].push(entry) + } + + delete (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) + + name = webidl.converters.USVString(name) + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + const next = [] + for (const entry of this[kState]) { + if (entry.name !== name) { + next.push(entry) + } + } + + this[kState] = next + } + + get (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) + + name = webidl.converters.USVString(name) + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? toUSVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry) + } + } + + entries () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) + } + + keys () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key' + ) + } + + values () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' + ) + } + + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } +} + +FormData.prototype[Symbol.iterator] = FormData.prototype.entries + +Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // "To convert a string into a scalar value string, replace any surrogates + // with U+FFFD." + // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end + name = Buffer.from(name).toString('utf8') + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + value = Buffer.from(value).toString('utf8') + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }) + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + } + + value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile + ? new File([value], filename, options) + : new FileLike(value, filename, options) + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} + +module.exports = { FormData } diff --git a/node_modules/undici/lib/fetch/global.js b/node_modules/undici/lib/fetch/global.js new file mode 100644 index 0000000..42282ac --- /dev/null +++ b/node_modules/undici/lib/fetch/global.js @@ -0,0 +1,48 @@ +'use strict' + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if ( + newOrigin !== undefined && + typeof newOrigin !== 'string' && + !(newOrigin instanceof URL) + ) { + throw new Error('Invalid base url') + } + + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return + } + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} + +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} diff --git a/node_modules/undici/lib/fetch/headers.js b/node_modules/undici/lib/fetch/headers.js new file mode 100644 index 0000000..5093ef8 --- /dev/null +++ b/node_modules/undici/lib/fetch/headers.js @@ -0,0 +1,549 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { kHeadersList } = require('../core/symbols') +const { kGuard, kHeadersCaseInsensitive } = require('./symbols') +const { kEnumerableProperty } = require('../core/util') +const { + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = require('./util') +const { webidl } = require('./webidl') +const assert = require('assert') + +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + + // Trimming the end with `.replace()` and a RegExp is typically subject to + // ReDoS. This is safer and faster. + let i = potentialValue.length + while (/[\r\n\t ]/.test(potentialValue.charAt(--i))); + return potentialValue.slice(0, i + 1).replace(/^[\r\n\t ]+/, '') +} + +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (const header of object) { + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + headers.append(header[0], header[1]) + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + for (const [key, value] of Object.entries(object)) { + headers.append(key, value) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } +} + +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]) + this[kHeadersSortedMap] = init[kHeadersSortedMap] + this.cookies = init.cookies + } else { + this[kHeadersMap] = new Map(init) + this[kHeadersSortedMap] = null + } + } + + // https://fetch.spec.whatwg.org/#header-list-contains + contains (name) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + name = name.toLowerCase() + + return this[kHeadersMap].has(name) + } + + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + } + + // https://fetch.spec.whatwg.org/#concept-header-list-append + append (name, value) { + this[kHeadersSortedMap] = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = name.toLowerCase() + const exists = this[kHeadersMap].get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + this.cookies ??= [] + this.cookies.push(value) + } + } + + // https://fetch.spec.whatwg.org/#concept-header-list-set + set (name, value) { + this[kHeadersSortedMap] = null + const lowercaseName = name.toLowerCase() + + if (lowercaseName === 'set-cookie') { + this.cookies = [value] + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + return this[kHeadersMap].set(lowercaseName, { name, value }) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-delete + delete (name) { + this[kHeadersSortedMap] = null + + name = name.toLowerCase() + + if (name === 'set-cookie') { + this.cookies = null + } + + return this[kHeadersMap].delete(name) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-get + get (name) { + // 1. If list does not contain name, then return null. + if (!this.contains(name)) { + return null + } + + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return this[kHeadersMap].get(name.toLowerCase())?.value ?? null + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] + } + } + + get [kHeadersCaseInsensitive] () { + /** @type {string[]} */ + const flatList = [] + + for (const { name, value } of this[kHeadersMap].values()) { + flatList.push(name, value) + } + + return flatList + } +} + +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + constructor (init = undefined) { + this[kHeadersList] = new HeadersList() + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this[kGuard] = 'none' + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init) + fill(this, init) + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers + return this[kHeadersList].append(name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + return this[kHeadersList].delete(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.get', + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.has', + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this[kHeadersList].contains(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + return this[kHeadersList].set(name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this[kHeadersList].cookies + + if (list) { + return [...list] + } + + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) + const cookies = this[kHeadersList].cookies + + // 3. For each name of names: + for (const [name, value] of names) { + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (const value of cookies) { + headers.push([name, value]) + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + assert(value !== null) + + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } + + this[kHeadersList][kHeadersSortedMap] = headers + + // 4. Return headers. + return headers + } + + keys () { + webidl.brandCheck(this, Headers) + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } + + values () { + webidl.brandCheck(this, Headers) + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } + + entries () { + webidl.brandCheck(this, Headers) + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) + } + + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } + + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) + + return this[kHeadersList] + } +} + +Headers.prototype[Symbol.iterator] = Headers.prototype.entries + +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + keys: kEnumerableProperty, + values: kEnumerableProperty, + entries: kEnumerableProperty, + forEach: kEnumerableProperty, + [Symbol.iterator]: { enumerable: false }, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + } +}) + +webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) + } + + return webidl.converters['record'](V) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} + +module.exports = { + fill, + Headers, + HeadersList +} diff --git a/node_modules/undici/lib/fetch/index.js b/node_modules/undici/lib/fetch/index.js new file mode 100644 index 0000000..e3834a7 --- /dev/null +++ b/node_modules/undici/lib/fetch/index.js @@ -0,0 +1,2104 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = require('./response') +const { Headers } = require('./headers') +const { Request, makeRequest } = require('./request') +const zlib = require('zlib') +const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode +} = require('./util') +const { kState, kHeaders, kGuard, kRealm, kHeadersCaseInsensitive } = require('./symbols') +const assert = require('assert') +const { safelyExtractBody } = require('./body') +const { + redirectStatus, + nullBodyStatus, + safeMethods, + requestBodyHeader, + subresource, + DOMException +} = require('./constants') +const { kHeadersList } = require('../core/symbols') +const EE = require('events') +const { Readable, pipeline } = require('stream') +const { isErrored, isReadable, nodeMajor, nodeMinor } = require('../core/util') +const { dataURLProcessor, serializeAMimeType } = require('./dataURL') +const { TransformStream } = require('stream/web') +const { getGlobalDispatcher } = require('../global') +const { webidl } = require('./webidl') +const { STATUS_CODES } = require('http') + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + // 2 terminated listeners get added per request, + // but only 1 gets removed. If there are 20 redirects, + // 21 listeners will be added. + // See https://github.com/nodejs/undici/issues/1711 + // TODO (fix): Find and fix root cause for leaked listener. + this.setMaxListeners(21) + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted' + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error + + this.connection?.destroy(error) + this.emit('terminated', error) + } +} + +// https://fetch.spec.whatwg.org/#fetch-method +async function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) + + // 1. Let p be a new promise. + const p = createDeferredPromise() + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject + + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = requestObject[kState] + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } + + // 7. Let responseObject be null. + let responseObject = null + + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null + + // 9. Let locallyAborted be false. + let locallyAborted = false + + // 10. Let controller be null. + let controller = null + + // 11. Add the following abort steps to requestObject’s signal: + requestObject.signal.addEventListener( + 'abort', + () => { + // 1. Set locallyAborted to true. + locallyAborted = true + + // 2. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason) + + // 3. If controller is not null, then abort controller. + if (controller != null) { + controller.abort() + } + }, + { once: true } + ) + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch') + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject( + Object.assign(new TypeError('fetch failed'), { cause: response.error }) + ) + return + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new Response() + responseObject[kState] = response + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + + // 5. Resolve p with responseObject. + p.resolve(responseObject) + } + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) + + // 14. Return p. + return p.promise +} + +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!/^https?:/.test(originalURL.protocol)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!timingInfo.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { + if (nodeMajor >= 18 && nodeMinor >= 2) { + performance.markResourceTiming(timingInfo, originalURL, initiatorType, globalThis, cacheState) + } +} + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // Note: AbortSignal.reason was added in node v17.2.0 + // which would give us an undefined error to reject with. + // Remove this once node v16 is no longer supported. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 1. Reject promise with error. + p.reject(error) + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = responseObject[kState] + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } +} + +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher // undici +}) { + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currenTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + // TODO: What if request.client is null? + request.origin = request.client?.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value) + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language')) { + request.headersList.append('accept-language', '*') + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } + + // 15. If request is a subresource request, then: + if (subresource.includes(request.destination)) { + // TODO + } + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) + + // 17. Return fetchParam's controller + return fetchParams.controller +} + +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if ( + request.localURLsOnly && + !/^(about|blob|data):/.test(requestCurrentURL(request).protocol) + ) { + response = makeNetworkError('local URLs only') + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request) + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } + + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } + + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' + + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!/^https?:/.test(requestCurrentURL(request).protocol)) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' + + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range') + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } +} + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +async function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return makeNetworkError('about scheme is not supported') + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = require('buffer').resolveObjectURL + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return makeNetworkError('NetworkError when attempting to fetch resource.') + } + + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { + return makeNetworkError('invalid method') + } + + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) + + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] + + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) + + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' + + // 7. Return a new response whose status message is `OK`, header list is + // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. + const response = makeResponse({ + statusText: 'OK', + headersList: [ + ['content-length', { name: 'Content-Length', value: length }], + ['content-type', { name: 'Content-Type', value: type }] + ] + }) + + response.body = body + + return response + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return makeNetworkError('failed to fetch the data URL') + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + }) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return makeNetworkError('not implemented... yet...') + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return await httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return makeNetworkError('unknown scheme') + } + } +} + +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) + } +} + +// https://fetch.spec.whatwg.org/#fetch-finale +async function fetchFinale (fetchParams, response) { + // 1. If response is a network error, then: + if (response.type === 'error') { + // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». + response.urlList = [fetchParams.request.urlList[0]] + + // 2. Set response’s timing info to the result of creating an opaque timing + // info for fetchParams’s timing info. + response.timingInfo = createOpaqueTimingInfo({ + startTime: fetchParams.timingInfo.startTime + }) + } + + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // If fetchParams’s process response end-of-body is not null, + // then queue a fetch task to run fetchParams’s process response + // end-of-body given response with fetchParams’s task destination. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + } + + // 3. If fetchParams’s process response is non-null, then queue a fetch task + // to run fetchParams’s process response given response, with fetchParams’s + // task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => fetchParams.processResponse(response)) + } + + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: + + // 1. Let transformStream be a new a TransformStream. + + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) + } + + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm + // and flushAlgorithm set to processResponseEndOfBody. + const transformStream = new TransformStream({ + start () {}, + transform: identityTransformAlgorithm, + flush: processResponseEndOfBody + }, { + size () { + return 1 + } + }, { + size () { + return 1 + } + }) + + // 4. Set response’s body to the result of piping response’s body through transformStream. + response.body = { stream: response.body.stream.pipeThrough(transformStream) } + } + + // 6. If fetchParams’s process response consume body is non-null, then: + if (fetchParams.processResponseConsumeBody != null) { + // 1. Let processBody given nullOrBytes be this step: run fetchParams’s + // process response consume body given response and nullOrBytes. + const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) + + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) + + // 3. If response’s body is null, then queue a fetch task to run processBody + // given null, with fetchParams’s task destination. + if (response.body == null) { + queueMicrotask(() => processBody(null)) + } else { + // 4. Otherwise, fully read response’s body given processBody, processBodyError, + // and fetchParams’s task destination. + await fullyReadBody(response.body, processBody, processBodyError) + } + } +} + +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let actualResponse be null. + let actualResponse = null + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatus.includes(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy() + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-redirect-fetch +async function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return makeNetworkError(err) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!/^https?:/.test(locationURL.protocol)) { + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return makeNetworkError('redirect count exceeded') + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return makeNetworkError('cross origin not allowed for request mode "cors"') + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + ) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return makeNetworkError() + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !['GET', 'HEAD'].includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization') + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source) + request.body = safelyExtractBody(request.body.source)[0] + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent')) { + httpRequest.headersList.append('user-agent', 'undici') + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since') || + httpRequest.headersList.contains('if-none-match') || + httpRequest.headersList.contains('if-unmodified-since') || + httpRequest.headersList.contains('if-match') || + httpRequest.headersList.contains('if-range')) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control') + ) { + httpRequest.headersList.append('cache-control', 'max-age=0') + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma')) { + httpRequest.headersList.append('pragma', 'no-cache') + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control')) { + httpRequest.headersList.append('cache-control', 'no-cache') + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range')) { + httpRequest.headersList.append('accept-encoding', 'identity') + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding')) { + if (/^https:/.test(requestCurrentURL(httpRequest).protocol)) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate') + } + } + + // 20. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + // 2. If httpRequest’s header list does not contain `Authorization`, then: + // TODO: credentials + } + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache + } + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.mode === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethods.includes(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } + + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err) { + if (!this.destroyed) { + this.destroyed = true + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) + } + } + } + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } + + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO + + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO + } + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) + } + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) + } + processEndOfBody() + } catch (err) { + processBodyError(err) + } + })() + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() + + response = makeResponse({ status, statusText, headersList }) + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() + } + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason) + } + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to + // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller + }, + async pull (controller) { + await pullAlgorithm(controller) + }, + async cancel (reason) { + await cancelAlgorithm(reason) + } + }, + { + highWaterMark: 0, + size () { + return 1 + } + } + ) + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream } + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.on('terminated', onAborted) + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + try { + const { done, value } = await fetchParams.controller.next() + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) + + finalizeResponse(fetchParams, response) + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isErrorLike(bytes)) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } + } + } + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() + } + + // 20. Return response. + return response + + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body, + headers: request.headersList[kHeadersCaseInsensitive], + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + }, + + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } + + let codings = [] + let location = '' + + const headers = new Headers() + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + + if (key.toLowerCase() === 'content-encoding') { + codings = val.split(',').map((x) => x.trim()) + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers.append(key, val) + } + + this.body = new Readable({ read: resume }) + + const decoders = [] + + const willFollow = request.redirect === 'follow' && + location && + redirectStatus.includes(status) + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + for (const coding of codings) { + if (/(x-)?gzip/.test(coding)) { + decoders.push(zlib.createGunzip()) + } else if (/(x-)?deflate/.test(coding)) { + decoders.push(zlib.createInflate()) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress()) + } else { + decoders.length = 0 + break + } + } + } + + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + fetchParams.controller.ended = true + + this.body.push(null) + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + this.body?.destroy(error) + + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } + + const headers = new Headers() + + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + + headers.append(key, val) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }) + + return true + } + } + )) + } +} + +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming +} diff --git a/node_modules/undici/lib/fetch/request.js b/node_modules/undici/lib/fetch/request.js new file mode 100644 index 0000000..080a5d7 --- /dev/null +++ b/node_modules/undici/lib/fetch/request.js @@ -0,0 +1,924 @@ +/* globals AbortController */ + +'use strict' + +const { extractBody, mixinBody, cloneBody } = require('./body') +const { Headers, fill: fillHeaders, HeadersList } = require('./headers') +const { FinalizationRegistry } = require('../compat/dispatcher-weakref')() +const util = require('../core/util') +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer +} = require('./util') +const { + forbiddenMethods, + corsSafeListedMethods, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = require('./constants') +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = require('./symbols') +const { webidl } = require('./webidl') +const { getGlobalOrigin } = require('./global') +const { URLSerializer } = require('./dataURL') +const { kHeadersList } = require('../core/symbols') +const assert = require('assert') +const { setMaxListeners, getEventListeners, defaultMaxListeners } = require('events') + +let TransformStream = globalThis.TransformStream + +const kInit = Symbol('init') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) + +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kInit) { + return + } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) + + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) + + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() + } + } + + // 1. Let request be null. + let request = null + + // 2. Let fallbackMode be null. + let fallbackMode = null + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl + + // 4. Let signal be null. + let signal = null + + // 5. If input is a string, then: + if (typeof input === 'string') { + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request) + + // 8. Set request to input’s request. + request = input[kState] + + // 9. Set signal to input’s signal. + signal = input[kSignal] + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin + + // 8. Let window be "client". + let window = 'client' + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window !== undefined && init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if (init.window !== undefined) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: this[kRealm].settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) + + // 13. If init is not empty, then: + if (Object.keys(init).length > 0) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false + + // 4. Set request’s origin to "client". + request.origin = 'client' + + // 5. Set request’s referrer to "client" + request.referrer = 'client' + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // parsedReferrer’s cannot-be-a-base-URL is true, scheme is "about", + // and path contains a single string "client" + // parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + // TODO + + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity !== undefined && init.integrity != null) { + request.integrity = String(init.integrity) + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method + + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(init.method)) { + throw TypeError(`'${init.method}' is not a valid HTTP method.`) + } + + if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) { + throw TypeError(`'${init.method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + method = normalizeMethod(init.method) + + // 4. Set request’s method to method. + request.method = method + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } + + // 27. Set this’s request to request. + this[kState] = request + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + const ac = new AbortController() + this[kSignal] = ac.signal + this[kSignal][kRealm] = this[kRealm] + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } + + if (signal.aborted) { + ac.abort(signal.reason) + } else { + const abort = function () { + ac.abort(this.reason) + } + + // Third-party AbortControllers may not work with these. + // See https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619 + try { + if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(100, signal) + } + } catch {} + + signal.addEventListener('abort', abort, { once: true }) + requestFinalizer.register(this, { signal, abort }) + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers() + this[kHeaders][kHeadersList] = request.headersList + this[kHeaders][kGuard] = 'request' + this[kHeaders][kRealm] = this[kRealm] + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethods.includes(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' + } + + // 32. If init is not empty, then: + if (Object.keys(init).length !== 0) { + // 1. Let headers be a copy of this’s headers and its associated header + // list. + let headers = new Headers(this[kHeaders]) + + // 2. If init["headers"] exists, then set headers to init["headers"]. + if (init.headers !== undefined) { + headers = init.headers + } + + // 3. Empty this’s headers’s header list. + this[kHeaders][kHeadersList].clear() + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers.constructor.name === 'Headers') { + for (const [key, val] of headers) { + this[kHeaders].append(key, val) + } + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers) + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + ((init.body !== undefined && init.body != null) || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null + + // 36. If init["body"] exists and is non-null, then: + if (init.body !== undefined && init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { + this[kHeaders].append('content-type', contentType) + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = require('stream/web').TransformStream + } + + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } + } + + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) + + // The method getter steps are to return this’s request’s method. + return this[kState].method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) + + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) + + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) + + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) + + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) + + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-foward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) + + // The signal getter steps are to return this’s signal. + return this[kSignal] + } + + get body () { + webidl.brandCheck(this, Request) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request) + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + const clonedRequestObject = new Request(kInit) + clonedRequestObject[kState] = clonedRequest + clonedRequestObject[kRealm] = this[kRealm] + clonedRequestObject[kHeaders] = new Headers() + clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList + clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + this.signal.addEventListener( + 'abort', + () => { + ac.abort(this.signal.reason) + }, + { once: true } + ) + } + clonedRequestObject[kSignal] = ac.signal + + // 4. Return clonedRequestObject. + return clonedRequestObject + } +} + +mixinBody(Request) + +function makeRequest (init) { + // https://fetch.spec.whatwg.org/#requests + const request = { + method: 'GET', + localURLsOnly: false, + unsafeRequest: false, + body: null, + client: null, + reservedClient: null, + replacesClientId: '', + window: 'client', + keepalive: false, + serviceWorkers: 'all', + initiator: '', + destination: '', + priority: null, + origin: 'client', + policyContainer: 'client', + referrer: 'client', + referrerPolicy: '', + mode: 'no-cors', + useCORSPreflightFlag: false, + credentials: 'same-origin', + useCredentials: false, + cache: 'default', + redirect: 'follow', + integrity: '', + cryptoGraphicsNonceMetadata: '', + parserMetadata: '', + reloadNavigation: false, + historyNavigation: false, + userActivation: false, + taintedOrigin: false, + redirectCount: 0, + responseTainting: 'basic', + preventNoCacheCacheControlHeaderModification: false, + done: false, + timingAllowFailed: false, + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } + request.url = request.urlList[0] + return request +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body) + } + + // 3. Return newRequest. + return newRequest +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } +}) + +webidl.converters.Request = webidl.interfaceConverter( + Request +) + +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (V instanceof Request) { + return webidl.converters.Request(V) + } + + return webidl.converters.USVString(V) +} + +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) + +// https://fetch.spec.whatwg.org/#requestinit +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + } +]) + +module.exports = { Request, makeRequest } diff --git a/node_modules/undici/lib/fetch/response.js b/node_modules/undici/lib/fetch/response.js new file mode 100644 index 0000000..0973211 --- /dev/null +++ b/node_modules/undici/lib/fetch/response.js @@ -0,0 +1,575 @@ +'use strict' + +const { Headers, HeadersList, fill } = require('./headers') +const { extractBody, cloneBody, mixinBody } = require('./body') +const util = require('../core/util') +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode +} = require('./util') +const { + redirectStatus, + nullBodyStatus, + DOMException +} = require('./constants') +const { kState, kHeaders, kGuard, kRealm } = require('./symbols') +const { webidl } = require('./webidl') +const { FormData } = require('./formdata') +const { getGlobalOrigin } = require('./global') +const { URLSerializer } = require('./dataURL') +const { kHeadersList } = require('../core/symbols') +const assert = require('assert') +const { types } = require('util') + +const ReadableStream = globalThis.ReadableStream || require('stream/web').ReadableStream + +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} } + + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = new Response() + responseObject[kState] = makeNetworkError() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data = undefined, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = new TextEncoder('utf-8').encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const relevantRealm = { settingsObject: {} } + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'response' + responseObject[kHeaders][kRealm] = relevantRealm + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + const relevantRealm = { settingsObject: {} } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) + + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, getGlobalOrigin()) + } catch (err) { + throw Object.assign(new TypeError('Failed to parse URL from ' + url), { + cause: err + }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatus.includes(status)) { + throw new RangeError('Invalid status code ' + status) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) + } + + init = webidl.converters.ResponseInit(init) + + // TODO + this[kRealm] = { settingsObject: {} } + + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers() + this[kHeaders][kGuard] = 'response' + this[kHeaders][kHeadersList] = this[kState].headersList + this[kHeaders][kRealm] = this[kRealm] + + // 3. Let bodyWithType be null. + let bodyWithType = null + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) + + // The type getter steps are to return this’s response’s type. + return this[kState].type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) + + const urlList = this[kState].urlList + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) + + // The status getter steps are to return this’s response’s status. + return this[kState].status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) + + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + get body () { + webidl.brandCheck(this, Response) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || (this.body && this.body.locked)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + const clonedResponseObject = new Response() + clonedResponseObject[kState] = clonedResponse + clonedResponseObject[kRealm] = this[kRealm] + clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList + clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + return clonedResponseObject + } +} + +mixinBody(Response) + +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } +}) + +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) + +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body) + } + + // 4. Return newResponse. + return newResponse +} + +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList(), + urlList: init.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason, { + cause: isError ? reason : undefined + }), + aborted: reason && reason.name === 'AbortError' + }) +} + +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} + +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(new DOMException('The operation was aborted.', 'AbortError')) + : makeNetworkError('Request was cancelled.') +} + +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kState].headersList, init.headers) + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: 'Invalid response status code ' + response.status + }) + } + + // 2. Set response's body to body's body. + response[kState].body = body.body + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('Content-Type')) { + response[kState].headersList.append('content-type', body.type) + } + } +} + +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) + +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) + +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) + +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + types.isAnyArrayBuffer(V) || + types.isTypedArray(V) || + types.isDataView(V) + ) { + return webidl.converters.BufferSource(V) + } + + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) + } + + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) + } + + return webidl.converters.DOMString(V) +} + +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V) +} + +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) + +module.exports = { + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response +} diff --git a/node_modules/undici/lib/fetch/symbols.js b/node_modules/undici/lib/fetch/symbols.js new file mode 100644 index 0000000..e841ac7 --- /dev/null +++ b/node_modules/undici/lib/fetch/symbols.js @@ -0,0 +1,11 @@ +'use strict' + +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm'), + kHeadersCaseInsensitive: Symbol('headers case insensitive') +} diff --git a/node_modules/undici/lib/fetch/util.js b/node_modules/undici/lib/fetch/util.js new file mode 100644 index 0000000..2d8977f --- /dev/null +++ b/node_modules/undici/lib/fetch/util.js @@ -0,0 +1,992 @@ +'use strict' + +const { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = require('./constants') +const { getGlobalOrigin } = require('./global') +const { performance } = require('perf_hooks') +const { isBlobLike, toUSVString, ReadableStreamFrom } = require('../core/util') +const assert = require('assert') +const { isUint8Array } = require('util/types') + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto + +try { + crypto = require('crypto') +} catch { + +} + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatus.includes(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location') + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + location = new URL(location, responseURL(response)) + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } + + // 5. Return location. + return location +} + +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} + +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (/^https?:/.test(url.protocol) && badPorts.includes(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' +} + +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} + +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true +} + +function isTokenChar (c) { + return !( + c >= 0x7f || + c <= 0x20 || + c === '(' || + c === ')' || + c === '<' || + c === '>' || + c === '@' || + c === ',' || + c === ';' || + c === ':' || + c === '\\' || + c === '"' || + c === '/' || + c === '[' || + c === ']' || + c === '?' || + c === '=' || + c === '{' || + c === '}' + ) +} + +// See RFC 7230, Section 3.2.6. +// https://github.com/chromium/chromium/blob/d7da0240cae77824d1eda25745c4022757499131/third_party/blink/renderer/platform/network/http_parsers.cc#L321 +function isValidHTTPToken (characters) { + if (!characters || typeof characters !== 'string') { + return false + } + for (let i = 0; i < characters.length; ++i) { + const c = characters.charCodeAt(i) + if (c > 0x7f || !isTokenChar(c)) { + return false + } + } + return true +} + +// https://fetch.spec.whatwg.org/#header-name +// https://github.com/chromium/chromium/blob/b3d37e6f94f87d59e44662d6078f6a12de845d17/net/http/http_util.cc#L342 +function isValidHeaderName (potentialValue) { + if (potentialValue.length === 0) { + return false + } + + return isValidHTTPToken(potentialValue) +} + +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + if ( + potentialValue.startsWith('\t') || + potentialValue.startsWith(' ') || + potentialValue.endsWith('\t') || + potentialValue.endsWith(' ') + ) { + return false + } + + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false + } + + return true +} + +// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = '' + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.includes(token)) { + policy = token + break + } + } + } + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} + +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} + +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} + +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} + +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header) + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} + +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. + let serializedOrigin = request.origin + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + if (serializedOrigin) { + request.headersList.append('origin', serializedOrigin) + } + + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. + if (/^https:/.test(request.origin) && !/^https:/.test(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } + + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin) + } + } +} + +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} + +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} + +// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer +function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) + + // 2. Let environment be request’s client. + + let referrerSource = null + + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin() + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin + } +} + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ +function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL) + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = '' + + // 4. Set url’s password to the empty string. + url.password = '' + + // 5. Set url’s fragment to null. + url.hash = '' + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' + + // 2. Set url’s query to null. + url.search = '' + } + + // 7. Return url. + return url +} + +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } + + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // If scheme is data, return true + if (url.protocol === 'data:') return true + + // If file, return true + if (url.protocol === 'file:') return true + + return isOriginPotentiallyTrustworthy(url.origin) + + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false + + const originAsURL = new URL(origin) + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true + } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false + } +} + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ +function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } + + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) + + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } + + // 3. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 4. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const list = parsedMetadata.sort((c, d) => d.algo.localeCompare(c.algo)) + // get the strongest algorithm + const strongest = list[0].algo + // get all entries that use the strongest algorithm; ignore weaker + const metadata = list.filter((item) => item.algo === strongest) + + // 5. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo + + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash + + // 3. Let actualValue be the result of applying algorithm to bytes. + const actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (actualValue === expectedValue) { + return true + } + } + + // 6. Return false. + return false +} + +// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options +// https://www.w3.org/TR/CSP2/#source-list-syntax +// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 +const parseHashWithOptions = /((?sha256|sha384|sha512)-(?[A-z0-9+/]{1}.*={0,2}))( +[\x21-\x7e]?)?/i + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = [] + + // 2. Let empty be equal to true. + let empty = true + + const supportedHashes = crypto.getHashes() + + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) + + // 3. If token does not parse, continue to the next token. + if (parsedToken === null || parsedToken.groups === undefined) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } + + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm.toLowerCase())) { + result.push(parsedToken.groups) + } + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + // "opaque origin" is an internal value we cannot access, ignore. + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false +} + +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) + + return { promise, resolve: res, reject: rej } +} + +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} + +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +// https://fetch.spec.whatwg.org/#concept-method-normalize +function normalizeMethod (method) { + return /^(DELETE|GET|HEAD|OPTIONS|POST|PUT)$/i.test(method) + ? method.toUpperCase() + : method +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result +} + +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {() => unknown[]} iterator + * @param {string} name name of the instance + * @param {'key'|'value'|'key+value'} kind + */ +function makeIterator (iterator, name, kind) { + const object = { + index: 0, + kind, + target: iterator + } + + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + + // 2. Let thisValue be the this value. + + // 3. Let object be ? ToObject(thisValue). + + // 4. If object is a platform object, then perform a security + // check, passing: + + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const { index, kind, target } = object + const values = target() + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { value: undefined, done: true } + } + + // 11. Let pair be the entry in values at index index. + const pair = values[index] + + // 12. Set object’s index to index + 1. + object.index = index + 1 + + // 13. Return the iterator result for pair and kind. + return iteratorResult(pair, kind) + }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". + [Symbol.toStringTag]: `${name} Iterator` + } + + // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. + Object.setPrototypeOf(i, esIteratorPrototype) + // esIteratorPrototype needs to be the prototype of i + // which is the prototype of an empty object. Yes, it's confusing. + return Object.setPrototypeOf({}, i) +} + +// https://webidl.spec.whatwg.org/#iterator-result +function iteratorResult (pair, kind) { + let result + + // 1. Let result be a value determined by the value of kind: + switch (kind) { + case 'key': { + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = pair[0] + break + } + case 'value': { + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = pair[1] + break + } + case 'key+value': { + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = pair + break + } + } + + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } +} + +/** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = (bytes) => queueMicrotask(() => processBody(bytes)) + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = (error) => queueMicrotask(() => processBodyError(error)) + + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader + + try { + reader = body.stream.getReader() + } catch (e) { + errorSteps(e) + return + } + + // 5. Read all bytes from reader, given successSteps and errorSteps. + readAllBytes(reader, successSteps, errorSteps) +} + +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream + +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} + +const MAXIMUM_ARGUMENT_LENGTH = 65535 + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {number[]|Uint8Array} input + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + + if (input.length < MAXIMUM_ARGUMENT_LENGTH) { + return String.fromCharCode(...input) + } + + return input.reduce((previous, current) => previous + String.fromCharCode(current), '') +} + +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed')) { + throw err + } + } +} + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + for (let i = 0; i < input.length; i++) { + assert(input.charCodeAt(i) <= 0xFF) + } + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} + +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + * @param {(bytes: Uint8Array) => void} successSteps + * @param {(error: Error) => void} failureSteps + */ +async function readAllBytes (reader, successSteps, failureSteps) { + const bytes = [] + let byteLength = 0 + + while (true) { + let done + let chunk + + try { + ({ done, value: chunk } = await reader.read()) + } catch (e) { + // 1. Call failureSteps with e. + failureSteps(e) + return + } + + if (done) { + // 1. Call successSteps with bytes. + successSteps(Buffer.concat(bytes, byteLength)) + return + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + failureSteps(new TypeError('Received non-Uint8Array chunk')) + return + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } +} + +/** + * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. + */ +const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) + +module.exports = { + isAborted, + isCancelled, + createDeferredPromise, + ReadableStreamFrom, + toUSVString, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + makeIterator, + isValidHeaderName, + isValidHeaderValue, + hasOwn, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + isomorphicDecode +} diff --git a/node_modules/undici/lib/fetch/webidl.js b/node_modules/undici/lib/fetch/webidl.js new file mode 100644 index 0000000..e55de13 --- /dev/null +++ b/node_modules/undici/lib/fetch/webidl.js @@ -0,0 +1,641 @@ +'use strict' + +const { types } = require('util') +const { hasOwn, toUSVString } = require('./util') + +/** @type {import('../../types/webidl').Webidl} */ +const webidl = {} +webidl.converters = {} +webidl.util = {} +webidl.errors = {} + +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} + +webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of' + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.` + + return webidl.errors.exception({ + header: context.prefix, + message + }) +} + +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I, opts = undefined) { + if (opts?.strict !== false && !(V instanceof I)) { + throw new TypeError('Illegal invocation') + } else { + return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] + } +} + +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + ...ctx + }) + } +} + +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } + + return 'Object' + } + } +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { + let upperBound + let lowerBound + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0 + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V) + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${V} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r +} + +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: 'Sequence', + message: `Value of type ${webidl.util.Type(V)} is not an Object.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = V?.[Symbol.iterator]?.() + const seq = [] + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: 'Sequence', + message: 'Object is not an iterator.' + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value)) + } + + return seq + } +} + +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: 'Record', + message: `Value of type ${webidl.util.Type(O)} is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {} + + if (!types.isProxy(O)) { + // Object.keys only returns enumerable properties + const keys = Object.keys(O) + + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + } + + // 5. Return result. + return result + } +} + +webidl.interfaceConverter = function (i) { + return (V, opts = {}) => { + if (opts.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: i.name, + message: `Expected ${V} to be an instance of ${i.name}.` + }) + } + + return V + } +} + +webidl.dictionaryConverter = function (converters) { + return (dictionary) => { + const type = webidl.util.Type(dictionary) + const dict = {} + + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options + + if (required === true) { + if (!hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key] + const hasDefault = hasOwn(options, 'defaultValue') + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value = value ?? defaultValue + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value) + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value + } + } + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V + } + + return converter(V) + } +} + +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, opts = {}) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts.legacyNullToEmptyString) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw new TypeError('Could not convert argument of type symbol to string.') + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) +} + +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + const charCode = x.charCodeAt(index) + + if (charCode > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${charCode} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x +} + +// https://webidl.spec.whatwg.org/#es-USVString +webidl.converters.USVString = toUSVString + +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V) + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} + +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V +} + +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed') + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned') + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned') + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix: `${V}`, + argument: `${V}`, + types: ['ArrayBuffer'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + // Note: resizable ArrayBuffers are currently a proposal. + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +webidl.converters.TypedArray = function (V, T, opts = {}) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix: `${T.name}`, + argument: `${V}`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable array buffers are currently a proposal + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V +} + +webidl.converters.DataView = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: 'DataView', + message: 'Object is not a DataView.' + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable ArrayBuffers are currently a proposal + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, opts = {}) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, opts) + } + + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor) + } + + if (types.isDataView(V)) { + return webidl.converters.DataView(V, opts) + } + + throw new TypeError(`Could not convert ${V} to a BufferSource.`) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) + +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) + +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) + +module.exports = { + webidl +} diff --git a/node_modules/undici/lib/fileapi/encoding.js b/node_modules/undici/lib/fileapi/encoding.js new file mode 100644 index 0000000..1d1d2b6 --- /dev/null +++ b/node_modules/undici/lib/fileapi/encoding.js @@ -0,0 +1,290 @@ +'use strict' + +/** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ +function getEncoding (label) { + if (!label) { + return 'failure' + } + + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' + } +} + +module.exports = { + getEncoding +} diff --git a/node_modules/undici/lib/fileapi/filereader.js b/node_modules/undici/lib/fileapi/filereader.js new file mode 100644 index 0000000..cd36a22 --- /dev/null +++ b/node_modules/undici/lib/fileapi/filereader.js @@ -0,0 +1,344 @@ +'use strict' + +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = require('./util') +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = require('./symbols') +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../core/util') + +class FileReader extends EventTarget { + constructor () { + super() + + this[kState] = 'empty' + this[kResult] = null + this[kError] = null + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding) + } + + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding) + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL') + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null + return + } + + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done' + this[kResult] = null + } + + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true + + // 4. Terminate the algorithm for the read method being processed. + // TODO + + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) + + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader) + + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader) + + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader) + + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] + } + + get onloadend () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadend + } + + set onloadend (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend) + } + + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null + } + } + + get onerror () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].error + } + + set onerror (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error) + } + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null + } + } + + get onloadstart () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadstart + } + + set onloadstart (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart) + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null + } + } + + get onprogress () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].progress + } + + set onprogress (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) + } + + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null + } + } + + get onload () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].load + } + + set onload (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) + } + + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null + } + } + + get onabort () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].abort + } + + set onabort (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort) + } + + if (typeof fn === 'function') { + this[kEvents].abort = fn + this.addEventListener('abort', fn) + } else { + this[kEvents].abort = null + } + } +} + +// https://w3c.github.io/FileAPI/#dom-filereader-empty +FileReader.EMPTY = FileReader.prototype.EMPTY = 0 +// https://w3c.github.io/FileAPI/#dom-filereader-loading +FileReader.LOADING = FileReader.prototype.LOADING = 1 +// https://w3c.github.io/FileAPI/#dom-filereader-done +FileReader.DONE = FileReader.prototype.DONE = 2 + +Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) + +module.exports = { + FileReader +} diff --git a/node_modules/undici/lib/fileapi/progressevent.js b/node_modules/undici/lib/fileapi/progressevent.js new file mode 100644 index 0000000..778cf22 --- /dev/null +++ b/node_modules/undici/lib/fileapi/progressevent.js @@ -0,0 +1,78 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') + +const kState = Symbol('ProgressEvent state') + +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) + + super(type, eventInitDict) + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + } + } + + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].lengthComputable + } + + get loaded () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].loaded + } + + get total () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].total + } +} + +webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +]) + +module.exports = { + ProgressEvent +} diff --git a/node_modules/undici/lib/fileapi/symbols.js b/node_modules/undici/lib/fileapi/symbols.js new file mode 100644 index 0000000..dd11746 --- /dev/null +++ b/node_modules/undici/lib/fileapi/symbols.js @@ -0,0 +1,10 @@ +'use strict' + +module.exports = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') +} diff --git a/node_modules/undici/lib/fileapi/util.js b/node_modules/undici/lib/fileapi/util.js new file mode 100644 index 0000000..1d10899 --- /dev/null +++ b/node_modules/undici/lib/fileapi/util.js @@ -0,0 +1,392 @@ +'use strict' + +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = require('./symbols') +const { ProgressEvent } = require('./progressevent') +const { getEncoding } = require('./encoding') +const { DOMException } = require('../fetch/constants') +const { serializeAMimeType, parseMIMEType } = require('../fetch/dataURL') +const { types } = require('util') +const { StringDecoder } = require('string_decoder') +const { btoa } = require('buffer') + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +/** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ +function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading' + + // 3. Set fr’s result to null. + fr[kResult] = null + + // 4. Set fr’s error to null. + fr[kError] = null + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream() + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader() + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = [] + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr) + }) + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value) + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now() + queueMicrotask(() => { + fireAProgressEvent('progress', fr) + }) + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read() + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName) + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr) + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Set fr’s error to error. + fr[kError] = error + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } + })() +} + +/** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ +function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }) + + reader.dispatchEvent(event) +} + +/** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ +function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: + + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:' + + const parsed = parseMIMEType(mimeType || 'application/octet-stream') + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed) + } + + dataURL += ';base64,' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)) + } + + dataURL += btoa(decoder.end()) + + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure' + + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName) + } + + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType) + + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')) + } + } + + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8' + } + + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) + } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes) + + return sequence.buffer + } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = '' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + binaryString += decoder.write(chunk) + } + + binaryString += decoder.end() + + return binaryString + } + } +} + +/** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ +function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue) + + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes) + + let slice = 0 + + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding + + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2 + } + + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". + + // 4. Return output. + + const sliced = bytes.slice(slice) + return new TextDecoder(encoding).decode(sliced) +} + +/** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ +function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue + + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } + + return null +} + +/** + * @param {Uint8Array[]} sequences + */ +function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0) + + let offset = 0 + + return sequences.reduce((a, b) => { + a.set(b, offset) + offset += b.byteLength + return a + }, new Uint8Array(size)) +} + +module.exports = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} diff --git a/node_modules/undici/lib/global.js b/node_modules/undici/lib/global.js new file mode 100644 index 0000000..18bfd73 --- /dev/null +++ b/node_modules/undici/lib/global.js @@ -0,0 +1,32 @@ +'use strict' + +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = require('./core/errors') +const Agent = require('./agent') + +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) +} + +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) +} + +function getGlobalDispatcher () { + return globalThis[globalDispatcher] +} + +module.exports = { + setGlobalDispatcher, + getGlobalDispatcher +} diff --git a/node_modules/undici/lib/handler/DecoratorHandler.js b/node_modules/undici/lib/handler/DecoratorHandler.js new file mode 100644 index 0000000..9d70a76 --- /dev/null +++ b/node_modules/undici/lib/handler/DecoratorHandler.js @@ -0,0 +1,35 @@ +'use strict' + +module.exports = class DecoratorHandler { + constructor (handler) { + this.handler = handler + } + + onConnect (...args) { + return this.handler.onConnect(...args) + } + + onError (...args) { + return this.handler.onError(...args) + } + + onUpgrade (...args) { + return this.handler.onUpgrade(...args) + } + + onHeaders (...args) { + return this.handler.onHeaders(...args) + } + + onData (...args) { + return this.handler.onData(...args) + } + + onComplete (...args) { + return this.handler.onComplete(...args) + } + + onBodySent (...args) { + return this.handler.onBodySent(...args) + } +} diff --git a/node_modules/undici/lib/handler/RedirectHandler.js b/node_modules/undici/lib/handler/RedirectHandler.js new file mode 100644 index 0000000..baca27e --- /dev/null +++ b/node_modules/undici/lib/handler/RedirectHandler.js @@ -0,0 +1,216 @@ +'use strict' + +const util = require('../core/util') +const { kBodyUsed } = require('../core/symbols') +const assert = require('assert') +const { InvalidArgumentError } = require('../core/errors') +const EE = require('events') + +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] + +const kBody = Symbol('body') + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + util.validateHandler(handler, opts.method, opts.upgrade) + + this.dispatch = dispatch + this.location = null + this.abort = null + this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] + + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) + } + } + + onConnect (abort) { + this.abort = abort + this.handler.onConnect(abort, { history: this.history }) + } + + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket) + } + + onError (error) { + this.handler.onError(error) + } + + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers) + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) + } + + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) + } + + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.maxRedirections = 0 + this.opts.query = null + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + this.opts.body = null + } + } + + onData (chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response bodies. + + Redirection is used to serve the requested resource from another URL, so it is assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. + + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. + + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitily chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + return this.handler.onData(chunk) + } + } + + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed informations. + */ + + this.location = null + this.abort = null + + this.dispatch(this.opts, this) + } else { + this.handler.onComplete(trailers) + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk) + } + } +} + +function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } + + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toString().toLowerCase() === 'location') { + return headers[i + 1] + } + } +} + +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + return ( + (header.length === 4 && header.toString().toLowerCase() === 'host') || + (removeContent && header.toString().toLowerCase().indexOf('content-') === 0) || + (unknownOrigin && header.length === 13 && header.toString().toLowerCase() === 'authorization') || + (unknownOrigin && header.length === 6 && header.toString().toLowerCase() === 'cookie') + ) +} + +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret +} + +module.exports = RedirectHandler diff --git a/node_modules/undici/lib/interceptor/redirectInterceptor.js b/node_modules/undici/lib/interceptor/redirectInterceptor.js new file mode 100644 index 0000000..7cc035e --- /dev/null +++ b/node_modules/undici/lib/interceptor/redirectInterceptor.js @@ -0,0 +1,21 @@ +'use strict' + +const RedirectHandler = require('../handler/RedirectHandler') + +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } +} + +module.exports = createRedirectInterceptor diff --git a/node_modules/undici/lib/llhttp/constants.d.ts b/node_modules/undici/lib/llhttp/constants.d.ts new file mode 100644 index 0000000..b75ab1b --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.d.ts @@ -0,0 +1,199 @@ +import { IEnumMap } from './utils'; +export declare type HTTPMode = 'loose' | 'strict'; +export declare enum ERROR { + OK = 0, + INTERNAL = 1, + STRICT = 2, + LF_EXPECTED = 3, + UNEXPECTED_CONTENT_LENGTH = 4, + CLOSED_CONNECTION = 5, + INVALID_METHOD = 6, + INVALID_URL = 7, + INVALID_CONSTANT = 8, + INVALID_VERSION = 9, + INVALID_HEADER_TOKEN = 10, + INVALID_CONTENT_LENGTH = 11, + INVALID_CHUNK_SIZE = 12, + INVALID_STATUS = 13, + INVALID_EOF_STATE = 14, + INVALID_TRANSFER_ENCODING = 15, + CB_MESSAGE_BEGIN = 16, + CB_HEADERS_COMPLETE = 17, + CB_MESSAGE_COMPLETE = 18, + CB_CHUNK_HEADER = 19, + CB_CHUNK_COMPLETE = 20, + PAUSED = 21, + PAUSED_UPGRADE = 22, + PAUSED_H2_UPGRADE = 23, + USER = 24 +} +export declare enum TYPE { + BOTH = 0, + REQUEST = 1, + RESPONSE = 2 +} +export declare enum FLAGS { + CONNECTION_KEEP_ALIVE = 1, + CONNECTION_CLOSE = 2, + CONNECTION_UPGRADE = 4, + CHUNKED = 8, + UPGRADE = 16, + CONTENT_LENGTH = 32, + SKIPBODY = 64, + TRAILING = 128, + TRANSFER_ENCODING = 512 +} +export declare enum LENIENT_FLAGS { + HEADERS = 1, + CHUNKED_LENGTH = 2, + KEEP_ALIVE = 4 +} +export declare enum METHODS { + DELETE = 0, + GET = 1, + HEAD = 2, + POST = 3, + PUT = 4, + CONNECT = 5, + OPTIONS = 6, + TRACE = 7, + COPY = 8, + LOCK = 9, + MKCOL = 10, + MOVE = 11, + PROPFIND = 12, + PROPPATCH = 13, + SEARCH = 14, + UNLOCK = 15, + BIND = 16, + REBIND = 17, + UNBIND = 18, + ACL = 19, + REPORT = 20, + MKACTIVITY = 21, + CHECKOUT = 22, + MERGE = 23, + 'M-SEARCH' = 24, + NOTIFY = 25, + SUBSCRIBE = 26, + UNSUBSCRIBE = 27, + PATCH = 28, + PURGE = 29, + MKCALENDAR = 30, + LINK = 31, + UNLINK = 32, + SOURCE = 33, + PRI = 34, + DESCRIBE = 35, + ANNOUNCE = 36, + SETUP = 37, + PLAY = 38, + PAUSE = 39, + TEARDOWN = 40, + GET_PARAMETER = 41, + SET_PARAMETER = 42, + REDIRECT = 43, + RECORD = 44, + FLUSH = 45 +} +export declare const METHODS_HTTP: METHODS[]; +export declare const METHODS_ICE: METHODS[]; +export declare const METHODS_RTSP: METHODS[]; +export declare const METHOD_MAP: IEnumMap; +export declare const H_METHOD_MAP: IEnumMap; +export declare enum FINISH { + SAFE = 0, + SAFE_WITH_CB = 1, + UNSAFE = 2 +} +export declare type CharList = Array; +export declare const ALPHA: CharList; +export declare const NUM_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const HEX_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; +}; +export declare const NUM: CharList; +export declare const ALPHANUM: CharList; +export declare const MARK: CharList; +export declare const USERINFO_CHARS: CharList; +export declare const STRICT_URL_CHAR: CharList; +export declare const URL_CHAR: CharList; +export declare const HEX: CharList; +export declare const STRICT_TOKEN: CharList; +export declare const TOKEN: CharList; +export declare const HEADER_CHARS: CharList; +export declare const CONNECTION_TOKEN_CHARS: CharList; +export declare const MAJOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const MINOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare enum HEADER_STATE { + GENERAL = 0, + CONNECTION = 1, + CONTENT_LENGTH = 2, + TRANSFER_ENCODING = 3, + UPGRADE = 4, + CONNECTION_KEEP_ALIVE = 5, + CONNECTION_CLOSE = 6, + CONNECTION_UPGRADE = 7, + TRANSFER_ENCODING_CHUNKED = 8 +} +export declare const SPECIAL_HEADERS: { + connection: HEADER_STATE; + 'content-length': HEADER_STATE; + 'proxy-connection': HEADER_STATE; + 'transfer-encoding': HEADER_STATE; + upgrade: HEADER_STATE; +}; diff --git a/node_modules/undici/lib/llhttp/constants.js b/node_modules/undici/lib/llhttp/constants.js new file mode 100644 index 0000000..fb0b5a2 --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.js @@ -0,0 +1,278 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = require("./utils"); +// C headers +var ERROR; +(function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; +})(ERROR = exports.ERROR || (exports.ERROR = {})); +var TYPE; +(function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; +})(TYPE = exports.TYPE || (exports.TYPE = {})); +var FLAGS; +(function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; +})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); +var LENIENT_FLAGS; +(function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; +})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); +var METHODS; +(function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; +})(METHODS = exports.METHODS || (exports.METHODS = {})); +exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, +]; +exports.METHODS_ICE = [ + METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, +]; +exports.METHOD_MAP = utils_1.enumToMap(METHODS); +exports.H_METHOD_MAP = {}; +Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } +}); +var FINISH; +(function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; +})(FINISH = exports.FINISH || (exports.FINISH = {})); +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); +// All characters with 0x80 bit set to 1 +for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); +} +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +var HEADER_STATE; +(function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; +})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); +exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, +}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/constants.js.map b/node_modules/undici/lib/llhttp/constants.js.map new file mode 100644 index 0000000..6ac54bc --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/llhttp/constants.ts"],"names":[],"mappings":";;;AAAA,mCAA8C;AAI9C,YAAY;AAEZ,IAAY,KA6BX;AA7BD,WAAY,KAAK;IACf,6BAAM,CAAA;IACN,yCAAQ,CAAA;IACR,qCAAM,CAAA;IACN,+CAAW,CAAA;IACX,2EAAyB,CAAA;IACzB,2DAAiB,CAAA;IACjB,qDAAc,CAAA;IACd,+CAAW,CAAA;IACX,yDAAgB,CAAA;IAChB,uDAAe,CAAA;IACf,kEAAoB,CAAA;IACpB,sEAAsB,CAAA;IACtB,8DAAkB,CAAA;IAClB,sDAAc,CAAA;IACd,4DAAiB,CAAA;IACjB,4EAAyB,CAAA;IAEzB,0DAAgB,CAAA;IAChB,gEAAmB,CAAA;IACnB,gEAAmB,CAAA;IACnB,wDAAe,CAAA;IACf,4DAAiB,CAAA;IAEjB,sCAAM,CAAA;IACN,sDAAc,CAAA;IACd,4DAAiB,CAAA;IAEjB,kCAAI,CAAA;AACN,CAAC,EA7BW,KAAK,GAAL,aAAK,KAAL,aAAK,QA6BhB;AAED,IAAY,IAIX;AAJD,WAAY,IAAI;IACd,+BAAQ,CAAA;IACR,qCAAO,CAAA;IACP,uCAAQ,CAAA;AACV,CAAC,EAJW,IAAI,GAAJ,YAAI,KAAJ,YAAI,QAIf;AAED,IAAY,KAWX;AAXD,WAAY,KAAK;IACf,mEAA8B,CAAA;IAC9B,yDAAyB,CAAA;IACzB,6DAA2B,CAAA;IAC3B,uCAAgB,CAAA;IAChB,wCAAgB,CAAA;IAChB,sDAAuB,CAAA;IACvB,0CAAiB,CAAA;IACjB,2CAAiB,CAAA;IACjB,mBAAm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;AAE5D;;;GAGG;AACU,QAAA,YAAY,GAAa,CAAE,IAAI,CAAE,CAAC;AAC/C,KAAK,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,EAAE,EAAE;IAC9B,IAAI,CAAC,KAAK,GAAG,EAAE;QACb,oBAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;KACtB;CACF;AAED,aAAa;AACA,QAAA,sBAAsB,GACjC,oBAAY,CAAC,MAAM,CAAC,CAAC,CAAkB,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;AAE3C,QAAA,KAAK,GAAG,eAAO,CAAC;AAChB,QAAA,KAAK,GAAG,aAAK,CAAC;AAE3B,IAAY,YAWX;AAXD,WAAY,YAAY;IACtB,qDAAW,CAAA;IACX,2DAAU,CAAA;IACV,mEAAc,CAAA;IACd,yEAAiB,CAAA;IACjB,qDAAO,CAAA;IAEP,iFAAqB,CAAA;IACrB,uEAAgB,CAAA;IAChB,2EAAkB,CAAA;IAClB,yFAAyB,CAAA;AAC3B,CAAC,EAXW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAWvB;AAEY,QAAA,eAAe,GAAG;IAC7B,YAAY,EAAE,YAAY,CAAC,UAAU;IACrC,gBAAgB,EAAE,YAAY,CAAC,cAAc;IAC7C,kBAAkB,EAAE,YAAY,CAAC,UAAU;IAC3C,mBAAmB,EAAE,YAAY,CAAC,iBAAiB;IACnD,SAAS,EAAE,YAAY,CAAC,OAAO;CAChC,CAAC"} \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/llhttp.wasm b/node_modules/undici/lib/llhttp/llhttp.wasm new file mode 100755 index 0000000..633d00a Binary files /dev/null and b/node_modules/undici/lib/llhttp/llhttp.wasm differ diff --git a/node_modules/undici/lib/llhttp/llhttp.wasm.js b/node_modules/undici/lib/llhttp/llhttp.wasm.js new file mode 100644 index 0000000..e176ce2 --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp.wasm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iAEGcf2pB5ABJDQAgAEHMAUYNACAAQbACRg0AQQQhBSAEQYgEcUGABEYNAiAEQShxRQ0CC0EADwtBAEEDIAApAyBQGyEFCyAFC10BAn9BACEBAkAgAC0AKEEBRg0AIAAvATIiAkGcf2pB5ABJDQAgAkHMAUYNACACQbACRg0AIAAvATAiAEHAAHENAEEBIQEgAEGIBHFBgARGDQAgAEEocUUhAQsgAQuiAQEDfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEDIAAvATAiBEECcUUNAQwCC0EAIQMgAC8BMCIEQQFxRQ0BC0EBIQMgAC0AKEEBRg0AIAAvATIiBUGcf2pB5ABJDQAgBUHMAUYNACAFQbACRg0AIARBwABxDQBBACEDIARBiARxQYAERg0AIARBKHFBAEchAwsgAEEAOwEwIABBADoALyADC5QBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQEgAC8BMCICQQJxRQ0BDAILQQAhASAALwEwIgJBAXFFDQELQQEhASAALQAoQQFGDQAgAC8BMiIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvc9wEDKH8DfgV/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8gASEQIAEhESABIRIgASETIAEhFCABIRUgASEWIAEhFyABIRggASEZIAEhGiABIRsgASEcIAEhHSABIR4gASEfIAEhICABISEgASEiI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kACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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aiEBC0EiISoMxgMLAkAgASIqIAJHDQBBHCEqDN8DC0IAISsgKiEBICotAABBUGoON+cB5gEBAgMEBQYHCAAAAAAAAAAJCgsMDQ4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8QERITFAALQR4hKgzEAwtCAiErDOUBC0IDISsM5AELQgQhKwzjAQtCBSErDOIBC0IGISsM4QELQgchKwzgAQtCCCErDN8BC0IJISsM3gELQgohKwzdAQtCCyErDNwBC0IMISsM2wELQg0hKwzaAQtCDiErDNkBC0IPISsM2AELQgohKwzXAQtCCyErDNYBC0IMISsM1QELQg0hKwzUAQtCDiErDNMBC0IPISsM0gELQgAhKwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgKi0AAEFQag435QHkAQABAgMEBQYH5gHmAeYB5gHmAeYB5gEICQoLDA3mAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYBDg8QERIT5gELQgIhKwzkAQtCAyErDOMBC0IEISsM4gELQgUhKwzhAQtCBiErDOABC0IHISsM3wELQgghKwzeAQtCCSErDN0BC0IKISsM3AELQgshKwzbAQtCDCErDNoBC0INISsM2QELQg4hKwzYAQtCDyErDNcBC0IKISsM1gELQgshKwzVAQtCDCErDNQBC0INISsM0wELQg4hKwzSAQtCDyErDNEBCyAAQgAgACkDICIrIAIgASIqa60iLH0iLSAtICtWGzcDICArICxWIi5FDdIBQR8hKgzHAwsCQCABIgEgAkYNACAAQYmAgIAANgIIIAAgATYCBCABIQFBJCEqDK4DC0EgISoMxgMLIAAgASIqIAIQvoCAgABBf2oOBbYBAMsCAdEB0gELQREhKgyrAwsgAEEBOgAvICohAQzCAwsgASIBIAJHDdIBQSQhKgzCAwsgASInIAJHDR5BxgAhKgzBAwsgACABIgEgAhCygICAACIqDdQBIAEhAQy1AQsgASIqIAJHDSZB0AAhKgy/AwsCQCABIgEgAkcNAEEoISoMvwMLIABBADYCBCAA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BzAHMAcwBzAHMAQHMAQsgBEEBaiEBQe8AISoMzQILIARBAWohAUHwACEqDMwCCwJAIAEiBCACRw0AQYYBISoM5QILIAQtAABBxQBHDckBIARBAWohAQyKAgsCQCABIiogAkcNAEGHASEqDOQCCyACICprIAAoAgAiLmohMiAqIQQgLiEBAkADQCAELQAAIAFBiM+AgABqLQAARw3JASABQQNGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIDI2AgBBhwEhKgzkAgsgAEEANgIAICogLmtBBGohAUEtISoMxgELAkAgASIqIAJHDQBBiAEhKgzjAgsgAiAqayAAKAIAIi5qITIgKiEEIC4hAQJAA0AgBC0AACABQdDPgIAAai0AAEcNyAEgAUEIRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAyNgIAQYgBISoM4wILIABBADYCACAqIC5rQQlqIQFBKSEqDMUBCwJAIAEiASACRw0AQYkBISoM4gILQQEhKiABLQAAQd8ARw3EASABQQFqIQEMiAILAkAgASIqIAJHDQBBigEhKgzhAgsgAiAqayAAKAIAIi5qITIgKiEEIC4hAQNAIAQtAAAgAUGMz4CAAGotAABHDcUBIAFBAUYNtwIgAUEBaiEBIARBAWoiBCACRw0ACyAAIDI2AgBBigEhKgzgAgsCQCABIiogAkcNAEGLASEqDOACCyACICprIAAoAgAiLmohMiAqIQQgLiEBAkADQCAELQAAIAFBjs+AgABqLQAARw3FASABQQJGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIDI2AgBBiwEhKgzgAgsgAEEANgIAICogLmtBA2ohAUECISoMwgELAkAgASIqIAJHDQBBjAEhKgzfAgsgAiAqayAAKAIAIi5qITIgKiEEIC4hAQJAA0AgBC0AACABQfDPgIAAai0AAEcNxAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAyNgIAQYwBISoM3wILIABBADYCACAqIC5rQQJqIQFBHyEqDMEBCwJAIAEiKiACRw0AQY0BISoM3gILIAIgKmsgACgCACIuaiEyICohBCAuIQECQANAIAQtAAAgAUHyz4CA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iEBQfcAISoMmwILIARBAWohAUH6ACEqDJoCCyAEQQFqIQRBgwEhKgyZAgsgBEEBaiEGQYQBISoMmAILIARBAWohB0GFASEqDJcCCyAEQQFqIQRBkgEhKgyWAgsgBEEBaiEEQZgBISoMlQILIARBAWohBEGgASEqDJQCCyAEQQFqIQRBowEhKgyTAgsgBEEBaiEEQaoBISoMkgILAkAgBCACRg0AIABBkICAgAA2AgggACAENgIEQasBISoMkgILQcABISoMqgILIAAgHSACEKqAgIAAIgENjwEgHSEBDF4LAkAgHiACRg0AIB5BAWohHQyRAQtBwgEhKgyoAgsDQAJAICotAABBdmoOBJABAACTAQALICpBAWoiKiACRw0AC0HDASEqDKcCCwJAIB8gAkYNACAAQZGAgIAANgIIIAAgHzYCBCAfIQFBASEqDI4CC0HEASEqDKYCCwJAIB8gAkcNAEHFASEqDKYCCwJAAkAgHy0AAEF2ag4EAdUB1QEA1QELIB9BAWohHgyRAQsgH0EBaiEdDI0BCwJAIB8gAkcNAEHGASEqDKUCCwJAAkAgHy0AAEF2ag4XAZMBkwEBkwGTAZMBkwGTAZMBkwGTAZMBkwGTAZMBkwGTAZMBkwGTAZMBAJMBCyAfQQFqIR8LQbABISoMiwILAkAgICACRw0AQcgBISoMpAILICAtAABBIEcNkQEgAEEAOwEyICBBAWohAUGzASEqDIoCCyABITICQANAIDIiHyACRg0BIB8tAABBUGpB/wFxIipBCk8N0wECQCAALwEyIi5BmTNLDQAgACAuQQpsIi47ATIgKkH//wNzIC5B/v8DcUkNACAfQQFqITIgACAuICpqIio7ATIgKkH//wNxQegHSQ0BCwtBACEqIABBADYCHCAAQcGJgIAANgIQIABBDTYCDCAAIB9BAWo2AhQMowILQccBISoMogILIAAgICACEK6AgIAAIipFDdEBICpBFUcNkAEgAEHIATYCHCAAICA2AhQgAEHJl4CAADYCECAAQRU2AgxBACEqDKECCwJAICEgAkcNAEHMASEqDKECC0EAIS5BASEyQQEhL0EAISoCQAJAAkACQAJAAkACQAJAAkAgIS0AAEFQag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oM/gELQdkBISoMlgILAkAgBCACRw0AQdoBISoMlgILIAQtAABByABGDcsBIABBAToAKAzAAQsgAEECOgAvIAAgBCACEKaAgIAAIioNkwFBwgEhKgz7AQsgAC0AKEF/ag4CvgHAAb8BCwNAAkAgBC0AAEF2ag4EAJQBlAEAlAELIARBAWoiBCACRw0AC0HdASEqDJICCyAAQQA6AC8gAC0ALUEEcUUNiwILIABBADoALyAAQQE6ADQgASEBDJIBCyAqQRVGDeIBIABBADYCHCAAIAE2AhQgAEGnjoCAADYCECAAQRI2AgxBACEqDI8CCwJAIAAgKiACELSAgIAAIgENACAqIQEMiAILAkAgAUEVRw0AIABBAzYCHCAAICo2AhQgAEGwmICAADYCECAAQRU2AgxBACEqDI8CCyAAQQA2AhwgACAqNgIUIABBp46AgAA2AhAgAEESNgIMQQAhKgyOAgsgKkEVRg3eASAAQQA2AhwgACABNgIUIABB2o2AgAA2AhAgAEEUNgIMQQAhKgyNAgsgACgCBCEyIABBADYCBCAqICunaiIvIQEgACAyICogLyAuGyIqELWAgIAAIi5FDZMBIABBBzYCHCAAICo2AhQgACAuNgIMQQAhKgyMAgsgACAALwEwQYABcjsBMCABIQELQSohKgzxAQsgKkEVRg3ZASAAQQA2AhwgACABNgIUIABBg4yAgAA2AhAgAEETNgIMQQAhKgyJAgsgKkEVRg3XASAAQQA2AhwgACABNgIUIABBmo+AgAA2AhAgAEEiNgIMQQAhKgyIAgsgACgCBCEqIABBADYCBAJAIAAgKiABELeAgIAAIioNACABQQFqIQEMkwELIABBDDYCHCAAICo2AgwgACABQQFqNgIUQQAhKgyHAgsgKkEVRg3UASAAQQA2AhwgACABNgIUIABBmo+AgAA2AhAgAEEiNgIMQQAhKgyGAgsgACgCBCEqIABBADYCBAJAIAAgKiABELeAgIAAIioNACABQQFqIQEMkgELIABBDTYCHCAAICo2AgwgACABQQFqNgIUQQAhKgyFAgsgKkEVRg3RASAAQQA2AhwgACABNgIUIABBxoyAgAA2AhAgAEEjNgIMQQAhKgyEAgsgACgCBCEqIABBADYCBAJAIAAgKiABELmAgIAAIioNACABQQFqIQEMkQELIABBDjYCHCAAICo2AgwgACABQQFqNgIUQQAhKgyDAgsgAEEANgIcIAAgATYCFCAAQcCVgIAANgIQIABBAjYCDEEAISoMggILICpBFUYNzQEgAEEANgIcIAAgATYCFCAAQcaMgIAANgIQIABBIzYCDEEAISoMgQILIABBEDYCHCAAIAE2AhQgACAqNgIMQQAhKgyAAgsgACgCBCEEIABBADYCBAJAIAAgBCABELmAgIAAIgQNACABQQFqIQEM+AELIABBETYCHCAAIAQ2AgwgACABQQFqNgIUQQAhKgz/AQsgKkEVRg3JASAAQQA2AhwgACABNgIUIABBxoyAgAA2AhAgAEEjNgIMQQAhKgz+AQsgACgCBCEqIABBADYCBAJAIAAgKiABELmAgIAAIioNACABQQFqIQEMjgELIABBEzYCHCAAICo2AgwgACABQQFqNgIUQQAhKgz9AQsgACgCBCEEIABBADYCBAJAIAAgBCABELmAgIAAIgQNACABQQFqIQEM9AELIABBFDYCHCAAIAQ2AgwgACABQQFqNgIUQQAhKgz8AQsgKkEVRg3FASAAQQA2AhwgACABNgIUIABBmo+AgAA2AhAgAEEiNgIMQQAhKgz7AQsgACgCBCEqIABBADYCBAJAIAAgKiABELeAgIAAIioNACABQQFqIQEMjAELIABBFjYCHCAAICo2AgwgACABQQFqNgIUQQAhKgz6AQsgACgCBCEEIABBADYCBAJAIAAgBCABELeAgIAAIgQNACABQQFqIQEM8AELIABBFzYCHCAAIAQ2AgwgACABQQFqNgIUQQAhKgz5AQsgAEEANgIcIAAgATYCFCAAQc2TgIAANgIQIABBDDYCDEEAISoM+AELQgEhKwsgKkEBaiEBAkAgACkDICIsQv//////////D1YNACAAICxCBIYgK4Q3AyAgASEBDIoBCyAAQQA2AhwgACABNgIUIABBrYmAgAA2AhAgAEEMNgIMQQAhKgz2AQsgAEEANgIcIAAgKjYCFCAAQc2TgIAANgIQIABBDDYCDEEAISoM9QELIAAoAgQhMiAAQQA2AgQgKiArp2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AISoMuQELIABBADYCACAyIC9rQQRqIQECQCAALQApIipBXWpBC08NACABIQEMWAsCQCAqQQZLDQBBASAqdEHKAHFFDQAgASEBDFgLQQAhKiAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLgBCyAqQRVGDXUgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAISoMtwELIAAoAgQhKiAAQQA2AgQCQCAAICogARCngICAACIqDQAgASEBDFcLIABB5QA2AhwgACABNgIUIAAgKjYCDEEAISoMtgELIAAoAgQhKiAAQQA2AgQCQCAAICogARCngICAACIqDQAgASEBDE8LIABB0gA2AhwgACABNgIUIAAgKjYCDEEAISoMtQELIAAoAgQhKiAAQQA2AgQCQCAAICogARCngICAACIqDQAgASEBDE8LIABB0wA2AhwgACABNgIUIAAgKjYCDEEAISoMtAELIAAoAgQhKiAAQQA2AgQCQCAAICogARCngICAACIqDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgKjYCDEEAISoMswELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEqDLIBCyAAKAIEISogAEEANgIEAkAgACAqIAEQp4CAgAAiKg0AIAEhAQxLCyAAQdIANgIcIAAgATYCFCAAICo2AgxBACEqDLEBCyAAKAIEISogAEEANgIEAkAgACAqIAEQp4CAgAAiKg0AIAEhAQxLCyAAQdMANgIcIAAgATYCFCAAICo2AgxBACEqDLABCyAAKAIEISogAEEANgIEAkAgACAqIAEQp4CAgAAiKg0AIAEhAQxQCyAAQeUANgIcIAAgATYCFCAAICo2AgxBACEqDK8BCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhKgyuAQsgKkE/Rw0BIAFBAWohAQtBBSEqDJMBC0EAISogAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyrAQsgACgCBCEqIABBADYCBAJAIAAgKiABEKeAgIAAIioNACABIQEMRAsgAEHSADYCHCAAIAE2AhQgACAqNgIMQQAhKgyqAQsgACgCBCEqIABBADYCBAJAIAAgKiABEKeAgIAAIioNACABIQEMRAsgAEHTADYCHCAAIAE2AhQgACAqNgIMQQAhKgypAQsgACgCBCEqIABBADYCBAJAIAAgKiABEKeAgIAAIioNACABIQEMSQsgAEHlADYCHCAAIAE2AhQgACAqNgIMQQAhKgyoAQsgACgCBCEBIABBADYCBAJAIAAgASAuEKeAgIAAIgENACAuIQEMQQsgAEHSADYCHCAAIC42AhQgACABNgIMQQAhKgynAQsgACgCBCEBIABBADYCBAJAIAAgASAuEKeAgIAAIgENACAuIQEMQQsgAEHTADYCHCAAIC42AhQgACABNgIMQQAhKgymAQsgACgCBCEBIABBADYCBAJAIAAgASAuEKeAgIAAIgENACAuIQEMRgsgAEHlADYCHCAAIC42AhQgACABNgIMQQAhKgylAQsgAEEANgIcIAAgLjYCFCAAQcOPgIAANgIQIABBBzYCDEEAISoMpAELIABBADYCHCAAIAE2AhQgAEHDj4CAADYCECAAQQc2AgxBACEqDKMBC0EAISogAEEANgIcIAAgLjYCFCAAQYycgIAANgIQIABBBzYCDAyiAQsgAEEANgIcIAAgLjYCFCAAQYycgIAANgIQIABBBzYCDEEAISoMoQELIABBADYCHCAAIC42AhQgAEH+kYCAADYCECAAQQc2AgxBACEqDKABCyAAQQA2AhwgACABNgIUIABBjpuAgAA2AhAgAEEGNgIMQQAhKgyfAQsgKkEVRg1bIABBADYCHCAAIAE2AhQgAEHMjoCAADYCECAAQSA2AgxBACEqDJ4BCyAAQQA2AgAgKiAua0EGaiEBQSQhKgsgACAqOgApIAAoAgQhKiAAQQA2AgQgACAqIAEQq4CAgAAiKg1YIAEhAQxBCyAAQQA2AgALQQAhKiAAQQA2AhwgACAENgIUIABB8ZuAgAA2AhAgAEEGNgIMDJoBCyABQRVGDVQgAEEANgIcIAAgHTYCFCAAQfCMgIAANgIQIABBGzYCDEEAISoMmQELIAAoAgQhHSAAQQA2AgQgACAdICoQqYCAgAAiHQ0BICpBAWohHQtBrQEhKgx+CyAAQcEBNgIcIA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gIcIAAgKjYCFCAAQdqNgIAANgIQIABBFDYCDEEAISoMLQsgAEEENgIcIAAgATYCFCAAQbCYgIAANgIQIABBFTYCDEEAISoMLAsgAEEANgIAIAQgLmtBBWohIwtBuAEhKgwRCyAAQQA2AgAgKiAua0ECaiEBQfUAISoMEAsgASEBAkAgAC0AKUEFRw0AQeMAISoMEAtB4gAhKgwPC0EAISogAEEANgIcIABB5JGAgAA2AhAgAEEHNgIMIAAgLkEBajYCFAwnCyAAQQA2AgAgMiAva0ECaiEBQcAAISoMDQsgASEBC0E4ISoMCwsCQCABIikgAkYNAANAAkAgKS0AAEGAvoCAAGotAAAiAUEBRg0AIAFBAkcNAyApQQFqIQEMBAsgKUEBaiIpIAJHDQALQT4hKgwkC0E+ISoMIwsgAEEAOgAsICkhAQwBC0ELISoMCAtBOiEqDAcLIAFBAWohAUEtISoMBgtBKCEqDAULIABBADYCACAvIDBrQQRqIQFBBiEqCyAAICo6ACwgASEBQQwhKgwDCyAAQQA2AgAgMiAva0EHaiEBQQohKgwCCyAAQQA2AgALIABBADoALCAnIQFBCSEqDAALC0EAISogAEEANgIcIAAgIzYCFCAAQc2QgIAANgIQIABBCTYCDAwXC0EAISogAEEANgIcIAAgIjYCFCAAQemKgIAANgIQIABBCTYCDAwWC0EAISogAEEANgIcIAAgITYCFCAAQbeQgIAANgIQIABBCTYCDAwVC0EAISogAEEANgIcIAAgIDYCFCAAQZyRgIAANgIQIABBCTYCDAwUC0EAISogAEEANgIcIAAgATYCFCAAQc2QgIAANgIQIABBCTYCDAwTC0EAISogAEEANgIcIAAgATYCFCAAQemKgIAANgIQIABBCTYCDAwSC0EAISogAEEANgIcIAAgATYCFCAAQbeQgIAANgIQIABBCTYCDAwRC0EAISogAEEANgIcIAAgATYCFCAAQZyRgIAANgIQIABBCTYCDAwQC0EAISogAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwPC0EAISogAEEANgIcIAAgATYCFCAAQZeVgIAANgIQIABBDzYCDAwOC0EAISogAEEANgIcIAAgATYCFCAAQcCSgIAANgIQIABBCzYCDAwNC0EAISogAEEANgIcIAAgATYCFCAAQZWJgIAANgIQIABBCzYCDAwMC0EAISogAEEANgIcIAAgATYCFCAAQeGPgIAANgIQIABBCjYCDAwLC0EAISogAEEANgIcIAAgATYCFCAAQfuPgIAANgIQIABBCjYCDAwKC0EAISogAEEANgIcIAAgATYCFCAAQfGZgIAANgIQIABBAjYCDAwJC0EAISogAEEANgIcIAAgATYCFCAAQcSUgIAANgIQIABBAjYCDAwIC0EAISogAEEANgIcIAAgATYCFCAAQfKVgIAANgIQIABBAjYCDAwHCyAAQQI2AhwgACABNgIUIABBnJqAgAA2AhAgAEEWNgIMQQAhKgwGC0EBISoMBQtB1AAhKiABIgEgAkYNBCADQQhqIAAgASACQdjCgIAAQQoQxYCAgAAgAygCDCEBIAMoAggOAwEEAgALEMuAgIAAAAsgAEEANgIcIABBtZqAgAA2AhAgAEEXNgIMIAAgAUEBajYCFEEAISoMAgsgAEEANgIcIAAgATYCFCAAQcqagIAANgIQIABBCTYCDEEAISoMAQsCQCABIgEgAkcNAEEiISoMAQsgAEGJgICAADYCCCAAIAE2AgRBISEqCyADQRBqJICAgIAAICoLrwEBAn8gASgCACEGAkACQCACIANGDQAgBCAGaiEEIAYgA2ogAmshByACIAZBf3MgBWoiBmohBQNAAkAgAi0AACAELQAARg0AQQIhBAwDCwJAIAYNAEEAIQQgBSECDAMLIAZBf2ohBiAEQQFqIQQgAkEBaiICIANHDQALIAchBiADIQILIABBATYCACABIAY2AgAgACACNgIEDwsgAUEANgIAIAAgBDYCACAAIAI2AgQLCgAgABDHgICAAAuVNwELfyOAgICAAEEQayIBJICAgIAAAkBBACgCoNCAgAANAEEAEMqAgIAAQYDUhIAAayICQdkASQ0AQQAhAwJAQQAoAuDTgIAAIgQNAEEAQn83AuzTgIAAQQBCgICEgICAwAA3AuTTgIAAQQAgAUEIakFwcUHYqtWqBXMiBDYC4NOAgABBAEEANgL004CAAEEAQ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MDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAACAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAATk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv' diff --git a/node_modules/undici/lib/llhttp/llhttp_simd.wasm b/node_modules/undici/lib/llhttp/llhttp_simd.wasm new file mode 100755 index 0000000..93cdf56 Binary files /dev/null and b/node_modules/undici/lib/llhttp/llhttp_simd.wasm differ diff --git a/node_modules/undici/lib/llhttp/llhttp_simd.wasm.js b/node_modules/undici/lib/llhttp/llhttp_simd.wasm.js new file mode 100644 index 0000000..0fb8a67 --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp_simd.wasm.js @@ -0,0 +1 @@ +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX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NAiAEQShxRQ0CC0EADwtBAEEDIAApAyBQGyEFCyAFC10BAn9BACEBAkAgAC0AKEEBRg0AIAAvATIiAkGcf2pB5ABJDQAgAkHMAUYNACACQbACRg0AIAAvATAiAEHAAHENAEEBIQEgAEGIBHFBgARGDQAgAEEocUUhAQsgAQuiAQEDfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEDIAAvATAiBEECcUUNAQwCC0EAIQMgAC8BMCIEQQFxRQ0BC0EBIQMgAC0AKEEBRg0AIAAvATIiBUGcf2pB5ABJDQAgBUHMAUYNACAFQbACRg0AIARBwABxDQBBACEDIARBiARxQYAERg0AIARBKHFBAEchAwsgAEEAOwEwIABBADoALyADC5QBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNAEEAIQEgAC8BMCICQQJxRQ0BDAILQQAhASAALwEwIgJBAXFFDQELQQEhASAALQAoQQFGDQAgAC8BMiIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC9z3AQMofwN+BX8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDyABIRAgASERIAEhEiABIRMgASEUIAEhFSABIRYgASEXIAEhGCABIRkgASEaIAEhGyABIRwgASEdIAEhHiABIR8gASEgIAEhISABISIgASEjIAEhJCABISUgASEmIAEhJyABISggASEpAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAk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ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAqDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSkt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AAAAkKCwwNDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADxAREhMUAAtBHiEqDMQDC0ICISsM5QELQgMhKwzkAQtCBCErDOMBC0IFISsM4gELQgYhKwzhAQtCByErDOABC0IIISsM3wELQgkhKwzeAQtCCiErDN0BC0ILISsM3AELQgwhKwzbAQtCDSErDNoBC0IOISsM2QELQg8hKwzYAQtCCiErDNcBC0ILISsM1gELQgwhKwzVAQtCDSErDNQBC0IOISsM0wELQg8hKwzSAQtCACErAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAqLQAAQVBqDjflAeQBAAECAwQFBgfmAeYB5gHmAeYB5gHmAQgJCgsMDeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gHmAeYB5gEODxAREhPmAQtCAiErDOQBC0IDISsM4wELQgQhKwziAQtCBSErDOEBC0IGISsM4AELQgchKwzfAQtCCCErDN4BC0IJISsM3QELQgohKwzcAQtCCyErDNsBC0IMISsM2gELQg0hKwzZAQtCDiErDNgBC0IPISsM1wELQgohKwzWAQtCCyErDNUBC0IMISsM1AELQg0hKwzTAQtCDiErDNIBC0IPISsM0QELIABCACAAKQMgIisgAiABIiprrSIsfSItIC0gK1YbNwMgICsgLFYiLkUN0gFBHyEqDMcDCwJAIAEiASACRg0AIABBiYCAgAA2AgggACABNgIEIAEhAUEkISoMrgMLQSAhKgzGAwsgACABIiogAhC+gICAAEF/ag4FtgEAywIB0QHSAQtBESEqDKsDCyAAQQE6AC8gKiEBDMIDCyABIgEgAkcN0gFBJCEqDMIDCyABIicgAkcNHkHGACEqDMEDCyAAIAEiASACELKAgIAAIioN1AEgASEBDLUBCyABIiogAkcNJkHQACEqDL8DCwJAIAEiASACRw0AQSghKgy/AwsgAEEANgIEIABBjICAgAA2AgggACABIAEQsYCAgAAiKg3TASABIQEM2AELAkAgASIqIAJHDQBBKSEqDL4DCyAqLQAAIgFBIEYNFCABQQ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IgKmsgACgCACIuaiEyICohBCAuIQECQANAIAQtAAAgAUGIz4CAAGotAABHDckBIAFBA0YNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgMjYCAEGHASEqDOQCCyAAQQA2AgAgKiAua0EEaiEBQS0hKgzGAQsCQCABIiogAkcNAEGIASEqDOMCCyACICprIAAoAgAiLmohMiAqIQQgLiEBAkADQCAELQAAIAFB0M+AgABqLQAARw3IASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIDI2AgBBiAEhKgzjAgsgAEEANgIAICogLmtBCWohAUEpISoMxQELAkAgASIBIAJHDQBBiQEhKgziAgtBASEqIAEtAABB3wBHDcQBIAFBAWohAQyIAgsCQCABIiogAkcNAEGKASEqDOECCyACICprIAAoAgAiLmohMiAqIQQgLiEBA0AgBC0AACABQYzPgIAAai0AAEcNxQEgAUEBRg23AiABQQFqIQEgBEEBaiIEIAJHDQALIAAgMjYCAEGKASEqDOACCwJAIAEiKiACRw0AQYsBISoM4AILIAIgKmsgACgCACIuaiEyICohBCAuIQECQANAIAQtAAAgAUGOz4CAAGotAABHDcUBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgMjYCAEGLASEqDOACCyAAQQA2AgAgKiAua0EDaiEBQQIhKgzCAQsCQCABIiogAkcNAEGMASEqDN8CCyACICprIAAoAgAiLmohMiAqIQQgLiEBAkADQCAELQAAIAFB8M+AgABqLQAARw3EASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIDI2AgBBjAEhKgzfAgsgAEEANgIAICogLmtBAmohAUEfISoMwQELAkAgASIqIAJHDQBBjQEhKgzeAgsgAiAqayAAKAIAIi5qITIgKiEEIC4hAQJAA0AgBC0AACABQfLPgIAAai0AAEcNwwEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAyNgIAQY0BISoM3gILIABBADYCACAqIC5rQQJqIQFBCSEqDMABCwJAIAEiBCACRw0AQY4BISoM3QILAkACQCAELQAAQbd/ag4HAMMB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DPgIAAai0AAEcNrAEgAUEBRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAuNgIAQaQBISoMxwILIABBADYCACAOICprQQJqIQFBHSEqDKkBCwJAIAQgAkcNAEGlASEqDMYCCwJAAkAgBC0AAEGuf2oOAwCsAQGsAQsgBEEBaiEOQZABISoMrQILIARBAWohAUEEISoMqAELAkAgBCACRw0AQaYBISoMxQILAkACQAJAAkACQCAELQAAQb9/ag4VAK4BrgGuAa4BrgGuAa4BrgGuAa4BAa4BrgECrgGuAQOuAa4BBK4BCyAEQQFqIQRBiAEhKgyvAgsgBEEBaiEKQYkBISoMrgILIARBAWohC0GKASEqDK0CCyAEQQFqIQRBjwEhKgysAgsgBEEBaiEEQZEBISoMqwILAkAgDyACRw0AQacBISoMxAILIAIgD2sgACgCACIqaiEuIA8hBCAqIQECQANAIAQtAAAgAUHtz4CAAGotAABHDakBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgLjYCAEGnASEqDMQCCyAAQQA2AgAgDyAqa0EDaiEBQREhKgymAQsCQCAQIAJHDQBBqAEhKgzDAgsgAiAQayAAKAIAIipqIS4gECEEICohAQJAA0AgBC0AACABQcLPgIAAai0AAEcNqAEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAuNgIAQagBISoMwwILIABBADYCACAQICprQQNqIQFBLCEqDKUBCwJAIBEgAkcNAEGpASEqDMICCyACIBFrIAAoAgAiKmohLiARIQQgKiEBAkADQCAELQAAIAFBxc+AgABqLQAARw2nASABQQRGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIC42AgBBqQEhKgzCAgsgAEEANgIAIBEgKmtBBWohAUErISoMpAELAkAgEiACRw0AQaoBISoMwQILIAIgEmsgACgCACIqaiEuIBIhBCAqIQECQANAIAQtAAAgAUHKz4CAAGotAABHDaYBIAFBAkYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgLjYCAEGqASEqDMECCyAAQQA2AgAgEiAqa0EDaiEBQRQhKgyjAQsCQCAEIAJHDQBBqwEhKgzAAgsCQAJAAkACQCAELQAAQb5/ag4PAAECqAGoAagBqAGoAagBqAGoAagBqAGoAQOoAQsgBEEBaiEPQZMBISoMqQILIARBAWohEEGUASEqDKgCCyAEQQFqIRFBlQEhKgynAgsgBEEBaiESQZYBISoMpgILAkAgBCACRw0AQawBISoMvwILIAQtAABBxQBHDaMBIARBAWohBAznAQsCQCATIAJHDQBBrQEhKgy+AgsgAiATayAAKAIAIipqIS4gEyEEICohAQJAA0AgBC0AACABQc3PgIAAai0AAEcNowEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAuNgIAQa0BISoMvgILIABBADYCACATICprQQNqIQFBDiEqDKABCwJAIAQgAkcNAEGuASEqDL0CCyAELQAAQdAARw2hASAEQQFqIQFBJSEqDJ8BCwJAIBQgAkcNAEGvASEqDLwCCyACIBRrIAAoAgAiKmohLiAUIQQgKiEBAkADQCAELQAAIAFB0M+AgABqLQAARw2hASABQQhGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIC42AgBBrwEhKgy8AgsgAEEANgIAIBQgKmtBCWohAUEqISoMngELAkAgBCACRw0AQbABISoMuwILAkACQCAELQAAQat/ag4LAKEBoQGhAaEBoQGhAaEBoQGhAQGhAQsgBEEBaiEEQZoBISoMogILIARBAWohFEGbASEqDKECCwJAIAQgAkcNAEGxASEqDLoCCwJAAkAgBC0AAEG/f2oOFACgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEBoAELIARBAWohE0GZASEqDKECCyAEQQFqIQRBnAEhKgygAgsCQCAVIAJHDQBBsgEhKgy5AgsgAiAVayAAKAIAIipqIS4gFSEEICohAQJAA0AgBC0AACABQdnPgIAAai0AAEcNngEgAUEDRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAuNgIAQbIBISoMuQILIABBADYCACAVICprQQRqIQFBISEqDJsBCwJAIBYgAkcNAEGzASEqDLgCCyACIBZrIAAoAgAiKmohLiAWIQQgKiEBAkADQCAELQAAIAFB3c+AgABqLQAARw2dASABQQZGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIC42AgBBswEhKgy4AgsgAEEANgIAIBYgKmtBB2ohAUEaISoMmgELAkAgBCACRw0AQbQBISoMtwILAkACQAJAIAQtAABBu39qDhEAngGeAZ4BngGeAZ4BngGeAZ4BAZ4BngGeAZ4BngECngELIARBAWohBEGdASEqDJ8CCyAEQQFqIRVBngEhKgyeAgsgBEEBaiEWQZ8BISoMnQILAkAgFyACRw0AQbUBISoMtgILIAIgF2sgACgCACIqaiEuIBchBCAqIQECQANAIAQtAAAgAUHkz4CAAGotAABHDZsBIAFBBUYNASABQQFqIQEgBEEBaiIEIAJHDQALIAAgLjYCAEG1ASEqDLYCCyAAQQA2AgAgFyAqa0EGaiEBQSghKgyYAQsCQCAYIAJHDQBBtgEhKgy1AgsgAiAYayAAKAIAIipqIS4gGCEEICohAQJAA0AgBC0AACABQerPgIAAai0AAEcNmgEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAuNgIAQbYBISoMtQILIABBADYCACAYICprQQNqIQFBByEqDJcBCwJAIAQgAkcNAEG3ASEqDLQCCwJAAkAgBC0AAEG7f2oODgCaAZoBmgGaAZoBmgGaAZoBmgGaAZoBmgEBmgELIARBAWohF0GhASEqDJsCCyAEQQFqIRhBogEhKgyaAgsCQCAZIAJHDQBBuAEhKgyzAgsgAiAZayAAKAIAIipqIS4gGSEEICohAQJAA0AgBC0AACABQe3PgIAAai0AAEcNmAEgAUECRg0BIAFBAWohASAEQQFqIgQgAkcNAAsgACAuNgIAQbgBISoMswILIABBADYCACAZICprQQNqIQFBEiEqDJUBCwJAIBogAkcNAEG5ASEqDLICCyACIBprIAAoAgAiKmohLiAaIQQgKiEBAkADQCAELQAAIAFB8M+AgABqLQAARw2XASABQQFGDQEgAUEBaiEBIARBAWoiBCACRw0ACyAAIC42AgBBuQEhKgyyAgsgAEEANgIAIBogKmtBAmohAUEgISoMlAELAkAgGyACRw0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AhQgAEH3iYCAADYCECAAQQg2AgwMuAELICpBFUYNdSAAQQA2AhwgACABNgIUIABBuY2AgAA2AhAgAEEaNgIMQQAhKgy3AQsgACgCBCEqIABBADYCBAJAIAAgKiABEKeAgIAAIioNACABIQEMVwsgAEHlADYCHCAAIAE2AhQgACAqNgIMQQAhKgy2AQsgACgCBCEqIABBADYCBAJAIAAgKiABEKeAgIAAIioNACABIQEMTwsgAEHSADYCHCAAIAE2AhQgACAqNgIMQQAhKgy1AQsgACgCBCEqIABBADYCBAJAIAAgKiABEKeAgIAAIioNACABIQEMTwsgAEHTADYCHCAAIAE2AhQgACAqNgIMQQAhKgy0AQsgACgCBCEqIABBADYCBAJAIAAgKiABEKeAgIAAIioNACABIQEMVAsgAEHlADYCHCAAIAE2AhQgACAqNgIMQQAhKgyzAQsgAEEANgIcIAAgATYCFCAAQcaKgIAANgIQIABBBzYCDEEAISoMsgELIAAoAgQhKiAAQQA2AgQCQCAAICogARCngICAACIqDQAgASEBDEsLIABB0gA2AhwgACABNgIUIAAgKjYCDEEAISoMsQELIAAoAgQhKiAAQQA2AgQCQCAAICogARCngICAACIqDQAgASEBDEsLIABB0wA2AhwgACABNgIUIAAgKjYCDEEAISoMsAELIAAoAgQhKiAAQQA2AgQCQCAAICogARCngICAACIqDQAgASEBDFALIABB5QA2AhwgACABNgIUIAAgKjYCDEEAISoMrwELIABBADYCHCAAIAE2AhQgAEHciICAADYCECAAQQc2AgxBACEqDK4BCyAqQT9HDQEgAUEBaiEBC0EFISoMkwELQQAhKiAAQQA2AhwgACABNgIUIABB/ZKAgAA2AhAgAEEHNgIMDKsBCyAAKAIEISogAEEANgIEAkAgACAqIAEQp4CAgAAiKg0AIAEhAQxECyAAQdIANgIcIAAgATYCFCAAICo2AgxBACEqDKoBCyAAKAIEISogAEEANgIEAkAgACAqIAEQp4CAgAAiKg0AIAEhAQxECyAAQdMANgIcIAAgATYCFCAAICo2AgxBACEqDKkBCyAAKAIEISogAEEANgIEAkAgACAqIAE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QsgACgCCCECCyACIAE2AgwgACABNgIIIAEgADYCDCABIAI2AggPC0EfIQICQCAAQf///wdLDQAgAEEIdiICIAJBgP4/akEQdkEIcSICdCIEIARBgOAfakEQdkEEcSIEdCIGIAZBgIAPakEQdkECcSIGdEEPdiACIARyIAZyayICQQF0IAAgAkEVanZBAXFyQRxqIQILIAFCADcCECABQRxqIAI2AgAgAkECdEG40oCAAGohBAJAAkBBACgCjNCAgAAiBkEBIAJ0IgNxDQAgBCABNgIAQQAgBiADcjYCjNCAgAAgAUEYaiAENgIAIAEgATYCCCABIAE2AgwMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgBCgCACEGAkADQCAGIgQoAgRBeHEgAEYNASACQR12IQYgAkEBdCECIAQgBkEEcWpBEGoiAygCACIGDQALIAMgATYCACABQRhqIAQ2AgAgASABNgIMIAEgATYCCAwBCyAEKAIIIgAgATYCDCAEIAE2AgggAUEYakEANgIAIAEgBDYCDCABIAA2AggLQQBBACgCqNCAgABBf2oiAUF/IAEbNgKo0ICAAAsLTgACQCAADQA/AEEQdA8LAkAgAEH//wNxDQAgAEF/TA0AAkAgAEEQdkAAIgBBf0cNAEEAQTA2AvjTgIAAQX8PCyAAQRB0DwsQy4CAgAAACwQAAAAL+wICA38BfgJAIAJFDQAgACABOgAAIAIgAGoiA0F/aiABOgAAIAJBA0kNACAAIAE6AAIgACABOgABIANBfWogAToAACADQX5qIAE6AAAgAkEHSQ0AIAAgAToAAyADQXxqIAE6AAAgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIFayICQSBJDQAgAa1CgYCAgBB+IQYgAyAFaiEBA0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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=' diff --git a/node_modules/undici/lib/llhttp/utils.d.ts b/node_modules/undici/lib/llhttp/utils.d.ts new file mode 100644 index 0000000..15497f3 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.d.ts @@ -0,0 +1,4 @@ +export interface IEnumMap { + [key: string]: number; +} +export declare function enumToMap(obj: any): IEnumMap; diff --git a/node_modules/undici/lib/llhttp/utils.js b/node_modules/undici/lib/llhttp/utils.js new file mode 100644 index 0000000..8a32e56 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enumToMap = void 0; +function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; +} +exports.enumToMap = enumToMap; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/utils.js.map b/node_modules/undici/lib/llhttp/utils.js.map new file mode 100644 index 0000000..2d7c356 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/llhttp/utils.ts"],"names":[],"mappings":";;;AAIA,SAAgB,SAAS,CAAC,GAAQ;IAChC,MAAM,GAAG,GAAa,EAAE,CAAC;IAEzB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;SAClB;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC;AACb,CAAC;AAXD,8BAWC"} \ No newline at end of file diff --git a/node_modules/undici/lib/mock/mock-agent.js b/node_modules/undici/lib/mock/mock-agent.js new file mode 100644 index 0000000..828e8af --- /dev/null +++ b/node_modules/undici/lib/mock/mock-agent.js @@ -0,0 +1,171 @@ +'use strict' + +const { kClients } = require('../core/symbols') +const Agent = require('../agent') +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = require('./mock-symbols') +const MockClient = require('./mock-client') +const MockPool = require('./mock-pool') +const { matchValue, buildMockOptions } = require('./mock-utils') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const Dispatcher = require('../dispatcher') +const Pluralizer = require('./pluralizer') +const PendingInterceptorsFormatter = require('./pending-interceptors-formatter') + +class FakeWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value + } +} + +class MockAgent extends Dispatcher { + constructor (opts) { + super(opts) + + this[kNetConnect] = true + this[kIsMockActive] = true + + // Instantiate Agent and encapsulate + if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts && opts.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent + + this[kClients] = agent[kClients] + this[kOptions] = buildMockOptions(opts) + } + + get (origin) { + let dispatcher = this[kMockAgentGet](origin) + + if (!dispatcher) { + dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + } + return dispatcher + } + + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + return this[kAgent].dispatch(opts, handler) + } + + async close () { + await this[kAgent].close() + this[kClients].clear() + } + + deactivate () { + this[kIsMockActive] = false + } + + activate () { + this[kIsMockActive] = true + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, new FakeWeakRef(dispatcher)) + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const ref = this[kClients].get(origin) + if (ref) { + return ref.deref() + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { + const nonExplicitDispatcher = nonExplicitRef.deref() + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients] + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() + + if (pending.length === 0) { + return + } + + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) + + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + +${pendingInterceptorsFormatter.format(pending)} +`.trim()) + } +} + +module.exports = MockAgent diff --git a/node_modules/undici/lib/mock/mock-client.js b/node_modules/undici/lib/mock/mock-client.js new file mode 100644 index 0000000..5f31215 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-client.js @@ -0,0 +1,59 @@ +'use strict' + +const { promisify } = require('util') +const Client = require('../client') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockClient diff --git a/node_modules/undici/lib/mock/mock-errors.js b/node_modules/undici/lib/mock/mock-errors.js new file mode 100644 index 0000000..5442c0e --- /dev/null +++ b/node_modules/undici/lib/mock/mock-errors.js @@ -0,0 +1,17 @@ +'use strict' + +const { UndiciError } = require('../core/errors') + +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, MockNotMatchedError) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} + +module.exports = { + MockNotMatchedError +} diff --git a/node_modules/undici/lib/mock/mock-interceptor.js b/node_modules/undici/lib/mock/mock-interceptor.js new file mode 100644 index 0000000..781e477 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-interceptor.js @@ -0,0 +1,206 @@ +'use strict' + +const { getResponseData, buildKey, addMockDispatch } = require('./mock-utils') +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = require('./mock-symbols') +const { InvalidArgumentError } = require('../core/errors') +const { buildURL } = require('../core/util') + +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch + } + + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + + this[kMockDispatch].delay = waitInMs + return this + } + + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } + + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes + return this + } +} + +/** + * Defines an interceptor for a Mock + */ +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } + + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false + } + + createMockScopeDispatchData (statusCode, data, responseOptions = {}) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } + + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (statusCode, data, responseOptions) { + if (typeof statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof data === 'undefined') { + throw new InvalidArgumentError('data must be defined') + } + if (typeof responseOptions !== 'object') { + throw new InvalidArgumentError('responseOptions must be an object') + } + } + + /** + * Mock an undici request with a defined reply. + */ + reply (replyData) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyData === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyData(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object') { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const { statusCode, data = '', responseOptions = {} } = resolvedData + this.validateReplyParameters(statusCode, data, responseOptions) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(statusCode, data, responseOptions) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const [statusCode, data = '', responseOptions = {}] = [...arguments] + this.validateReplyParameters(statusCode, data, responseOptions) + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) + return new MockScope(newMockDispatch) + } + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers + return this + } + + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } + + this[kDefaultTrailers] = trailers + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this + } +} + +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope diff --git a/node_modules/undici/lib/mock/mock-pool.js b/node_modules/undici/lib/mock/mock-pool.js new file mode 100644 index 0000000..0a3a7cd --- /dev/null +++ b/node_modules/undici/lib/mock/mock-pool.js @@ -0,0 +1,59 @@ +'use strict' + +const { promisify } = require('util') +const Pool = require('../pool') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockPool diff --git a/node_modules/undici/lib/mock/mock-symbols.js b/node_modules/undici/lib/mock/mock-symbols.js new file mode 100644 index 0000000..8c4cbb6 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-symbols.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') +} diff --git a/node_modules/undici/lib/mock/mock-utils.js b/node_modules/undici/lib/mock/mock-utils.js new file mode 100644 index 0000000..42ea185 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-utils.js @@ -0,0 +1,351 @@ +'use strict' + +const { MockNotMatchedError } = require('./mock-errors') +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = require('./mock-symbols') +const { buildURL, nop } = require('../core/util') +const { STATUS_CODES } = require('http') +const { + types: { + isPromise + } +} = require('util') + +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} + +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} + +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } +} + +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) +} + +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true +} + +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + + const pathSegments = path.split('?') + + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} + +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} + +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } +} + +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath + + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) + } + + return matchedMockDispatches[0] +} + +function addMockDispatch (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch +} + +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) + } +} + +function buildKey (opts) { + const { path, method, body, headers, query } = opts + return { + path, + method, + body, + headers, + query + } +} + +function generateKeyValues (data) { + return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ + ...keyValuePairs, + Buffer.from(`${key}`), + Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) + ], []) +} + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' +} + +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') +} + +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) + + mockDispatch.timesInvoked++ + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)) + return + } + + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.abort = nop + handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData(Buffer.from(responseData)) + handler.onComplete(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true +} + +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } +} + +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} + +function buildMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts + return mockOptions + } +} + +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildMockOptions, + getHeaderByName +} diff --git a/node_modules/undici/lib/mock/pending-interceptors-formatter.js b/node_modules/undici/lib/mock/pending-interceptors-formatter.js new file mode 100644 index 0000000..1bc7539 --- /dev/null +++ b/node_modules/undici/lib/mock/pending-interceptors-formatter.js @@ -0,0 +1,40 @@ +'use strict' + +const { Transform } = require('stream') +const { Console } = require('console') + +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) + } + }) + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? '✅' : '❌', + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) + + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() + } +} diff --git a/node_modules/undici/lib/mock/pluralizer.js b/node_modules/undici/lib/mock/pluralizer.js new file mode 100644 index 0000000..47f150b --- /dev/null +++ b/node_modules/undici/lib/mock/pluralizer.js @@ -0,0 +1,29 @@ +'use strict' + +const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' +} + +const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' +} + +module.exports = class Pluralizer { + constructor (singular, plural) { + this.singular = singular + this.plural = plural + } + + pluralize (count) { + const one = count === 1 + const keys = one ? singulars : plurals + const noun = one ? this.singular : this.plural + return { ...keys, count, noun } + } +} diff --git a/node_modules/undici/lib/node/fixed-queue.js b/node_modules/undici/lib/node/fixed-queue.js new file mode 100644 index 0000000..3572681 --- /dev/null +++ b/node_modules/undici/lib/node/fixed-queue.js @@ -0,0 +1,117 @@ +/* eslint-disable */ + +'use strict' + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048; +const kMask = kSize - 1; + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | [empty] | <-- top | item | | item | +// | [empty] | | item | | item | +// | [empty] | | [empty] | <-- top top --> | [empty] | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | [empty] | | item | +// | [empty] | | item | +// | item | <-- bottom top --> | [empty] | +// | item | | [empty] | +// | [empty] | <-- top bottom --> | item | +// | [empty] | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; + } + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } +} + +module.exports = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } +}; diff --git a/node_modules/undici/lib/pool-base.js b/node_modules/undici/lib/pool-base.js new file mode 100644 index 0000000..2a909ee --- /dev/null +++ b/node_modules/undici/lib/pool-base.js @@ -0,0 +1,194 @@ +'use strict' + +const DispatcherBase = require('./dispatcher-base') +const FixedQueue = require('./node/fixed-queue') +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('./core/symbols') +const PoolStats = require('./pool-stats') + +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') +const kStats = Symbol('stats') + +class PoolBase extends DispatcherBase { + constructor () { + super() + + this[kQueue] = new FixedQueue() + this[kClients] = [] + this[kQueued] = 0 + + const pool = this + + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue] + + let needDrain = false + + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + pool[kQueued]-- + needDrain = !this.dispatch(item.opts, item.handler) + } + + this[kNeedDrain] = needDrain + + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false + pool.emit('drain', origin, [pool, ...targets]) + } + + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]) + } + } + + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err) + } + + this[kStats] = new PoolStats(this) + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } + + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } + + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending + } + return ret + } + + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret + } + + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret + } + + get stats () { + return this[kStats] + } + + async [kClose] () { + if (this[kQueue].isEmpty()) { + return Promise.all(this[kClients].map(c => c.close())) + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve + }) + } + } + + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) + } + + return Promise.all(this[kClients].map(c => c.destroy(err))) + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + process.nextTick(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]) + } + }) + } + + return this + } + + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + } +} + +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} diff --git a/node_modules/undici/lib/pool-stats.js b/node_modules/undici/lib/pool-stats.js new file mode 100644 index 0000000..b4af8ae --- /dev/null +++ b/node_modules/undici/lib/pool-stats.js @@ -0,0 +1,34 @@ +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require('./core/symbols') +const kPool = Symbol('pool') + +class PoolStats { + constructor (pool) { + this[kPool] = pool + } + + get connected () { + return this[kPool][kConnected] + } + + get free () { + return this[kPool][kFree] + } + + get pending () { + return this[kPool][kPending] + } + + get queued () { + return this[kPool][kQueued] + } + + get running () { + return this[kPool][kRunning] + } + + get size () { + return this[kPool][kSize] + } +} + +module.exports = PoolStats diff --git a/node_modules/undici/lib/pool.js b/node_modules/undici/lib/pool.js new file mode 100644 index 0000000..93b3158 --- /dev/null +++ b/node_modules/undici/lib/pool.js @@ -0,0 +1,92 @@ +'use strict' + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher +} = require('./pool-base') +const Client = require('./client') +const { + InvalidArgumentError +} = require('./core/errors') +const util = require('./core/util') +const { kUrl, kInterceptors } = require('./core/symbols') +const buildConnector = require('./core/connect') + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + ...options + } = {}) { + super() + + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + socketPath, + timeout: connectTimeout == null ? 10e3 : connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : [] + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory + } + + [kGetDispatcher] () { + let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + + if (dispatcher) { + return dispatcher + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + } + + return dispatcher + } +} + +module.exports = Pool diff --git a/node_modules/undici/lib/proxy-agent.js b/node_modules/undici/lib/proxy-agent.js new file mode 100644 index 0000000..c710948 --- /dev/null +++ b/node_modules/undici/lib/proxy-agent.js @@ -0,0 +1,187 @@ +'use strict' + +const { kProxy, kClose, kDestroy, kInterceptors } = require('./core/symbols') +const { URL } = require('url') +const Agent = require('./agent') +const Pool = require('./pool') +const DispatcherBase = require('./dispatcher-base') +const { InvalidArgumentError, RequestAbortedError } = require('./core/errors') +const buildConnector = require('./core/connect') + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 +} + +function buildProxyOptions (opts) { + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + return { + uri: opts.uri, + protocol: opts.protocol || 'https' + } +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class ProxyAgent extends DispatcherBase { + constructor (opts) { + super(opts) + this[kProxy] = buildProxyOptions(opts) + this[kAgent] = new Agent(opts) + this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : [] + + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } + + const resolvedUrl = new URL(opts.uri) + const { origin, port, host } = resolvedUrl + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + this[kClient] = clientFactory(resolvedUrl, { connect }) + this[kAgent] = new Agent({ + ...opts, + connect: async (opts, callback) => { + let requestedHost = opts.host + if (!opts.port) { + requestedHost += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedHost, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host + } + }) + if (statusCode !== 200) { + socket.on('error', () => {}).destroy() + callback(new RequestAbortedError('Proxy response !== 200 when HTTP Tunneling')) + } + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + callback(err) + } + } + }) + } + + dispatch (opts, handler) { + const { host } = new URL(opts.origin) + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + return this[kAgent].dispatch( + { + ...opts, + headers: { + ...headers, + host + } + }, + handler + ) + } + + async [kClose] () { + await this[kAgent].close() + await this[kClient].close() + } + + async [kDestroy] () { + await this[kAgent].destroy() + await this[kClient].destroy() + } +} + +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] + } + + return headersPair + } + + return headers +} + +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } +} + +module.exports = ProxyAgent diff --git a/node_modules/undici/lib/timers.js b/node_modules/undici/lib/timers.js new file mode 100644 index 0000000..5782217 --- /dev/null +++ b/node_modules/undici/lib/timers.js @@ -0,0 +1,97 @@ +'use strict' + +let fastNow = Date.now() +let fastNowTimeout + +const fastTimers = [] + +function onTimeout () { + fastNow = Date.now() + + let len = fastTimers.length + let idx = 0 + while (idx < len) { + const timer = fastTimers[idx] + + if (timer.state === 0) { + timer.state = fastNow + timer.delay + } else if (timer.state > 0 && fastNow >= timer.state) { + timer.state = -1 + timer.callback(timer.opaque) + } + + if (timer.state === -1) { + timer.state = -2 + if (idx !== len - 1) { + fastTimers[idx] = fastTimers.pop() + } else { + fastTimers.pop() + } + len -= 1 + } else { + idx += 1 + } + } + + if (fastTimers.length > 0) { + refreshTimeout() + } +} + +function refreshTimeout () { + if (fastNowTimeout && fastNowTimeout.refresh) { + fastNowTimeout.refresh() + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTimeout, 1e3) + if (fastNowTimeout.unref) { + fastNowTimeout.unref() + } + } +} + +class Timeout { + constructor (callback, delay, opaque) { + this.callback = callback + this.delay = delay + this.opaque = opaque + + // -2 not in timer list + // -1 in timer list but inactive + // 0 in timer list waiting for time + // > 0 in timer list waiting for time to expire + this.state = -2 + + this.refresh() + } + + refresh () { + if (this.state === -2) { + fastTimers.push(this) + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + } + + this.state = 0 + } + + clear () { + this.state = -1 + } +} + +module.exports = { + setTimeout (callback, delay, opaque) { + return delay < 1e3 + ? setTimeout(callback, delay, opaque) + : new Timeout(callback, delay, opaque) + }, + clearTimeout (timeout) { + if (timeout instanceof Timeout) { + timeout.clear() + } else { + clearTimeout(timeout) + } + } +} diff --git a/node_modules/undici/lib/websocket/connection.js b/node_modules/undici/lib/websocket/connection.js new file mode 100644 index 0000000..0977024 --- /dev/null +++ b/node_modules/undici/lib/websocket/connection.js @@ -0,0 +1,274 @@ +'use strict' + +const { randomBytes, createHash } = require('crypto') +const diagnosticsChannel = require('diagnostics_channel') +const { uid, states } = require('./constants') +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose +} = require('./symbols') +const { fireEvent, failWebsocketConnection } = require('./util') +const { CloseEvent } = require('./events') +const { makeRequest } = require('../fetch/request') +const { fetching } = require('../fetch/index') +const { getGlobalDispatcher } = require('../global') + +const channels = {} +channels.open = diagnosticsChannel.channel('undici:websocket:open') +channels.close = diagnosticsChannel.channel('undici:websocket:close') +channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') + +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any) => void} onEstablish + */ +function establishWebSocketConnection (url, protocols, ws, onEstablish) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }) + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13') + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + // TODO: enable once permessage-deflate is supported + const permessageDeflate = '' // 'permessage-deflate; 15' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + // request.headersList.append('sec-websocket-extensions', permessageDeflate) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: getGlobalDispatcher(), + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.') + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.') + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = createHash('sha1').update(keyValue + uid).digest('base64') + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') + + if (secExtension !== null && secExtension !== permessageDeflate) { + failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') + return + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') + + if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') + return + } + + response.socket.on('data', onSocketData) + response.socket.on('close', onSocketClose) + response.socket.on('error', onSocketError) + + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }) + } + + onEstablish(response) + } + }) + + return controller +} + +/** + * @param {Buffer} chunk + */ +function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause() + } +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ +function onSocketClose () { + const { ws } = this + + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] && ws[kReceivedClose] + + let code = 1005 + let reason = '' + + const result = ws[kByteParser].closingInfo + + if (result) { + code = result.code ?? 1005 + reason = result.reason + } else if (!ws[kSentClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + } + + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + fireEvent('close', ws, CloseEvent, { + wasClean, code, reason + }) + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }) + } +} + +function onSocketError (error) { + const { ws } = this + + ws[kReadyState] = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error) + } + + this.destroy() +} + +module.exports = { + establishWebSocketConnection +} diff --git a/node_modules/undici/lib/websocket/constants.js b/node_modules/undici/lib/websocket/constants.js new file mode 100644 index 0000000..406b8e3 --- /dev/null +++ b/node_modules/undici/lib/websocket/constants.js @@ -0,0 +1,51 @@ +'use strict' + +// This is a Globally Unique Identifier unique used +// to validate that the endpoint accepts websocket +// connections. +// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 +} + +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA +} + +const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 + +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 +} + +const emptyBuffer = Buffer.allocUnsafe(0) + +module.exports = { + uid, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer +} diff --git a/node_modules/undici/lib/websocket/events.js b/node_modules/undici/lib/websocket/events.js new file mode 100644 index 0000000..621a226 --- /dev/null +++ b/node_modules/undici/lib/websocket/events.js @@ -0,0 +1,303 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../core/util') +const { MessagePort } = require('worker_threads') + +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.MessageEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get data () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent) + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } +} + +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason + } +} + +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) + + super(type, eventInitDict) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict + } + + get message () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.error + } +} + +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) + +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) + +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) + +webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +] + +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + get defaultValue () { + return [] + } + } +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'error', + converter: webidl.converters.any + } +]) + +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent +} diff --git a/node_modules/undici/lib/websocket/frame.js b/node_modules/undici/lib/websocket/frame.js new file mode 100644 index 0000000..1df5e16 --- /dev/null +++ b/node_modules/undici/lib/websocket/frame.js @@ -0,0 +1,66 @@ +'use strict' + +const { randomBytes } = require('crypto') +const { maxUnsigned16Bit } = require('./constants') + +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + this.maskKey = randomBytes(4) + } + + createFrame (opcode) { + const bodyLength = this.frameData?.byteLength ?? 0 + + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset) + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = this.maskKey[0] + buffer[offset - 3] = this.maskKey[1] + buffer[offset - 2] = this.maskKey[2] + buffer[offset - 1] = this.maskKey[3] + + buffer[1] = payloadLength + + if (payloadLength === 126) { + new DataView(buffer.buffer).setUint16(2, bodyLength) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } + + buffer[1] |= 0x80 // MASK + + // mask body + for (let i = 0; i < bodyLength; i++) { + buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] + } + + return buffer + } +} + +module.exports = { + WebsocketFrameSend +} diff --git a/node_modules/undici/lib/websocket/receiver.js b/node_modules/undici/lib/websocket/receiver.js new file mode 100644 index 0000000..bdd2031 --- /dev/null +++ b/node_modules/undici/lib/websocket/receiver.js @@ -0,0 +1,344 @@ +'use strict' + +const { Writable } = require('stream') +const diagnosticsChannel = require('diagnostics_channel') +const { parserStates, opcodes, states, emptyBuffer } = require('./constants') +const { kReadyState, kSentClose, kResponse, kReceivedClose } = require('./symbols') +const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = require('./util') +const { WebsocketFrameSend } = require('./frame') + +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors + +const channels = {} +channels.ping = diagnosticsChannel.channel('undici:websocket:ping') +channels.pong = diagnosticsChannel.channel('undici:websocket:pong') + +class ByteParser extends Writable { + #buffers = [] + #byteOffset = 0 + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + constructor (ws) { + super() + + this.ws = ws + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length + + this.run(callback) + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (true) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.fin = (buffer[0] & 0x80) !== 0 + this.#info.opcode = buffer[0] & 0x0F + + // If we receive a fragmented message, we use the type of the first + // frame to parse the full message as binary/text, when it's terminated + this.#info.originalOpcode ??= this.#info.opcode + + this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION + + if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') + return + } + + const payloadLength = buffer[1] & 0x7F + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } + + if (this.#info.fragmented && payloadLength > 125) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') + return + } else if ( + (this.#info.opcode === opcodes.PING || + this.#info.opcode === opcodes.PONG || + this.#info.opcode === opcodes.CLOSE) && + payloadLength > 125 + ) { + // Control frames can have a payload length of 125 bytes MAX + failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') + return + } else if (this.#info.opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') + return + } + + const body = this.consume(payloadLength) + + this.#info.closeInfo = this.parseCloseBody(false, body) + + if (!this.ws[kSentClose]) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + const body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + const closeFrame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true + } + } + ) + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING + this.ws[kReceivedClose] = true + + this.end() + + return + } else if (this.#info.opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + const body = this.consume(payloadLength) + + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) + + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }) + } + } + + this.#state = parserStates.INFO + + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } else if (this.#info.opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + + const body = this.consume(payloadLength) + + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }) + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) + + // 2^31 is the maxinimum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') + return + } + + const lower = buffer.readUInt32BE(4) + + this.#info.payloadLength = (upper << 8) + lower + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + // If there is still more data in this chunk that needs to be read + return callback() + } else if (this.#byteOffset >= this.#info.payloadLength) { + // If the server sent multiple frames in a single chunk + + const body = this.consume(this.#info.payloadLength) + + this.#fragments.push(body) + + // If the frame is unfragmented, or a fragmented frame was terminated, + // a message was received + if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { + const fullMessage = Buffer.concat(this.#fragments) + + websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) + + this.#info = {} + this.#fragments.length = 0 + } + + this.#state = parserStates.INFO + } + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + break + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer|null} + */ + consume (n) { + if (n > this.#byteOffset) { + return null + } else if (n === 0) { + return emptyBuffer + } + + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length + return this.#buffers.shift() + } + + const buffer = Buffer.allocUnsafe(n) + let offset = 0 + + while (offset !== n) { + const next = this.#buffers[0] + const { length } = next + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += next.length + } + } + + this.#byteOffset -= n + + return buffer + } + + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } + + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } + + return { code } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } + + if (code !== undefined && !isValidStatusCode(code)) { + return null + } + + try { + // TODO: optimize this + reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) + } catch { + return null + } + + return { code, reason } + } + + get closingInfo () { + return this.#info.closeInfo + } +} + +module.exports = { + ByteParser +} diff --git a/node_modules/undici/lib/websocket/symbols.js b/node_modules/undici/lib/websocket/symbols.js new file mode 100644 index 0000000..11d03e3 --- /dev/null +++ b/node_modules/undici/lib/websocket/symbols.js @@ -0,0 +1,12 @@ +'use strict' + +module.exports = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') +} diff --git a/node_modules/undici/lib/websocket/util.js b/node_modules/undici/lib/websocket/util.js new file mode 100644 index 0000000..6c59b2c --- /dev/null +++ b/node_modules/undici/lib/websocket/util.js @@ -0,0 +1,200 @@ +'use strict' + +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols') +const { states, opcodes } = require('./constants') +const { MessageEvent, ErrorEvent } = require('./events') + +/* globals Blob */ + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN +} + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING +} + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosed (ws) { + return ws[kReadyState] === states.CLOSED +} + +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {EventInit | undefined} eventInitDict + */ +function fireEvent (e, target, eventConstructor = Event, eventInitDict) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ +function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = new Uint8Array(data).buffer + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, MessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }) +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (const char of protocol) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || + code > 0x7E || + char === '(' || + char === ')' || + char === '<' || + char === '>' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' || + code === 32 || // SP + code === 9 // HT + ) { + return false + } + } + + return true +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 +} + +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws + + controller.abort() + + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() + } + + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }) + } +} + +module.exports = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived +} diff --git a/node_modules/undici/lib/websocket/websocket.js b/node_modules/undici/lib/websocket/websocket.js new file mode 100644 index 0000000..164d24c --- /dev/null +++ b/node_modules/undici/lib/websocket/websocket.js @@ -0,0 +1,596 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') +const { DOMException } = require('../fetch/constants') +const { URLSerializer } = require('../fetch/dataURL') +const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = require('./constants') +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = require('./symbols') +const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = require('./util') +const { establishWebSocketConnection } = require('./connection') +const { WebsocketFrameSend } = require('./frame') +const { ByteParser } = require('./receiver') +const { kEnumerableProperty, isBlobLike } = require('../core/util') +const { types } = require('util') + +let experimentalWarned = false + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('WebSockets are experimental, expect them to change at any time.', { + code: 'UNDICI-WS' + }) + } + + url = webidl.converters.USVString(url) + protocols = webidl.converters['DOMString or sequence'](protocols) + + // 1. Let urlRecord be the result of applying the URL parser to url. + let urlRecord + + try { + urlRecord = new URL(url) + } catch (e) { + // 2. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 3. If urlRecord’s scheme is not "ws" or "wss", then throw a + // "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 4. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 5. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 6. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 7. Set this's url to urlRecord. + this[kWebSocketURL] = urlRecord + + // 8. Let client be this's relevant settings object. + + // 9. Run this step in parallel: + + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response) + ) + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob' + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, { clamp: true }) + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason) + } + + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + let reasonByteLength = 0 + + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason) + + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } + + // 3. Run the first matching steps from the following list: + if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { + // If this's ready state is CLOSING (2) or CLOSED (3) + // Do nothing. + } else if (!isEstablished(this)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(this, 'Connection was closed before it was established.') + this[kReadyState] = WebSocket.CLOSING + } else if (!isClosing(this)) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + socket.write(frame.createFrame(opcodes.CLOSE), (err) => { + if (!err) { + this[kSentClose] = true + } + }) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this[kReadyState] = states.CLOSING + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + this[kReadyState] = WebSocket.CLOSING + } + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) + + data = webidl.converters.WebSocketSendData(data) + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (this[kReadyState] === WebSocket.CONNECTING) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this) || isClosing(this)) { + return + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.TEXT) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + const ab = Buffer.from(data, data.byteOffset, data.byteLength) + + const frame = new WebsocketFrameSend(ab) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += ab.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= ab.byteLength + }) + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + const frame = new WebsocketFrameSend() + + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab) + frame.frameData = value + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + }) + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket) + + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket) + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } + + get extensions () { + webidl.brandCheck(this, WebSocket) + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket) + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket) + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket) + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket) + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } + + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket) + + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket) + + return this[kBinaryType] + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket) + + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob' + } else { + this[kBinaryType] = type + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response + + const parser = new ByteParser(this) + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume() + }) + + response.socket.ws = this + this[kByteParser] = parser + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + } +} + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) + +webidl.converters['DOMString or sequence'] = function (V) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } + + return webidl.converters.DOMString(V) +} + +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { + return webidl.converters.BufferSource(V) + } + } + + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket +} diff --git a/node_modules/undici/package.json b/node_modules/undici/package.json new file mode 100644 index 0000000..39be173 --- /dev/null +++ b/node_modules/undici/package.json @@ -0,0 +1,136 @@ +{ + "name": "undici", + "version": "5.21.0", + "description": "An HTTP/1.1 client, written from scratch for Node.js", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "author": "Matteo Collina ", + "contributors": [ + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + } + ], + "keywords": [ + "fetch", + "http", + "https", + "promise", + "request", + "curl", + "wget", + "xhr", + "whatwg" + ], + "main": "index.js", + "types": "index.d.ts", + "files": [ + "*.d.ts", + "index.js", + "index-fetch.js", + "lib", + "types", + "docs" + ], + "scripts": { + "build:node": "npx esbuild@0.14.38 index-fetch.js --bundle --platform=node --outfile=undici-fetch.js", + "prebuild:wasm": "docker build -t llhttp_wasm_builder -f build/Dockerfile .", + "build:wasm": "node build/wasm.js --docker", + "lint": "standard | snazzy", + "lint:fix": "standard --fix | snazzy", + "test": "npm run test:tap && npm run test:node-fetch && npm run test:fetch && npm run test:cookies && npm run test:wpt && npm run test:websocket && npm run test:jest && tsd", + "test:cookies": "node scripts/verifyVersion 16 || tap test/cookie/*.js", + "test:node-fetch": "node scripts/verifyVersion.js 16 || mocha test/node-fetch", + "test:fetch": "node scripts/verifyVersion.js 16 || (npm run build:node && tap test/fetch/*.js && tap test/webidl/*.js)", + "test:jest": "node scripts/verifyVersion.js 14 || jest", + "test:tap": "tap test/*.js test/diagnostics-channel/*.js", + "test:tdd": "tap test/*.js test/diagnostics-channel/*.js -w", + "test:typescript": "tsd && tsc test/imports/undici-import.ts", + "test:websocket": "node scripts/verifyVersion.js 18 || tap test/websocket/*.js", + "test:wpt": "node scripts/verifyVersion 18 || (node test/wpt/start-fetch.mjs && node test/wpt/start-FileAPI.mjs && node test/wpt/start-mimesniff.mjs && node test/wpt/start-xhr.mjs && node --no-warnings test/wpt/start-websockets.mjs)", + "coverage": "nyc --reporter=text --reporter=html npm run test", + "coverage:ci": "nyc --reporter=lcov npm run test", + "bench": "PORT=3042 concurrently -k -s first npm:bench:server npm:bench:run", + "bench:server": "node benchmarks/server.js", + "prebench:run": "node benchmarks/wait.js", + "bench:run": "CONNECTIONS=1 node --experimental-wasm-simd benchmarks/benchmark.js; CONNECTIONS=50 node --experimental-wasm-simd benchmarks/benchmark.js", + "serve:website": "docsify serve .", + "prepare": "husky install", + "fuzz": "jsfuzz test/fuzzing/fuzz.js corpus" + }, + "devDependencies": { + "@sinonjs/fake-timers": "^10.0.2", + "@types/node": "^18.0.3", + "abort-controller": "^3.0.0", + "atomic-sleep": "^1.0.0", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^3.0.2", + "chai-string": "^1.5.0", + "concurrently": "^7.1.0", + "cronometro": "^1.0.5", + "delay": "^5.0.0", + "dns-packet": "^5.4.0", + "docsify-cli": "^4.4.3", + "form-data": "^4.0.0", + "formdata-node": "^4.3.1", + "https-pem": "^3.0.0", + "husky": "^8.0.1", + "import-fresh": "^3.3.0", + "jest": "^29.0.2", + "jsdom": "^21.1.0", + "jsfuzz": "^1.0.15", + "mocha": "^10.0.0", + "p-timeout": "^3.2.0", + "pre-commit": "^1.2.2", + "proxy": "^1.0.2", + "proxyquire": "^2.1.3", + "sinon": "^15.0.0", + "snazzy": "^9.0.0", + "standard": "^17.0.0", + "table": "^6.8.0", + "tap": "^16.1.0", + "tsd": "^0.25.0", + "typescript": "^4.9.5", + "wait-on": "^6.0.0", + "ws": "^8.11.0" + }, + "engines": { + "node": ">=12.18" + }, + "standard": { + "env": [ + "mocha" + ], + "ignore": [ + "lib/llhttp/constants.js", + "lib/llhttp/utils.js", + "test/wpt/tests" + ] + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "esModuleInterop": true, + "lib": [ + "esnext" + ] + } + }, + "jest": { + "testMatch": [ + "/test/jest/**" + ] + }, + "dependencies": { + "busboy": "^1.6.0" + } +} diff --git a/node_modules/undici/types/agent.d.ts b/node_modules/undici/types/agent.d.ts new file mode 100644 index 0000000..0813735 --- /dev/null +++ b/node_modules/undici/types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from "./dispatcher"; + +export default Agent + +declare class Agent extends Dispatcher{ + constructor(opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean; + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean; + /** Dispatches a request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: URL, opts: Object): Dispatcher; + /** Integer. Default: `0` */ + maxRedirections?: number; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + /** Integer. */ + maxRedirections?: number; + } +} diff --git a/node_modules/undici/types/api.d.ts b/node_modules/undici/types/api.d.ts new file mode 100644 index 0000000..400341d --- /dev/null +++ b/node_modules/undici/types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +export { + request, + stream, + pipeline, + connect, + upgrade, +} + +/** Performs an HTTP request. */ +declare function request( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit & Partial>, +): Promise; + +/** A faster version of `request`. */ +declare function stream( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + factory: Dispatcher.StreamFactory +): Promise; + +/** For easy use with `stream.pipeline`. */ +declare function pipeline( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + handler: Dispatcher.PipelineHandler +): Duplex; + +/** Starts two-way communications with the requested resource. */ +declare function connect( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; + +/** Upgrade to a different protocol. */ +declare function upgrade( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; diff --git a/node_modules/undici/types/balanced-pool.d.ts b/node_modules/undici/types/balanced-pool.d.ts new file mode 100644 index 0000000..d1e9375 --- /dev/null +++ b/node_modules/undici/types/balanced-pool.d.ts @@ -0,0 +1,18 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +declare class BalancedPool extends Dispatcher { + constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + + addUpstream(upstream: string | URL): BalancedPool; + removeUpstream(upstream: string | URL): BalancedPool; + upstreams: Array; + + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; +} diff --git a/node_modules/undici/types/client.d.ts b/node_modules/undici/types/client.d.ts new file mode 100644 index 0000000..56074a1 --- /dev/null +++ b/node_modules/undici/types/client.d.ts @@ -0,0 +1,88 @@ +import { URL } from 'url' +import { TlsOptions } from 'tls' +import Dispatcher from './dispatcher' +import DispatchInterceptor from './dispatcher' +import buildConnector from "./connector"; + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor(url: string | URL, options?: Client.Options); + /** Property to get and set the pipelining factor. */ + pipelining: number; + /** `true` after `client.close()` has been called. */ + closed: boolean; + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean; +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout` when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + maxRedirections?: number; + /** TODO */ + connect?: buildConnector.BuildOptions | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client; diff --git a/node_modules/undici/types/connector.d.ts b/node_modules/undici/types/connector.d.ts new file mode 100644 index 0000000..d53d795 --- /dev/null +++ b/node_modules/undici/types/connector.d.ts @@ -0,0 +1,39 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export type connector = connectorAsync | connectorSync + + interface connectorSync { + (options: buildConnector.Options): Socket | TLSSocket + } + + interface connectorAsync { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/node_modules/undici/types/content-type.d.ts b/node_modules/undici/types/content-type.d.ts new file mode 100644 index 0000000..f2a87f1 --- /dev/null +++ b/node_modules/undici/types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/node_modules/undici/types/cookies.d.ts b/node_modules/undici/types/cookies.d.ts new file mode 100644 index 0000000..aa38cae --- /dev/null +++ b/node_modules/undici/types/cookies.d.ts @@ -0,0 +1,28 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void diff --git a/node_modules/undici/types/diagnostics-channel.d.ts b/node_modules/undici/types/diagnostics-channel.d.ts new file mode 100644 index 0000000..85d4482 --- /dev/null +++ b/node_modules/undici/types/diagnostics-channel.d.ts @@ -0,0 +1,67 @@ +import { Socket } from "net"; +import { URL } from "url"; +import Connector from "./connector"; +import Dispatcher from "./dispatcher"; + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: string; + addHeader(key: string, value: string): Request; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + type Error = unknown; + interface ConnectParams { + host: URL["host"]; + hostname: URL["hostname"]; + protocol: URL["protocol"]; + port: URL["port"]; + servername: string | null; + } + type Connector = Connector.connector; + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/node_modules/undici/types/dispatcher.d.ts b/node_modules/undici/types/dispatcher.d.ts new file mode 100644 index 0000000..c6b0c88 --- /dev/null +++ b/node_modules/undici/types/dispatcher.d.ts @@ -0,0 +1,237 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' + +type AbortSignal = unknown; + +export default Dispatcher + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise; + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise; + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + /** Upgrade to a different protocol. */ + upgrade(options: Dispatcher.UpgradeOptions): Promise; + upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close(): Promise; + close(callback: () => void): void; + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + + on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'drain', callback: (origin: URL) => void): this; + + + once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'drain', callback: (origin: URL) => void): this; + + + off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'drain', callback: (origin: URL) => void): this; + + + addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'drain', callback: (origin: URL) => void): this; + + removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; + + listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'drain'): ((origin: URL) => void)[]; + + rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; + + emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; + emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'drain', origin: URL): boolean; +} + +declare namespace Dispatcher { + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + } + export interface ConnectOptions { + path: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: unknown; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: unknown; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: unknown; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: unknown; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable; + export interface DispatchHandlers { + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + onConnect?(abort: () => void): void; + /** Invoked when an error has occurred. */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + onHeaders?(statusCode: number, headers: Buffer[] | string[] | null, resume: () => void): boolean; + /** Invoked when response payload data is received. */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable; + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; // throws on node v16.6.0 + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch'] + } +} diff --git a/node_modules/undici/types/errors.d.ts b/node_modules/undici/types/errors.d.ts new file mode 100644 index 0000000..fd2ce7c --- /dev/null +++ b/node_modules/undici/types/errors.d.ts @@ -0,0 +1,119 @@ +import { IncomingHttpHeaders } from "./header"; +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError'; + code: 'UND_ERR_CONNECT_TIMEOUT'; + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError'; + code: 'UND_ERR_HEADERS_TIMEOUT'; + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError'; + code: 'UND_ERR_BODY_TIMEOUT'; + } + + export class ResponseStatusCodeError extends UndiciError { + name: 'ResponseStatusCodeError'; + code: 'UND_ERR_RESPONSE_STATUS_CODE'; + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null; + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError'; + code: 'UND_ERR_INVALID_ARG'; + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError'; + code: 'UND_ERR_INVALID_RETURN_VALUE'; + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError'; + code: 'UND_ERR_ABORTED'; + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError'; + code: 'UND_ERR_INFO'; + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError'; + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError'; + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError'; + code: 'UND_ERR_DESTROYED'; + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError'; + code: 'UND_ERR_CLOSED'; + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError'; + code: 'UND_ERR_SOCKET'; + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError'; + code: 'UND_ERR_NOT_SUPPORTED'; + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError'; + code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError'; + code: string; + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError'; + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } +} diff --git a/node_modules/undici/types/fetch.d.ts b/node_modules/undici/types/fetch.d.ts new file mode 100644 index 0000000..fa4619c --- /dev/null +++ b/node_modules/undici/types/fetch.d.ts @@ -0,0 +1,209 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' + +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export interface BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = string[][] | Record> | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + method?: string + keepalive?: boolean + headers?: HeadersInit + body?: BodyInit + redirect?: RequestRedirect + integrity?: string + signal?: AbortSignal + credentials?: RequestCredentials + mode?: RequestMode + referrer?: string + referrerPolicy?: ReferrerPolicy + window?: null + dispatcher?: Dispatcher + duplex?: RequestDuplex +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url'; + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request implements BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrerPolicy: string + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response implements BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Response + + static error (): Response + static json(data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/node_modules/undici/types/file.d.ts b/node_modules/undici/types/file.d.ts new file mode 100644 index 0000000..c695b7a --- /dev/null +++ b/node_modules/undici/types/file.d.ts @@ -0,0 +1,39 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT) +/// + +import { Blob } from 'buffer' + +export interface BlobPropertyBag { + type?: string + endings?: 'native' | 'transparent' +} + +export interface FilePropertyBag extends BlobPropertyBag { + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + lastModified?: number +} + +export declare class File extends Blob { + /** + * Creates a new File instance. + * + * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + * @param fileName The name of the file. + * @param options An options object containing optional attributes for the file. + */ + constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag) + + /** + * Name of the file referenced by the File object. + */ + readonly name: string + + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + readonly lastModified: number + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici/types/filereader.d.ts b/node_modules/undici/types/filereader.d.ts new file mode 100644 index 0000000..f05d231 --- /dev/null +++ b/node_modules/undici/types/filereader.d.ts @@ -0,0 +1,54 @@ +/// + +import { Blob } from 'buffer' +import { DOMException, Event, EventInit, EventTarget } from './patch' + +export declare class FileReader { + __proto__: EventTarget & FileReader + + constructor () + + readAsArrayBuffer (blob: Blob): void + readAsBinaryString (blob: Blob): void + readAsText (blob: Blob, encoding?: string): void + readAsDataURL (blob: Blob): void + + abort (): void + + static readonly EMPTY = 0 + static readonly LOADING = 1 + static readonly DONE = 2 + + readonly EMPTY = 0 + readonly LOADING = 1 + readonly DONE = 2 + + readonly readyState: number + + readonly result: string | ArrayBuffer | null + + readonly error: DOMException | null + + onloadstart: null | ((this: FileReader, event: ProgressEvent) => void) + onprogress: null | ((this: FileReader, event: ProgressEvent) => void) + onload: null | ((this: FileReader, event: ProgressEvent) => void) + onabort: null | ((this: FileReader, event: ProgressEvent) => void) + onerror: null | ((this: FileReader, event: ProgressEvent) => void) + onloadend: null | ((this: FileReader, event: ProgressEvent) => void) +} + +export interface ProgressEventInit extends EventInit { + lengthComputable?: boolean + loaded?: number + total?: number +} + +export declare class ProgressEvent { + __proto__: Event & ProgressEvent + + constructor (type: string, eventInitDict?: ProgressEventInit) + + readonly lengthComputable: boolean + readonly loaded: number + readonly total: number +} diff --git a/node_modules/undici/types/formdata.d.ts b/node_modules/undici/types/formdata.d.ts new file mode 100644 index 0000000..df29a57 --- /dev/null +++ b/node_modules/undici/types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from './file' +import { SpecIterator, SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append(name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set(name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get(name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll(name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has(name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete(name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici/types/global-dispatcher.d.ts b/node_modules/undici/types/global-dispatcher.d.ts new file mode 100644 index 0000000..728f95c --- /dev/null +++ b/node_modules/undici/types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export { + getGlobalDispatcher, + setGlobalDispatcher +} + +declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; +declare function getGlobalDispatcher(): Dispatcher; diff --git a/node_modules/undici/types/global-origin.d.ts b/node_modules/undici/types/global-origin.d.ts new file mode 100644 index 0000000..322542d --- /dev/null +++ b/node_modules/undici/types/global-origin.d.ts @@ -0,0 +1,7 @@ +export { + setGlobalOrigin, + getGlobalOrigin +} + +declare function setGlobalOrigin(origin: string | URL | undefined): void; +declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/node_modules/undici/types/handlers.d.ts b/node_modules/undici/types/handlers.d.ts new file mode 100644 index 0000000..eb4f5a9 --- /dev/null +++ b/node_modules/undici/types/handlers.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export declare class RedirectHandler implements Dispatcher.DispatchHandlers{ + constructor (dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandlers{ + constructor (handler: Dispatcher.DispatchHandlers) +} diff --git a/node_modules/undici/types/header.d.ts b/node_modules/undici/types/header.d.ts new file mode 100644 index 0000000..bfdb329 --- /dev/null +++ b/node_modules/undici/types/header.d.ts @@ -0,0 +1,4 @@ +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record; diff --git a/node_modules/undici/types/interceptors.d.ts b/node_modules/undici/types/interceptors.d.ts new file mode 100644 index 0000000..047ac17 --- /dev/null +++ b/node_modules/undici/types/interceptors.d.ts @@ -0,0 +1,5 @@ +import Dispatcher from "./dispatcher"; + +type RedirectInterceptorOpts = { maxRedirections?: number } + +export declare function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatchInterceptor diff --git a/node_modules/undici/types/mock-agent.d.ts b/node_modules/undici/types/mock-agent.d.ts new file mode 100644 index 0000000..98cd645 --- /dev/null +++ b/node_modules/undici/types/mock-agent.d.ts @@ -0,0 +1,50 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch; + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor(options?: MockAgent.Options) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable; + get(origin: RegExp): TInterceptable; + get(origin: ((origin: string) => boolean)): TInterceptable; + /** Dispatches a mocked request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close(): Promise; + /** Disables mocking in MockAgent. */ + deactivate(): void; + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate(): void; + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect(): void; + enableNetConnect(host: string): void; + enableNetConnect(host: RegExp): void; + enableNetConnect(host: ((host: string) => boolean)): void; + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect(): void; + pendingInterceptors(): PendingInterceptor[]; + assertNoPendingInterceptors(options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void; +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Agent; + } +} diff --git a/node_modules/undici/types/mock-client.d.ts b/node_modules/undici/types/mock-client.d.ts new file mode 100644 index 0000000..51d008c --- /dev/null +++ b/node_modules/undici/types/mock-client.d.ts @@ -0,0 +1,25 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor(origin: string, options: MockClient.Options); + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici/types/mock-errors.d.ts b/node_modules/undici/types/mock-errors.d.ts new file mode 100644 index 0000000..3d9e727 --- /dev/null +++ b/node_modules/undici/types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor(message?: string); + name: 'MockNotMatchedError'; + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } +} diff --git a/node_modules/undici/types/mock-interceptor.d.ts b/node_modules/undici/types/mock-interceptor.d.ts new file mode 100644 index 0000000..6b3961c --- /dev/null +++ b/node_modules/undici/types/mock-interceptor.d.ts @@ -0,0 +1,93 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher'; +import { BodyInit, Headers } from './fetch' + +export { + Interceptable, + MockInterceptor, + MockScope +} + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor(mockDispatch: MockInterceptor.MockDispatch); + /** Delay a reply by a set amount of time in ms. */ + delay(waitInMs: number): MockScope; + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist(): MockScope; + /** Define a reply for a set amount of matching requests. */ + times(repeatTimes: number): MockScope; +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope; + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope; + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers(trailers: Record): MockInterceptor; + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength(): MockInterceptor; +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + origin: string; + method: string; + body?: BodyInit | Dispatcher.DispatchOptions['body']; + headers: Headers | Record; + maxRedirections: number; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string; + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; +} diff --git a/node_modules/undici/types/mock-pool.d.ts b/node_modules/undici/types/mock-pool.d.ts new file mode 100644 index 0000000..39e709a --- /dev/null +++ b/node_modules/undici/types/mock-pool.d.ts @@ -0,0 +1,25 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor(origin: string, options: MockPool.Options); + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici/types/patch.d.ts b/node_modules/undici/types/patch.d.ts new file mode 100644 index 0000000..3871acf --- /dev/null +++ b/node_modules/undici/types/patch.d.ts @@ -0,0 +1,71 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export type DOMException = typeof globalThis extends { DOMException: infer T } + ? T + : any + +export type EventTarget = typeof globalThis extends { EventTarget: infer T } + ? T + : { + addEventListener( + type: string, + listener: any, + options?: any, + ): void + dispatchEvent(event: Event): boolean + removeEventListener( + type: string, + listener: any, + options?: any | boolean, + ): void + } + +export type Event = typeof globalThis extends { Event: infer T } + ? T + : { + readonly bubbles: boolean + cancelBubble: () => void + readonly cancelable: boolean + readonly composed: boolean + composedPath(): [EventTarget?] + readonly currentTarget: EventTarget | null + readonly defaultPrevented: boolean + readonly eventPhase: 0 | 2 + readonly isTrusted: boolean + preventDefault(): void + returnValue: boolean + readonly srcElement: EventTarget | null + stopImmediatePropagation(): void + stopPropagation(): void + readonly target: EventTarget | null + readonly timeStamp: number + readonly type: string + } + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/node_modules/undici/types/pool-stats.d.ts b/node_modules/undici/types/pool-stats.d.ts new file mode 100644 index 0000000..8b6d2bf --- /dev/null +++ b/node_modules/undici/types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from "./pool" + +export default PoolStats + +declare class PoolStats { + constructor(pool: Pool); + /** Number of open socket connections in this pool. */ + connected: number; + /** Number of open socket connections in this pool that do not have an active request. */ + free: number; + /** Number of pending requests across all clients in this pool. */ + pending: number; + /** Number of queued requests across all clients in this pool. */ + queued: number; + /** Number of currently active requests across all clients in this pool. */ + running: number; + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number; +} diff --git a/node_modules/undici/types/pool.d.ts b/node_modules/undici/types/pool.d.ts new file mode 100644 index 0000000..7747d48 --- /dev/null +++ b/node_modules/undici/types/pool.d.ts @@ -0,0 +1,28 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from "./dispatcher"; + +export default Pool + +declare class Pool extends Dispatcher { + constructor(url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats; +} + +declare namespace Pool { + export type PoolStats = TPoolStats; + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + } +} diff --git a/node_modules/undici/types/proxy-agent.d.ts b/node_modules/undici/types/proxy-agent.d.ts new file mode 100644 index 0000000..96b2638 --- /dev/null +++ b/node_modules/undici/types/proxy-agent.d.ts @@ -0,0 +1,30 @@ +import Agent from './agent' +import buildConnector from './connector'; +import Client from './client' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' +import Pool from './pool' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor(options: ProxyAgent.Options | string) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + } +} diff --git a/node_modules/undici/types/readable.d.ts b/node_modules/undici/types/readable.d.ts new file mode 100644 index 0000000..032b53b --- /dev/null +++ b/node_modules/undici/types/readable.d.ts @@ -0,0 +1,61 @@ +import { Readable } from "stream"; +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor( + resume?: (this: Readable, size: number) => void | null, + abort?: () => void | null, + contentType?: string + ) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text(): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json(): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob(): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer(): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData(): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** Throws on node 16.6.0 + * + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 262144 + */ + dump(opts?: { limit: number }): Promise +} diff --git a/node_modules/undici/types/webidl.d.ts b/node_modules/undici/types/webidl.d.ts new file mode 100644 index 0000000..182d18e --- /dev/null +++ b/node_modules/undici/types/webidl.d.ts @@ -0,0 +1,218 @@ +// These types are not exported, and are only used internally + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + exception (opts: { header: string, message: string }): TypeError + /** + * @description Throw an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + IntegerPart (N: number): number +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + [Key: string]: (...args: any[]) => unknown +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (cls: Interface): ( + V: unknown, + opts?: { strict: boolean } + ) => asserts V is typeof cls + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: { + header: string + message?: string + }): void +} diff --git a/node_modules/undici/types/websocket.d.ts b/node_modules/undici/types/websocket.d.ts new file mode 100644 index 0000000..dadd801 --- /dev/null +++ b/node_modules/undici/types/websocket.d.ts @@ -0,0 +1,122 @@ +/// + +import type { MessagePort } from 'worker_threads' +import { + EventTarget, + Event, + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: Event + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[]): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} diff --git a/node_modules/unique-string/index.d.ts b/node_modules/unique-string/index.d.ts new file mode 100644 index 0000000..08959a6 --- /dev/null +++ b/node_modules/unique-string/index.d.ts @@ -0,0 +1,16 @@ +/** +Generate a unique random string. + +@returns A 32 character unique string. Matches the length of MD5, which is [unique enough](https://stackoverflow.com/a/2444336/64949) for non-crypto purposes. + +@example +``` +import uniqueString = require('unique-string'); + +uniqueString(); +//=> 'b4de2a49c8ffa3fbee04446f045483b2' +``` +*/ +declare function uniqueString(): string; + +export = uniqueString; diff --git a/node_modules/unique-string/index.js b/node_modules/unique-string/index.js new file mode 100644 index 0000000..5bc7787 --- /dev/null +++ b/node_modules/unique-string/index.js @@ -0,0 +1,4 @@ +'use strict'; +const cryptoRandomString = require('crypto-random-string'); + +module.exports = () => cryptoRandomString(32); diff --git a/node_modules/unique-string/license b/node_modules/unique-string/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/unique-string/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/unique-string/package.json b/node_modules/unique-string/package.json new file mode 100644 index 0000000..6da0a5b --- /dev/null +++ b/node_modules/unique-string/package.json @@ -0,0 +1,75 @@ +{ + "_args": [ + [ + "unique-string@2.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "unique-string@2.0.0", + "_id": "unique-string@2.0.0", + "_inBundle": false, + "_integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", + "_location": "/unique-string", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "unique-string@2.0.0", + "name": "unique-string", + "escapedName": "unique-string", + "rawSpec": "2.0.0", + "saveSpec": null, + "fetchSpec": "2.0.0" + }, + "_requiredBy": [ + "/configstore" + ], + "_resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", + "_spec": "2.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/unique-string/issues" + }, + "dependencies": { + "crypto-random-string": "^2.0.0" + }, + "description": "Generate a unique random string", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/unique-string#readme", + "keywords": [ + "unique", + "string", + "random", + "text", + "id", + "identifier", + "slug", + "hex" + ], + "license": "MIT", + "name": "unique-string", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/unique-string.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.0.0" +} diff --git a/node_modules/unique-string/readme.md b/node_modules/unique-string/readme.md new file mode 100644 index 0000000..9213f11 --- /dev/null +++ b/node_modules/unique-string/readme.md @@ -0,0 +1,32 @@ +# unique-string [![Build Status](https://travis-ci.org/sindresorhus/unique-string.svg?branch=master)](https://travis-ci.org/sindresorhus/unique-string) + +> Generate a unique random string + + +## Install + +``` +$ npm install unique-string +``` + + +## Usage + +```js +const uniqueString = require('unique-string'); + +uniqueString(); +//=> 'b4de2a49c8ffa3fbee04446f045483b2' +``` + + +## API + +### uniqueString() + +Returns a 32 character unique string. Matches the length of MD5, which is [unique enough](https://stackoverflow.com/a/2444336/64949) for non-crypto purposes. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/universalify/LICENSE b/node_modules/universalify/LICENSE new file mode 100644 index 0000000..514e84e --- /dev/null +++ b/node_modules/universalify/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2017, Ryan Zimmerman + +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/universalify/README.md b/node_modules/universalify/README.md new file mode 100644 index 0000000..487067b --- /dev/null +++ b/node_modules/universalify/README.md @@ -0,0 +1,76 @@ +# universalify + +[![Travis branch](https://img.shields.io/travis/RyanZim/universalify/master.svg)](https://travis-ci.org/RyanZim/universalify) +![Coveralls github branch](https://img.shields.io/coveralls/github/RyanZim/universalify/master.svg) +![npm](https://img.shields.io/npm/dm/universalify.svg) +![npm](https://img.shields.io/npm/l/universalify.svg) + +Make a callback- or promise-based function support both promises and callbacks. + +Uses the native promise implementation. + +## Installation + +```bash +npm install universalify +``` + +## API + +### `universalify.fromCallback(fn)` + +Takes a callback-based function to universalify, and returns the universalified function. + +Function must take a callback as the last parameter that will be called with the signature `(error, result)`. `universalify` does not support calling the callback with more than three arguments, and does not ensure that the callback is only called once. + +```js +function callbackFn (n, cb) { + setTimeout(() => cb(null, n), 15) +} + +const fn = universalify.fromCallback(callbackFn) + +// Works with Promises: +fn('Hello World!') +.then(result => console.log(result)) // -> Hello World! +.catch(error => console.error(error)) + +// Works with Callbacks: +fn('Hi!', (error, result) => { + if (error) return console.error(error) + console.log(result) + // -> Hi! +}) +``` + +### `universalify.fromPromise(fn)` + +Takes a promise-based function to universalify, and returns the universalified function. + +Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned. + +```js +function promiseFn (n) { + return new Promise(resolve => { + setTimeout(() => resolve(n), 15) + }) +} + +const fn = universalify.fromPromise(promiseFn) + +// Works with Promises: +fn('Hello World!') +.then(result => console.log(result)) // -> Hello World! +.catch(error => console.error(error)) + +// Works with Callbacks: +fn('Hi!', (error, result) => { + if (error) return console.error(error) + console.log(result) + // -> Hi! +}) +``` + +## License + +MIT diff --git a/node_modules/universalify/index.js b/node_modules/universalify/index.js new file mode 100644 index 0000000..0c9ba39 --- /dev/null +++ b/node_modules/universalify/index.js @@ -0,0 +1,25 @@ +'use strict' + +exports.fromCallback = function (fn) { + return Object.defineProperty(function () { + if (typeof arguments[arguments.length - 1] === 'function') fn.apply(this, arguments) + else { + return new Promise((resolve, reject) => { + arguments[arguments.length] = (err, res) => { + if (err) return reject(err) + resolve(res) + } + arguments.length++ + fn.apply(this, arguments) + }) + } + }, 'name', { value: fn.name }) +} + +exports.fromPromise = function (fn) { + return Object.defineProperty(function () { + const cb = arguments[arguments.length - 1] + if (typeof cb !== 'function') return fn.apply(this, arguments) + else fn.apply(this, arguments).then(r => cb(null, r), cb) + }, 'name', { value: fn.name }) +} diff --git a/node_modules/universalify/package.json b/node_modules/universalify/package.json new file mode 100644 index 0000000..0da5e6a --- /dev/null +++ b/node_modules/universalify/package.json @@ -0,0 +1,67 @@ +{ + "_args": [ + [ + "universalify@0.1.2", + "/home/other/discord_bot" + ] + ], + "_from": "universalify@0.1.2", + "_id": "universalify@0.1.2", + "_inBundle": false, + "_integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "_location": "/universalify", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "universalify@0.1.2", + "name": "universalify", + "escapedName": "universalify", + "rawSpec": "0.1.2", + "saveSpec": null, + "fetchSpec": "0.1.2" + }, + "_requiredBy": [ + "/tough-cookie" + ], + "_resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "_spec": "0.1.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "Ryan Zimmerman", + "email": "opensrc@ryanzim.com" + }, + "bugs": { + "url": "https://github.com/RyanZim/universalify/issues" + }, + "description": "Make a callback- or promise-based function support both promises and callbacks.", + "devDependencies": { + "colortape": "^0.1.2", + "coveralls": "^3.0.1", + "nyc": "^10.2.0", + "standard": "^10.0.1", + "tape": "^4.6.3" + }, + "engines": { + "node": ">= 4.0.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/RyanZim/universalify#readme", + "keywords": [ + "callback", + "native", + "promise" + ], + "license": "MIT", + "name": "universalify", + "repository": { + "type": "git", + "url": "git+https://github.com/RyanZim/universalify.git" + }, + "scripts": { + "test": "standard && nyc tape test/*.js | colortape" + }, + "version": "0.1.2" +} diff --git a/node_modules/update-notifier/check.js b/node_modules/update-notifier/check.js new file mode 100644 index 0000000..fc0ee9c --- /dev/null +++ b/node_modules/update-notifier/check.js @@ -0,0 +1,28 @@ +/* eslint-disable unicorn/no-process-exit */ +'use strict'; +let updateNotifier = require('.'); + +const options = JSON.parse(process.argv[2]); + +updateNotifier = new updateNotifier.UpdateNotifier(options); + +(async () => { + // Exit process when offline + setTimeout(process.exit, 1000 * 30); + + const update = await updateNotifier.fetchInfo(); + + // Only update the last update check time on success + updateNotifier.config.set('lastUpdateCheck', Date.now()); + + if (update.type && update.type !== 'latest') { + updateNotifier.config.set('update', update); + } + + // Call process exit explicitly to terminate the child process, + // otherwise the child process will run forever, according to the Node.js docs + process.exit(); +})().catch(error => { + console.error(error); + process.exit(1); +}); diff --git a/node_modules/update-notifier/index.js b/node_modules/update-notifier/index.js new file mode 100644 index 0000000..5e89216 --- /dev/null +++ b/node_modules/update-notifier/index.js @@ -0,0 +1,188 @@ +'use strict'; +const {spawn} = require('child_process'); +const path = require('path'); +const {format} = require('util'); +const importLazy = require('import-lazy')(require); + +const configstore = importLazy('configstore'); +const chalk = importLazy('chalk'); +const semver = importLazy('semver'); +const semverDiff = importLazy('semver-diff'); +const latestVersion = importLazy('latest-version'); +const isNpm = importLazy('is-npm'); +const isInstalledGlobally = importLazy('is-installed-globally'); +const isYarnGlobal = importLazy('is-yarn-global'); +const hasYarn = importLazy('has-yarn'); +const boxen = importLazy('boxen'); +const xdgBasedir = importLazy('xdg-basedir'); +const isCi = importLazy('is-ci'); +const pupa = importLazy('pupa'); + +const ONE_DAY = 1000 * 60 * 60 * 24; + +class UpdateNotifier { + constructor(options = {}) { + this.options = options; + options.pkg = options.pkg || {}; + options.distTag = options.distTag || 'latest'; + + // Reduce pkg to the essential keys. with fallback to deprecated options + // TODO: Remove deprecated options at some point far into the future + options.pkg = { + name: options.pkg.name || options.packageName, + version: options.pkg.version || options.packageVersion + }; + + if (!options.pkg.name || !options.pkg.version) { + throw new Error('pkg.name and pkg.version required'); + } + + this.packageName = options.pkg.name; + this.packageVersion = options.pkg.version; + this.updateCheckInterval = typeof options.updateCheckInterval === 'number' ? options.updateCheckInterval : ONE_DAY; + this.disabled = 'NO_UPDATE_NOTIFIER' in process.env || + process.env.NODE_ENV === 'test' || + process.argv.includes('--no-update-notifier') || + isCi(); + this.shouldNotifyInNpmScript = options.shouldNotifyInNpmScript; + + if (!this.disabled) { + try { + const ConfigStore = configstore(); + this.config = new ConfigStore(`update-notifier-${this.packageName}`, { + optOut: false, + // Init with the current time so the first check is only + // after the set interval, so not to bother users right away + lastUpdateCheck: Date.now() + }); + } catch { + // Expecting error code EACCES or EPERM + const message = + chalk().yellow(format(' %s update check failed ', options.pkg.name)) + + format('\n Try running with %s or get access ', chalk().cyan('sudo')) + + '\n to the local update config store via \n' + + chalk().cyan(format(' sudo chown -R $USER:$(id -gn $USER) %s ', xdgBasedir().config)); + + process.on('exit', () => { + console.error(boxen()(message, {align: 'center'})); + }); + } + } + } + + check() { + if ( + !this.config || + this.config.get('optOut') || + this.disabled + ) { + return; + } + + this.update = this.config.get('update'); + + if (this.update) { + // Use the real latest version instead of the cached one + this.update.current = this.packageVersion; + + // Clear cached information + this.config.delete('update'); + } + + // Only check for updates on a set interval + if (Date.now() - this.config.get('lastUpdateCheck') < this.updateCheckInterval) { + return; + } + + // Spawn a detached process, passing the options as an environment property + spawn(process.execPath, [path.join(__dirname, 'check.js'), JSON.stringify(this.options)], { + detached: true, + stdio: 'ignore' + }).unref(); + } + + async fetchInfo() { + const {distTag} = this.options; + const latest = await latestVersion()(this.packageName, {version: distTag}); + + return { + latest, + current: this.packageVersion, + type: semverDiff()(this.packageVersion, latest) || distTag, + name: this.packageName + }; + } + + notify(options) { + const suppressForNpm = !this.shouldNotifyInNpmScript && isNpm().isNpmOrYarn; + if (!process.stdout.isTTY || suppressForNpm || !this.update || !semver().gt(this.update.latest, this.update.current)) { + return this; + } + + options = { + isGlobal: isInstalledGlobally(), + isYarnGlobal: isYarnGlobal()(), + ...options + }; + + let installCommand; + if (options.isYarnGlobal) { + installCommand = `yarn global add ${this.packageName}`; + } else if (options.isGlobal) { + installCommand = `npm i -g ${this.packageName}`; + } else if (hasYarn()()) { + installCommand = `yarn add ${this.packageName}`; + } else { + installCommand = `npm i ${this.packageName}`; + } + + const defaultTemplate = 'Update available ' + + chalk().dim('{currentVersion}') + + chalk().reset(' → ') + + chalk().green('{latestVersion}') + + ' \nRun ' + chalk().cyan('{updateCommand}') + ' to update'; + + const template = options.message || defaultTemplate; + + options.boxenOptions = options.boxenOptions || { + padding: 1, + margin: 1, + align: 'center', + borderColor: 'yellow', + borderStyle: 'round' + }; + + const message = boxen()( + pupa()(template, { + packageName: this.packageName, + currentVersion: this.update.current, + latestVersion: this.update.latest, + updateCommand: installCommand + }), + options.boxenOptions + ); + + if (options.defer === false) { + console.error(message); + } else { + process.on('exit', () => { + console.error(message); + }); + + process.on('SIGINT', () => { + console.error(''); + process.exit(); + }); + } + + return this; + } +} + +module.exports = options => { + const updateNotifier = new UpdateNotifier(options); + updateNotifier.check(); + return updateNotifier; +}; + +module.exports.UpdateNotifier = UpdateNotifier; diff --git a/node_modules/update-notifier/license b/node_modules/update-notifier/license new file mode 100644 index 0000000..cea5a35 --- /dev/null +++ b/node_modules/update-notifier/license @@ -0,0 +1,9 @@ +Copyright Google + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/update-notifier/node_modules/.bin/semver b/node_modules/update-notifier/node_modules/.bin/semver new file mode 120000 index 0000000..5aaadf4 --- /dev/null +++ b/node_modules/update-notifier/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver.js \ No newline at end of file diff --git a/node_modules/update-notifier/node_modules/semver/CHANGELOG.md b/node_modules/update-notifier/node_modules/semver/CHANGELOG.md new file mode 100644 index 0000000..220af17 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/CHANGELOG.md @@ -0,0 +1,111 @@ +# changes log + +## 7.3.0 + +* Add `subset(r1, r2)` method to determine if `r1` range is entirely + contained by `r2` range. + +## 7.2.3 + +* Fix handling of `includePrelease` mode where version ranges like `1.0.0 - + 2.0.0` would include `3.0.0-pre` and not `1.0.0-pre`. + +## 7.2.2 + +* Fix bug where `2.0.0-pre` would be included in `^1.0.0` if + `includePrerelease` was set to true. + +## 7.2.0 + +* Add `simplifyRange` method to attempt to generate a more human-readable + range expression that is equivalent to a supplied range, for a given set + of versions. + +## 7.1.2 + +* Remove fancy lazy-loading logic, as it was causing problems for webpack + users. + +## 7.1.0 + +* Add `require('semver/preload')` to load the entire module without using + lazy getter methods. + +## 7.0.0 + +* Refactor module into separate files for better tree-shaking +* Drop support for very old node versions, use const/let, `=>` functions, + and classes. + +## 6.3.0 + +* Expose the token enum on the exports + +## 6.2.0 + +* Coerce numbers to strings when passed to semver.coerce() +* Add `rtl` option to coerce from right to left + +## 6.1.3 + +* Handle X-ranges properly in includePrerelease mode + +## 6.1.2 + +* Do not throw when testing invalid version strings + +## 6.1.1 + +* Add options support for semver.coerce() +* Handle undefined version passed to Range.test + +## 6.1.0 + +* Add semver.compareBuild function +* Support `*` in semver.intersects + +## 6.0 + +* Fix `intersects` logic. + + This is technically a bug fix, but since it is also a change to behavior + that may require users updating their code, it is marked as a major + version increment. + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/node_modules/update-notifier/node_modules/semver/LICENSE b/node_modules/update-notifier/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/update-notifier/node_modules/semver/README.md b/node_modules/update-notifier/node_modules/semver/README.md new file mode 100644 index 0000000..9bef045 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/README.md @@ -0,0 +1,566 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about, if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const simplifyRange = require('semver/ranges/simplify') +const rangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need, if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` diff --git a/node_modules/update-notifier/node_modules/semver/bin/semver.js b/node_modules/update-notifier/node_modules/semver/bin/semver.js new file mode 100755 index 0000000..73fe295 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/bin/semver.js @@ -0,0 +1,173 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +const semver = require('../') + +let reverse = false + +const options = {} + +const main = () => { + if (!argv.length) return help() + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + const options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const success = () => { + const compare = reverse ? 'rcompare' : 'compare' + versions.sort((a, b) => { + return semver[compare](a, b, options) + }).map((v) => { + return semver.clean(v, options) + }).map((v) => { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach((v, i, _) => { console.log(v) }) +} + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/update-notifier/node_modules/semver/classes/comparator.js b/node_modules/update-notifier/node_modules/semver/classes/comparator.js new file mode 100644 index 0000000..dbbef2d --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/classes/comparator.js @@ -0,0 +1,135 @@ +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + const sameSemVer = this.semver.version === comp.semver.version + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<') + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>') + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const {re, t} = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/update-notifier/node_modules/semver/classes/index.js b/node_modules/update-notifier/node_modules/semver/classes/index.js new file mode 100644 index 0000000..198b84d --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/classes/index.js @@ -0,0 +1,5 @@ +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js') +} diff --git a/node_modules/update-notifier/node_modules/semver/classes/range.js b/node_modules/update-notifier/node_modules/semver/classes/range.js new file mode 100644 index 0000000..aa04f6b --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/classes/range.js @@ -0,0 +1,510 @@ +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range + .split(/\s*\|\|\s*/) + // map the range to a 2d array of comparators + .map(range => this.parseRange(range.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) + this.set = [first] + else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.format() + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim() + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim() + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(',') + const memoKey = `parseRange:${memoOpts}:${range}` + const cached = cache.get(memoKey) + if (cached) + return cached + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[t.COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + // in loose mode, throw out any that are not valid comparators + .filter(this.options.loose ? comp => !!comp.match(compRe) : () => true) + .map(comp => new Comparator(comp, this.options)) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const l = rangeList.length + const rangeMap = new Map() + for (const comp of rangeList) { + if (isNullSet(comp)) + return [comp] + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) + rangeMap.delete('') + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} +module.exports = Range + +const LRU = require('lru-cache') +const cache = new LRU({ max: 1000 }) + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace +} = require('../internal/re') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceTilde(comp, options) + }).join(' ') + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((comp) => { + return replaceCaret(comp, options) + }).join(' ') + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map((comp) => { + return replaceXRange(comp, options) + }).join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') + pr = '-0' + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp.trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return (`${from} ${to}`).trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/update-notifier/node_modules/semver/classes/semver.js b/node_modules/update-notifier/node_modules/semver/classes/semver.js new file mode 100644 index 0000000..ed81a7e --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/classes/semver.js @@ -0,0 +1,287 @@ +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format() + this.raw = this.version + return this + } +} + +module.exports = SemVer diff --git a/node_modules/update-notifier/node_modules/semver/functions/clean.js b/node_modules/update-notifier/node_modules/semver/functions/clean.js new file mode 100644 index 0000000..811fe6b --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/clean.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/update-notifier/node_modules/semver/functions/cmp.js b/node_modules/update-notifier/node_modules/semver/functions/cmp.js new file mode 100644 index 0000000..3b89db7 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/cmp.js @@ -0,0 +1,48 @@ +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/update-notifier/node_modules/semver/functions/coerce.js b/node_modules/update-notifier/node_modules/semver/functions/coerce.js new file mode 100644 index 0000000..106ca71 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/coerce.js @@ -0,0 +1,51 @@ +const SemVer = require('../classes/semver') +const parse = require('./parse') +const {re, t} = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) + return null + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) +} +module.exports = coerce diff --git a/node_modules/update-notifier/node_modules/semver/functions/compare-build.js b/node_modules/update-notifier/node_modules/semver/functions/compare-build.js new file mode 100644 index 0000000..9eb881b --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/compare-build.js @@ -0,0 +1,7 @@ +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/update-notifier/node_modules/semver/functions/compare-loose.js b/node_modules/update-notifier/node_modules/semver/functions/compare-loose.js new file mode 100644 index 0000000..4881fbe --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/update-notifier/node_modules/semver/functions/compare.js b/node_modules/update-notifier/node_modules/semver/functions/compare.js new file mode 100644 index 0000000..748b7af --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/compare.js @@ -0,0 +1,5 @@ +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/update-notifier/node_modules/semver/functions/diff.js b/node_modules/update-notifier/node_modules/semver/functions/diff.js new file mode 100644 index 0000000..87200ef --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/diff.js @@ -0,0 +1,23 @@ +const parse = require('./parse') +const eq = require('./eq') + +const diff = (version1, version2) => { + if (eq(version1, version2)) { + return null + } else { + const v1 = parse(version1) + const v2 = parse(version2) + const hasPre = v1.prerelease.length || v2.prerelease.length + const prefix = hasPre ? 'pre' : '' + const defaultResult = hasPre ? 'prerelease' : '' + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} +module.exports = diff diff --git a/node_modules/update-notifier/node_modules/semver/functions/eq.js b/node_modules/update-notifier/node_modules/semver/functions/eq.js new file mode 100644 index 0000000..271fed9 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/eq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/update-notifier/node_modules/semver/functions/gt.js b/node_modules/update-notifier/node_modules/semver/functions/gt.js new file mode 100644 index 0000000..d9b2156 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/gt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/update-notifier/node_modules/semver/functions/gte.js b/node_modules/update-notifier/node_modules/semver/functions/gte.js new file mode 100644 index 0000000..5aeaa63 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/gte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/update-notifier/node_modules/semver/functions/inc.js b/node_modules/update-notifier/node_modules/semver/functions/inc.js new file mode 100644 index 0000000..aa4d83a --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/inc.js @@ -0,0 +1,15 @@ +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options + options = undefined + } + + try { + return new SemVer(version, options).inc(release, identifier).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/update-notifier/node_modules/semver/functions/lt.js b/node_modules/update-notifier/node_modules/semver/functions/lt.js new file mode 100644 index 0000000..b440ab7 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/lt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/update-notifier/node_modules/semver/functions/lte.js b/node_modules/update-notifier/node_modules/semver/functions/lte.js new file mode 100644 index 0000000..6dcc956 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/lte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/update-notifier/node_modules/semver/functions/major.js b/node_modules/update-notifier/node_modules/semver/functions/major.js new file mode 100644 index 0000000..4283165 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/major.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/update-notifier/node_modules/semver/functions/minor.js b/node_modules/update-notifier/node_modules/semver/functions/minor.js new file mode 100644 index 0000000..57b3455 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/minor.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/update-notifier/node_modules/semver/functions/neq.js b/node_modules/update-notifier/node_modules/semver/functions/neq.js new file mode 100644 index 0000000..f944c01 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/neq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/update-notifier/node_modules/semver/functions/parse.js b/node_modules/update-notifier/node_modules/semver/functions/parse.js new file mode 100644 index 0000000..11f20f0 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/parse.js @@ -0,0 +1,33 @@ +const {MAX_LENGTH} = require('../internal/constants') +const { re, t } = require('../internal/re') +const SemVer = require('../classes/semver') + +const parseOptions = require('../internal/parse-options') +const parse = (version, options) => { + options = parseOptions(options) + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +module.exports = parse diff --git a/node_modules/update-notifier/node_modules/semver/functions/patch.js b/node_modules/update-notifier/node_modules/semver/functions/patch.js new file mode 100644 index 0000000..63afca2 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/patch.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/update-notifier/node_modules/semver/functions/prerelease.js b/node_modules/update-notifier/node_modules/semver/functions/prerelease.js new file mode 100644 index 0000000..06aa132 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/prerelease.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/update-notifier/node_modules/semver/functions/rcompare.js b/node_modules/update-notifier/node_modules/semver/functions/rcompare.js new file mode 100644 index 0000000..0ac509e --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/rcompare.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/update-notifier/node_modules/semver/functions/rsort.js b/node_modules/update-notifier/node_modules/semver/functions/rsort.js new file mode 100644 index 0000000..82404c5 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/rsort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/update-notifier/node_modules/semver/functions/satisfies.js b/node_modules/update-notifier/node_modules/semver/functions/satisfies.js new file mode 100644 index 0000000..50af1c1 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/satisfies.js @@ -0,0 +1,10 @@ +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/update-notifier/node_modules/semver/functions/sort.js b/node_modules/update-notifier/node_modules/semver/functions/sort.js new file mode 100644 index 0000000..4d10917 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/sort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/update-notifier/node_modules/semver/functions/valid.js b/node_modules/update-notifier/node_modules/semver/functions/valid.js new file mode 100644 index 0000000..f27bae1 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/functions/valid.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/update-notifier/node_modules/semver/index.js b/node_modules/update-notifier/node_modules/semver/index.js new file mode 100644 index 0000000..57e2ae6 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/index.js @@ -0,0 +1,48 @@ +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +module.exports = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: require('./internal/constants').SEMVER_SPEC_VERSION, + SemVer: require('./classes/semver'), + compareIdentifiers: require('./internal/identifiers').compareIdentifiers, + rcompareIdentifiers: require('./internal/identifiers').rcompareIdentifiers, + parse: require('./functions/parse'), + valid: require('./functions/valid'), + clean: require('./functions/clean'), + inc: require('./functions/inc'), + diff: require('./functions/diff'), + major: require('./functions/major'), + minor: require('./functions/minor'), + patch: require('./functions/patch'), + prerelease: require('./functions/prerelease'), + compare: require('./functions/compare'), + rcompare: require('./functions/rcompare'), + compareLoose: require('./functions/compare-loose'), + compareBuild: require('./functions/compare-build'), + sort: require('./functions/sort'), + rsort: require('./functions/rsort'), + gt: require('./functions/gt'), + lt: require('./functions/lt'), + eq: require('./functions/eq'), + neq: require('./functions/neq'), + gte: require('./functions/gte'), + lte: require('./functions/lte'), + cmp: require('./functions/cmp'), + coerce: require('./functions/coerce'), + Comparator: require('./classes/comparator'), + Range: require('./classes/range'), + satisfies: require('./functions/satisfies'), + toComparators: require('./ranges/to-comparators'), + maxSatisfying: require('./ranges/max-satisfying'), + minSatisfying: require('./ranges/min-satisfying'), + minVersion: require('./ranges/min-version'), + validRange: require('./ranges/valid'), + outside: require('./ranges/outside'), + gtr: require('./ranges/gtr'), + ltr: require('./ranges/ltr'), + intersects: require('./ranges/intersects'), + simplifyRange: require('./ranges/simplify'), + subset: require('./ranges/subset'), +} diff --git a/node_modules/update-notifier/node_modules/semver/internal/constants.js b/node_modules/update-notifier/node_modules/semver/internal/constants.js new file mode 100644 index 0000000..49df215 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/internal/constants.js @@ -0,0 +1,17 @@ +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +module.exports = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH +} diff --git a/node_modules/update-notifier/node_modules/semver/internal/debug.js b/node_modules/update-notifier/node_modules/semver/internal/debug.js new file mode 100644 index 0000000..1c00e13 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/internal/debug.js @@ -0,0 +1,9 @@ +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/update-notifier/node_modules/semver/internal/identifiers.js b/node_modules/update-notifier/node_modules/semver/internal/identifiers.js new file mode 100644 index 0000000..ed13094 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/internal/identifiers.js @@ -0,0 +1,23 @@ +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers +} diff --git a/node_modules/update-notifier/node_modules/semver/internal/parse-options.js b/node_modules/update-notifier/node_modules/semver/internal/parse-options.js new file mode 100644 index 0000000..42d2ebd --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/internal/parse-options.js @@ -0,0 +1,11 @@ +// parse out just the options we care about so we always get a consistent +// obj with keys in a consistent order. +const opts = ['includePrerelease', 'loose', 'rtl'] +const parseOptions = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((options, k) => { + options[k] = true + return options + }, {}) +module.exports = parseOptions diff --git a/node_modules/update-notifier/node_modules/semver/internal/re.js b/node_modules/update-notifier/node_modules/semver/internal/re.js new file mode 100644 index 0000000..54d4176 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/internal/re.js @@ -0,0 +1,182 @@ +const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const createToken = (name, value, isGlobal) => { + const index = R++ + debug(index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$') diff --git a/node_modules/update-notifier/node_modules/semver/package.json b/node_modules/update-notifier/node_modules/semver/package.json new file mode 100644 index 0000000..9a7d814 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/package.json @@ -0,0 +1,76 @@ +{ + "_args": [ + [ + "semver@7.3.5", + "/home/other/discord_bot" + ] + ], + "_from": "semver@7.3.5", + "_id": "semver@7.3.5", + "_inBundle": false, + "_integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "_location": "/update-notifier/semver", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "semver@7.3.5", + "name": "semver", + "escapedName": "semver", + "rawSpec": "7.3.5", + "saveSpec": null, + "fetchSpec": "7.3.5" + }, + "_requiredBy": [ + "/update-notifier" + ], + "_resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "_spec": "7.3.5", + "_where": "/home/other/discord_bot", + "bin": { + "semver": "bin/semver.js" + }, + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "description": "The semantic version parser used by npm.", + "devDependencies": { + "tap": "^14.10.7" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "bin/**/*.js", + "range.bnf", + "classes/**/*.js", + "functions/**/*.js", + "internal/**/*.js", + "ranges/**/*.js", + "index.js", + "preload.js" + ], + "homepage": "https://github.com/npm/node-semver#readme", + "license": "ISC", + "main": "index.js", + "name": "semver", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "scripts": { + "postpublish": "git push origin --follow-tags", + "postversion": "npm publish", + "preversion": "npm test", + "snap": "tap", + "test": "tap" + }, + "tap": { + "check-coverage": true, + "coverage-map": "map.js" + }, + "version": "7.3.5" +} diff --git a/node_modules/update-notifier/node_modules/semver/preload.js b/node_modules/update-notifier/node_modules/semver/preload.js new file mode 100644 index 0000000..947cd4f --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/preload.js @@ -0,0 +1,2 @@ +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/update-notifier/node_modules/semver/range.bnf b/node_modules/update-notifier/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/update-notifier/node_modules/semver/ranges/gtr.js b/node_modules/update-notifier/node_modules/semver/ranges/gtr.js new file mode 100644 index 0000000..db7e355 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/gtr.js @@ -0,0 +1,4 @@ +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/update-notifier/node_modules/semver/ranges/intersects.js b/node_modules/update-notifier/node_modules/semver/ranges/intersects.js new file mode 100644 index 0000000..3d1a6f3 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/intersects.js @@ -0,0 +1,7 @@ +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} +module.exports = intersects diff --git a/node_modules/update-notifier/node_modules/semver/ranges/ltr.js b/node_modules/update-notifier/node_modules/semver/ranges/ltr.js new file mode 100644 index 0000000..528a885 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/ltr.js @@ -0,0 +1,4 @@ +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/update-notifier/node_modules/semver/ranges/max-satisfying.js b/node_modules/update-notifier/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 0000000..6e3d993 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,25 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/update-notifier/node_modules/semver/ranges/min-satisfying.js b/node_modules/update-notifier/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 0000000..9b60974 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,24 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/update-notifier/node_modules/semver/ranges/min-version.js b/node_modules/update-notifier/node_modules/semver/ranges/min-version.js new file mode 100644 index 0000000..2fac412 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/min-version.js @@ -0,0 +1,60 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) + minver = setMin + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/update-notifier/node_modules/semver/ranges/outside.js b/node_modules/update-notifier/node_modules/semver/ranges/outside.js new file mode 100644 index 0000000..2a4b0a1 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/outside.js @@ -0,0 +1,80 @@ +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const {ANY} = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/update-notifier/node_modules/semver/ranges/simplify.js b/node_modules/update-notifier/node_modules/semver/ranges/simplify.js new file mode 100644 index 0000000..b792f97 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/simplify.js @@ -0,0 +1,44 @@ +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let min = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!min) + min = version + } else { + if (prev) { + set.push([min, prev]) + } + prev = null + min = null + } + } + if (min) + set.push([min, null]) + + const ranges = [] + for (const [min, max] of set) { + if (min === max) + ranges.push(min) + else if (!max && min === v[0]) + ranges.push('*') + else if (!max) + ranges.push(`>=${min}`) + else if (min === v[0]) + ranges.push(`<=${max}`) + else + ranges.push(`${min} - ${max}`) + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} diff --git a/node_modules/update-notifier/node_modules/semver/ranges/subset.js b/node_modules/update-notifier/node_modules/semver/ranges/subset.js new file mode 100644 index 0000000..532fd13 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/subset.js @@ -0,0 +1,222 @@ +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) + return true + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) + continue OUTER + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) + return false + } + return true +} + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) + return true + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) + return true + else if (options.includePrerelease) + sub = [ new Comparator('>=0.0.0-0') ] + else + sub = [ new Comparator('>=0.0.0') ] + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) + return true + else + dom = [ new Comparator('>=0.0.0') ] + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') + gt = higherGT(gt, c, options) + else if (c.operator === '<' || c.operator === '<=') + lt = lowerLT(lt, c, options) + else + eqSet.add(c.semver) + } + + if (eqSet.size > 1) + return null + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) + return null + else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) + return null + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) + return null + + if (lt && !satisfies(eq, String(lt), options)) + return null + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) + return false + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) + return false + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) + return false + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) + return false + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) + return false + } + if (!c.operator && (lt || gt) && gtltComp !== 0) + return false + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) + return false + + if (lt && hasDomGT && !gt && gtltComp !== 0) + return false + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) + return false + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) + return b + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/update-notifier/node_modules/semver/ranges/to-comparators.js b/node_modules/update-notifier/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 0000000..6c8bc7e --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,8 @@ +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/update-notifier/node_modules/semver/ranges/valid.js b/node_modules/update-notifier/node_modules/semver/ranges/valid.js new file mode 100644 index 0000000..365f356 --- /dev/null +++ b/node_modules/update-notifier/node_modules/semver/ranges/valid.js @@ -0,0 +1,11 @@ +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/update-notifier/package.json b/node_modules/update-notifier/package.json new file mode 100644 index 0000000..d06524f --- /dev/null +++ b/node_modules/update-notifier/package.json @@ -0,0 +1,97 @@ +{ + "_args": [ + [ + "update-notifier@5.1.0", + "/home/other/discord_bot" + ] + ], + "_from": "update-notifier@5.1.0", + "_id": "update-notifier@5.1.0", + "_inBundle": false, + "_integrity": "sha512-ItnICHbeMh9GqUy31hFPrD1kcuZ3rpxDZbf4KUDavXwS0bW5m7SLbDQpGX3UYr072cbrF5hFUs3r5tUsPwjfHw==", + "_location": "/update-notifier", + "_phantomChildren": { + "lru-cache": "6.0.0" + }, + "_requested": { + "type": "version", + "registry": true, + "raw": "update-notifier@5.1.0", + "name": "update-notifier", + "escapedName": "update-notifier", + "rawSpec": "5.1.0", + "saveSpec": null, + "fetchSpec": "5.1.0" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-5.1.0.tgz", + "_spec": "5.1.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/yeoman/update-notifier/issues" + }, + "dependencies": { + "boxen": "^5.0.0", + "chalk": "^4.1.0", + "configstore": "^5.0.1", + "has-yarn": "^2.1.0", + "import-lazy": "^2.1.0", + "is-ci": "^2.0.0", + "is-installed-globally": "^0.4.0", + "is-npm": "^5.0.0", + "is-yarn-global": "^0.3.0", + "latest-version": "^5.1.0", + "pupa": "^2.1.1", + "semver": "^7.3.4", + "semver-diff": "^3.1.1", + "xdg-basedir": "^4.0.0" + }, + "description": "Update notifications for your CLI app", + "devDependencies": { + "ava": "^2.4.0", + "clear-module": "^4.1.1", + "fixture-stdout": "^0.2.1", + "mock-require": "^3.0.3", + "strip-ansi": "^6.0.0", + "xo": "^0.37.1" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "check.js" + ], + "funding": "https://github.com/yeoman/update-notifier?sponsor=1", + "homepage": "https://github.com/yeoman/update-notifier#readme", + "keywords": [ + "npm", + "update", + "updater", + "notify", + "notifier", + "check", + "checker", + "cli", + "module", + "package", + "version" + ], + "license": "BSD-2-Clause", + "name": "update-notifier", + "repository": { + "type": "git", + "url": "git+https://github.com/yeoman/update-notifier.git" + }, + "scripts": { + "test": "xo && ava --timeout=20s --serial" + }, + "version": "5.1.0" +} diff --git a/node_modules/update-notifier/readme.md b/node_modules/update-notifier/readme.md new file mode 100644 index 0000000..140c987 --- /dev/null +++ b/node_modules/update-notifier/readme.md @@ -0,0 +1,223 @@ +# update-notifier + +> Update notifications for your CLI app + +![](screenshot.png) + +Inform users of your package of updates in a non-intrusive way. + +#### Contents + +- [Install](#install) +- [Usage](#usage) +- [How](#how) +- [API](#api) +- [About](#about) +- [Users](#users) + +## Install + +``` +$ npm install update-notifier +``` + +## Usage + +### Simple + +```js +const updateNotifier = require('update-notifier'); +const pkg = require('./package.json'); + +updateNotifier({pkg}).notify(); +``` + +### Comprehensive + +```js +const updateNotifier = require('update-notifier'); +const pkg = require('./package.json'); + +// Checks for available update and returns an instance +const notifier = updateNotifier({pkg}); + +// Notify using the built-in convenience method +notifier.notify(); + +// `notifier.update` contains some useful info about the update +console.log(notifier.update); +/* +{ + latest: '1.0.1', + current: '1.0.0', + type: 'patch', // Possible values: latest, major, minor, patch, prerelease, build + name: 'pageres' +} +*/ +``` + +### Options and custom message + +```js +const notifier = updateNotifier({ + pkg, + updateCheckInterval: 1000 * 60 * 60 * 24 * 7 // 1 week +}); + +if (notifier.update) { + console.log(`Update available: ${notifier.update.latest}`); +} +``` + +## How + +Whenever you initiate the update notifier and it's not within the interval threshold, it will asynchronously check with npm in the background for available updates, then persist the result. The next time the notifier is initiated, the result will be loaded into the `.update` property. This prevents any impact on your package startup performance. +The update check is done in a unref'ed [child process](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). This means that if you call `process.exit`, the check will still be performed in its own process. + +The first time the user runs your app, it will check for an update, and even if an update is available, it will wait the specified `updateCheckInterval` before notifying the user. This is done to not be annoying to the user, but might surprise you as an implementer if you're testing whether it works. Check out [`example.js`](example.js) to quickly test out `update-notifier` and see how you can test that it works in your app. + +## API + +### notifier = updateNotifier(options) + +Checks if there is an available update. Accepts options defined below. Returns an instance with an `.update` property if there is an available update, otherwise `undefined`. + +### options + +Type: `object` + +#### pkg + +Type: `object` + +##### name + +*Required*\ +Type: `string` + +##### version + +*Required*\ +Type: `string` + +#### updateCheckInterval + +Type: `number`\ +Default: `1000 * 60 * 60 * 24` *(1 day)* + +How often to check for updates. + +#### shouldNotifyInNpmScript + +Type: `boolean`\ +Default: `false` + +Allows notification to be shown when running as an npm script. + +#### distTag + +Type: `string`\ +Default: `'latest'` + +Which [dist-tag](https://docs.npmjs.com/adding-dist-tags-to-packages) to use to find the latest version. + +### notifier.fetchInfo() + +Check update information. + +Returns an `object` with: + +- `latest` _(String)_ - Latest version. +- `current` _(String)_ - Current version. +- `type` _(String)_ - Type of current update. Possible values: `latest`, `major`, `minor`, `patch`, `prerelease`, `build`. +- `name` _(String)_ - Package name. + +### notifier.notify(options?) + +Convenience method to display a notification message. *(See screenshot)* + +Only notifies if there is an update and the process is [TTY](https://nodejs.org/api/process.html#process_a_note_on_process_i_o). + +#### options + +Type: `object` + +##### defer + +Type: `boolean`\ +Default: `true` + +Defer showing the notification to after the process has exited. + +##### message + +Type: `string`\ +Default: [See above screenshot](https://github.com/yeoman/update-notifier#update-notifier-) + +Message that will be shown when an update is available. + +Available placeholders: + +- `{packageName}` - Package name. +- `{currentVersion}` - Current version. +- `{latestVersion}` - Latest version. +- `{updateCommand}` - Update command. + +```js +notifier.notify({message: 'Run `{updateCommand}` to update.'}); + +// Output: +// Run `npm install update-notifier-tester@1.0.0` to update. +``` + +##### isGlobal + +Type: `boolean`\ +Default: Auto-detect + +Include the `-g` argument in the default message's `npm i` recommendation. You may want to change this if your CLI package can be installed as a dependency of another project, and don't want to recommend a global installation. This option is ignored if you supply your own `message` (see above). + +##### boxenOptions + +Type: `object`\ +Default: `{padding: 1, margin: 1, align: 'center', borderColor: 'yellow', borderStyle: 'round'}` *(See screenshot)* + +Options object that will be passed to [`boxen`](https://github.com/sindresorhus/boxen). + +### User settings + +Users of your module have the ability to opt-out of the update notifier by changing the `optOut` property to `true` in `~/.config/configstore/update-notifier-[your-module-name].json`. The path is available in `notifier.config.path`. + +Users can also opt-out by [setting the environment variable](https://github.com/sindresorhus/guides/blob/main/set-environment-variables.md) `NO_UPDATE_NOTIFIER` with any value or by using the `--no-update-notifier` flag on a per run basis. + +The check is also skipped automatically: + - on CI + - in unit tests (when the `NODE_ENV` environment variable is `test`) + +## About + +The idea for this module came from the desire to apply the browser update strategy to CLI tools, where everyone is always on the latest version. We first tried automatic updating, which we discovered wasn't popular. This is the second iteration of that idea, but limited to just update notifications. + +## Users + +There are a bunch projects using it: + +- [npm](https://github.com/npm/npm) - Package manager for JavaScript +- [Yeoman](https://yeoman.io) - Modern workflows for modern webapps +- [AVA](https://avajs.dev) - Simple concurrent test runner +- [XO](https://github.com/xojs/xo) - JavaScript happiness style linter +- [Node GH](https://github.com/node-gh/gh) - GitHub command line tool + +[And 2700+ more…](https://www.npmjs.org/browse/depended/update-notifier) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/url-parse-lax/index.js b/node_modules/url-parse-lax/index.js new file mode 100644 index 0000000..5c62a58 --- /dev/null +++ b/node_modules/url-parse-lax/index.js @@ -0,0 +1,12 @@ +'use strict'; +const url = require('url'); +const prependHttp = require('prepend-http'); + +module.exports = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError(`Expected \`url\` to be of type \`string\`, got \`${typeof input}\` instead.`); + } + + const finalUrl = prependHttp(input, Object.assign({https: true}, options)); + return url.parse(finalUrl); +}; diff --git a/node_modules/url-parse-lax/license b/node_modules/url-parse-lax/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/url-parse-lax/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/url-parse-lax/package.json b/node_modules/url-parse-lax/package.json new file mode 100644 index 0000000..9c66d8e --- /dev/null +++ b/node_modules/url-parse-lax/package.json @@ -0,0 +1,77 @@ +{ + "_args": [ + [ + "url-parse-lax@3.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "url-parse-lax@3.0.0", + "_id": "url-parse-lax@3.0.0", + "_inBundle": false, + "_integrity": "sha1-FrXK/Afb42dsGxmZF3gj1lA6yww=", + "_location": "/url-parse-lax", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "url-parse-lax@3.0.0", + "name": "url-parse-lax", + "escapedName": "url-parse-lax", + "rawSpec": "3.0.0", + "saveSpec": null, + "fetchSpec": "3.0.0" + }, + "_requiredBy": [ + "/got" + ], + "_resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-3.0.0.tgz", + "_spec": "3.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/url-parse-lax/issues" + }, + "dependencies": { + "prepend-http": "^2.0.0" + }, + "description": "Lax url.parse() with support for protocol-less URLs & IPs", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/url-parse-lax#readme", + "keywords": [ + "url", + "uri", + "parse", + "parser", + "loose", + "lax", + "protocol", + "less", + "protocol-less", + "ip", + "ipv4", + "ipv6" + ], + "license": "MIT", + "name": "url-parse-lax", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/url-parse-lax.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "3.0.0" +} diff --git a/node_modules/url-parse-lax/readme.md b/node_modules/url-parse-lax/readme.md new file mode 100644 index 0000000..be0d437 --- /dev/null +++ b/node_modules/url-parse-lax/readme.md @@ -0,0 +1,127 @@ +# url-parse-lax [![Build Status](https://travis-ci.org/sindresorhus/url-parse-lax.svg?branch=master)](https://travis-ci.org/sindresorhus/url-parse-lax) + +> Lax [`url.parse()`](https://nodejs.org/docs/latest/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost) with support for protocol-less URLs & IPs + + +## Install + +``` +$ npm install url-parse-lax +``` + + +## Usage + +```js +const urlParseLax = require('url-parse-lax'); + +urlParseLax('sindresorhus.com'); +/* +{ + protocol: 'https:', + slashes: true, + auth: null, + host: 'sindresorhus.com', + port: null, + hostname: 'sindresorhus.com', + hash: null, + search: null, + query: null, + pathname: '/', + path: '/', + href: 'https://sindresorhus.com/' +} +*/ + +urlParseLax('[2001:db8::]:8000'); +/* +{ + protocol: null, + slashes: true, + auth: null, + host: '[2001:db8::]:8000', + port: '8000', + hostname: '2001:db8::', + hash: null, + search: null, + query: null, + pathname: '/', + path: '/', + href: 'http://[2001:db8::]:8000/' +} +*/ +``` + +And with the built-in `url.parse()`: + +```js +const url = require('url'); + +url.parse('sindresorhus.com'); +/* +{ + protocol: null, + slashes: null, + auth: null, + host: null, + port: null, + hostname: null, + hash: null, + search: null, + query: null, + pathname: 'sindresorhus', + path: 'sindresorhus', + href: 'sindresorhus' +} +*/ + +url.parse('[2001:db8::]:8000'); +/* +{ + protocol: null, + slashes: null, + auth: null, + host: null, + port: null, + hostname: null, + hash: null, + search: null, + query: null, + pathname: '[2001:db8::]:8000', + path: '[2001:db8::]:8000', + href: '[2001:db8::]:8000' +} +*/ +``` + + +## API + +### urlParseLax(url, [options]) + +#### url + +Type: `string` + +URL to parse. + +#### options + +Type: `Object` + +##### https + +Type: `boolean`
+Default: `true` + +Prepend `https://` instead of `http://` to protocol-less URLs. + + +## Related + +- [url-format-lax](https://github.com/sindresorhus/url-format-lax) - Lax `url.format()` that formats a hostname and port into IPv6-compatible socket form of `hostname:port` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/util-deprecate/History.md b/node_modules/util-deprecate/History.md new file mode 100644 index 0000000..acc8675 --- /dev/null +++ b/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/node_modules/util-deprecate/LICENSE b/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000..6a60e8c --- /dev/null +++ b/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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/util-deprecate/README.md b/node_modules/util-deprecate/README.md new file mode 100644 index 0000000..75622fa --- /dev/null +++ b/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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/util-deprecate/browser.js b/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000..549ae2f --- /dev/null +++ b/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/node_modules/util-deprecate/node.js b/node_modules/util-deprecate/node.js new file mode 100644 index 0000000..5e6fcff --- /dev/null +++ b/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/node_modules/util-deprecate/package.json b/node_modules/util-deprecate/package.json new file mode 100644 index 0000000..2e79f89 --- /dev/null +++ b/node_modules/util-deprecate/package.json @@ -0,0 +1,27 @@ +{ + "name": "util-deprecate", + "version": "1.0.2", + "description": "The Node.js `util.deprecate()` function with browser support", + "main": "node.js", + "browser": "browser.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "author": "Nathan Rajlich (http://n8.io/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "homepage": "https://github.com/TooTallNate/util-deprecate" +} diff --git a/node_modules/webidl-conversions/LICENSE.md b/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 0000000..d4a994f --- /dev/null +++ b/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/webidl-conversions/README.md b/node_modules/webidl-conversions/README.md new file mode 100644 index 0000000..3657890 --- /dev/null +++ b/node_modules/webidl-conversions/README.md @@ -0,0 +1,53 @@ +# WebIDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a WebIDL operation declared as + +```webidl +void doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +## Status + +All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! + +I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. + +We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't Use This + +Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. diff --git a/node_modules/webidl-conversions/lib/index.js b/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 0000000..c5153a3 --- /dev/null +++ b/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,189 @@ +"use strict"; + +var conversions = {}; +module.exports = conversions; + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); + } +} + +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + + return function(V, opts) { + if (!opts) opts = {}; + + let x = +V; + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + + return x; + } + + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); + + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; + } + } + + return x; + } +} + +conversions["void"] = function () { + return undefined; +}; + +conversions["boolean"] = function (val) { + return !!val; +}; + +conversions["byte"] = createNumberConversion(8, { unsigned: false }); +conversions["octet"] = createNumberConversion(8, { unsigned: true }); + +conversions["short"] = createNumberConversion(16, { unsigned: false }); +conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + +conversions["long"] = createNumberConversion(32, { unsigned: false }); +conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + +conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + +conversions["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); + } + + return x; +}; + +conversions["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); + } + + return x; +}; + +// not quite valid, but good enough for JS +conversions["float"] = conversions["double"]; +conversions["unrestricted float"] = conversions["unrestricted double"]; + +conversions["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + return String(V); +}; + +conversions["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); + } + } + + return x; +}; + +conversions["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + } + + return U.join(''); +}; + +conversions["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; diff --git a/node_modules/webidl-conversions/package.json b/node_modules/webidl-conversions/package.json new file mode 100644 index 0000000..18d5a49 --- /dev/null +++ b/node_modules/webidl-conversions/package.json @@ -0,0 +1,59 @@ +{ + "_from": "webidl-conversions@^3.0.0", + "_id": "webidl-conversions@3.0.1", + "_inBundle": false, + "_integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "_location": "/webidl-conversions", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "webidl-conversions@^3.0.0", + "name": "webidl-conversions", + "escapedName": "webidl-conversions", + "rawSpec": "^3.0.0", + "saveSpec": null, + "fetchSpec": "^3.0.0" + }, + "_requiredBy": [ + "/whatwg-url" + ], + "_resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "_shasum": "24534275e2a7bc6be7bc86611cc16ae0a5654871", + "_spec": "webidl-conversions@^3.0.0", + "_where": "/home/other/discord_bot/node_modules/whatwg-url", + "author": { + "name": "Domenic Denicola", + "email": "d@domenic.me", + "url": "https://domenic.me/" + }, + "bugs": { + "url": "https://github.com/jsdom/webidl-conversions/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "devDependencies": { + "mocha": "^1.21.4" + }, + "files": [ + "lib/" + ], + "homepage": "https://github.com/jsdom/webidl-conversions#readme", + "keywords": [ + "webidl", + "web", + "types" + ], + "license": "BSD-2-Clause", + "main": "lib/index.js", + "name": "webidl-conversions", + "repository": { + "type": "git", + "url": "git+https://github.com/jsdom/webidl-conversions.git" + }, + "scripts": { + "test": "mocha test/*.js" + }, + "version": "3.0.1" +} diff --git a/node_modules/websocket-driver/CHANGELOG.md b/node_modules/websocket-driver/CHANGELOG.md new file mode 100644 index 0000000..cb3945f --- /dev/null +++ b/node_modules/websocket-driver/CHANGELOG.md @@ -0,0 +1,142 @@ +### 0.7.4 / 2020-05-22 + +- Avoid crashing if `process.version` does not contain any digits +- Emit `ping` and `pong` events from the `Server` driver +- Require http-parser-js >=0.5.1 which fixes the bug we addressed in 0.7.3 + +### 0.7.3 / 2019-06-13 + +- Cap version of http-parser-js below 0.4.11, which introduced a bug that + prevents us from handling messages that are part of the same input buffer as + the handshake response if chunked encoding is specified + +### 0.7.2 / 2019-06-13 + +(This version was pulled due to an error when publishing) + +### 0.7.1 / 2019-06-10 + +- Catch any exceptions produced while generating a handshake response and send a + `400 Bad Request` response to the client +- Pick the RFC-6455 protocol version if the request contains any of the headers + used by that version +- Use the `Buffer.alloc()` and `Buffer.from()` functions instead of the unsafe + `Buffer()` constructor +- Handle errors encountered while handling malformed draft-76 requests +- Change license from MIT to Apache 2.0 + +### 0.7.0 / 2017-09-11 + +- Add `ping` and `pong` to the set of events users can listen to +- Replace the bindings to Node's HTTP parser with `http-parser-js` + +### 0.6.5 / 2016-05-20 + +- Don't mutate buffers passed in by the application when masking + +### 0.6.4 / 2016-01-07 + +- If a number is given as input for a frame payload, send it as a string + +### 0.6.3 / 2015-11-06 + +- Reject draft-76 handshakes if their Sec-WebSocket-Key headers are invalid +- Throw a more helpful error if a client is created with an invalid URL + +### 0.6.2 / 2015-07-18 + +- When the peer sends a close frame with no error code, emit 1000 + +### 0.6.1 / 2015-07-13 + +- Use the `buffer.{read,write}UInt{16,32}BE` methods for reading/writing numbers + to buffers rather than including duplicate logic for this + +### 0.6.0 / 2015-07-08 + +- Allow the parser to recover cleanly if event listeners raise an error +- Add a `pong` method for sending unsolicited pong frames + +### 0.5.4 / 2015-03-29 + +- Don't emit extra close frames if we receive a close frame after we already + sent one +- Fail the connection when the driver receives an invalid + `Sec-WebSocket-Extensions` header + +### 0.5.3 / 2015-02-22 + +- Don't treat incoming data as WebSocket frames if a client driver is closed + before receiving the server handshake + +### 0.5.2 / 2015-02-19 + +- Fix compatibility with the HTTP parser on io.js +- Use `websocket-extensions` to make sure messages and close frames are kept in + order +- Don't emit multiple `error` events + +### 0.5.1 / 2014-12-18 + +- Don't allow drivers to be created with unrecognized options + +### 0.5.0 / 2014-12-13 + +- Support protocol extensions via the websocket-extensions module + +### 0.4.0 / 2014-11-08 + +- Support connection via HTTP proxies using `CONNECT` + +### 0.3.6 / 2014-10-04 + +- It is now possible to call `close()` before `start()` and close the driver + +### 0.3.5 / 2014-07-06 + +- Don't hold references to frame buffers after a message has been emitted +- Make sure that `protocol` and `version` are exposed properly by the TCP driver + +### 0.3.4 / 2014-05-08 + +- Don't hold memory-leaking references to I/O buffers after they have been + parsed + +### 0.3.3 / 2014-04-24 + +- Correct the draft-76 status line reason phrase + +### 0.3.2 / 2013-12-29 + +- Expand `maxLength` to cover sequences of continuation frames and + `draft-{75,76}` +- Decrease default maximum frame buffer size to 64MB +- Stop parsing when the protocol enters a failure mode, to save CPU cycles + +### 0.3.1 / 2013-12-03 + +- Add a `maxLength` option to limit allowed frame size +- Don't pre-allocate a message buffer until the whole frame has arrived +- Fix compatibility with Node v0.11 `HTTPParser` + +### 0.3.0 / 2013-09-09 + +- Support client URLs with Basic Auth credentials + +### 0.2.2 / 2013-07-05 + +- No functional changes, just updates to package.json + +### 0.2.1 / 2013-05-17 + +- Export the isSecureRequest() method since faye-websocket relies on it +- Queue sent messages in the client's initial state + +### 0.2.0 / 2013-05-12 + +- Add API for setting and reading headers +- Add Driver.server() method for getting a driver for TCP servers + +### 0.1.0 / 2013-05-04 + +- First stable release diff --git a/node_modules/websocket-driver/LICENSE.md b/node_modules/websocket-driver/LICENSE.md new file mode 100644 index 0000000..9475f06 --- /dev/null +++ b/node_modules/websocket-driver/LICENSE.md @@ -0,0 +1,12 @@ +Copyright 2010-2020 James Coglan + +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/websocket-driver/README.md b/node_modules/websocket-driver/README.md new file mode 100644 index 0000000..95c33c4 --- /dev/null +++ b/node_modules/websocket-driver/README.md @@ -0,0 +1,370 @@ +# websocket-driver [![Build Status](https://travis-ci.org/faye/websocket-driver-node.svg)](https://travis-ci.org/faye/websocket-driver-node) + +This module provides a complete implementation of the WebSocket protocols that +can be hooked up to any I/O stream. It aims to simplify things by decoupling the +protocol details from the I/O layer, such that users only need to implement code +to stream data in and out of it without needing to know anything about how the +protocol actually works. Think of it as a complete WebSocket system with +pluggable I/O. + +Due to this design, you get a lot of things for free. In particular, if you hook +this module up to some I/O object, it will do all of this for you: + +- Select the correct server-side driver to talk to the client +- Generate and send both server- and client-side handshakes +- Recognize when the handshake phase completes and the WS protocol begins +- Negotiate subprotocol selection based on `Sec-WebSocket-Protocol` +- Negotiate and use extensions via the + [websocket-extensions](https://github.com/faye/websocket-extensions-node) + module +- Buffer sent messages until the handshake process is finished +- Deal with proxies that defer delivery of the draft-76 handshake body +- Notify you when the socket is open and closed and when messages arrive +- Recombine fragmented messages +- Dispatch text, binary, ping, pong and close frames +- Manage the socket-closing handshake process +- Automatically reply to ping frames with a matching pong +- Apply masking to messages sent by the client + +This library was originally extracted from the [Faye](http://faye.jcoglan.com) +project but now aims to provide simple WebSocket support for any Node-based +project. + + +## Installation + +``` +$ npm install websocket-driver +``` + + +## Usage + +This module provides protocol drivers that have the same interface on the server +and on the client. A WebSocket driver is an object with two duplex streams +attached; one for incoming/outgoing messages and one for managing the wire +protocol over an I/O stream. The full API is described below. + + +### Server-side with HTTP + +A Node webserver emits a special event for 'upgrade' requests, and this is where +you should handle WebSockets. You first check whether the request is a +WebSocket, and if so you can create a driver and attach the request's I/O stream +to it. + +```js +var http = require('http'), + websocket = require('websocket-driver'); + +var server = http.createServer(); + +server.on('upgrade', function(request, socket, body) { + if (!websocket.isWebSocket(request)) return; + + var driver = websocket.http(request); + + driver.io.write(body); + socket.pipe(driver.io).pipe(socket); + + driver.messages.on('data', function(message) { + console.log('Got a message', message); + }); + + driver.start(); +}); +``` + +Note the line `driver.io.write(body)` - you must pass the `body` buffer to the +socket driver in order to make certain versions of the protocol work. + + +### Server-side with TCP + +You can also handle WebSocket connections in a bare TCP server, if you're not +using an HTTP server and don't want to implement HTTP parsing yourself. + +The driver will emit a `connect` event when a request is received, and at this +point you can detect whether it's a WebSocket and handle it as such. Here's an +example using the Node `net` module: + +```js +var net = require('net'), + websocket = require('websocket-driver'); + +var server = net.createServer(function(connection) { + var driver = websocket.server(); + + driver.on('connect', function() { + if (websocket.isWebSocket(driver)) { + driver.start(); + } else { + // handle other HTTP requests + } + }); + + driver.on('close', function() { connection.end() }); + connection.on('error', function() {}); + + connection.pipe(driver.io).pipe(connection); + + driver.messages.pipe(driver.messages); +}); + +server.listen(4180); +``` + +In the `connect` event, the driver gains several properties to describe the +request, similar to a Node request object, such as `method`, `url` and +`headers`. However you should remember it's not a real request object; you +cannot write data to it, it only tells you what request data we parsed from the +input. + +If the request has a body, it will be in the `driver.body` buffer, but only as +much of the body as has been piped into the driver when the `connect` event +fires. + + +### Client-side + +Similarly, to implement a WebSocket client you just need to make a driver by +passing in a URL. After this you use the driver API as described below to +process incoming data and send outgoing data. + + +```js +var net = require('net'), + websocket = require('websocket-driver'); + +var driver = websocket.client('ws://www.example.com/socket'), + tcp = net.connect(80, 'www.example.com'); + +tcp.pipe(driver.io).pipe(tcp); + +tcp.on('connect', function() { + driver.start(); +}); + +driver.messages.on('data', function(message) { + console.log('Got a message', message); +}); +``` + +Client drivers have two additional properties for reading the HTTP data that was +sent back by the server: + +- `driver.statusCode` - the integer value of the HTTP status code +- `driver.headers` - an object containing the response headers + + +### HTTP Proxies + +The client driver supports connections via HTTP proxies using the `CONNECT` +method. Instead of sending the WebSocket handshake immediately, it will send a +`CONNECT` request, wait for a `200` response, and then proceed as normal. + +To use this feature, call `driver.proxy(url)` where `url` is the origin of the +proxy, including a username and password if required. This produces a duplex +stream that you should pipe in and out of your TCP connection to the proxy +server. When the proxy emits `connect`, you can then pipe `driver.io` to your +TCP stream and call `driver.start()`. + +```js +var net = require('net'), + websocket = require('websocket-driver'); + +var driver = websocket.client('ws://www.example.com/socket'), + proxy = driver.proxy('http://username:password@proxy.example.com'), + tcp = net.connect(80, 'proxy.example.com'); + +tcp.pipe(proxy).pipe(tcp, { end: false }); + +tcp.on('connect', function() { + proxy.start(); +}); + +proxy.on('connect', function() { + driver.io.pipe(tcp).pipe(driver.io); + driver.start(); +}); + +driver.messages.on('data', function(message) { + console.log('Got a message', message); +}); +``` + +The proxy's `connect` event is also where you should perform a TLS handshake on +your TCP stream, if you are connecting to a `wss:` endpoint. + +In the event that proxy connection fails, `proxy` will emit an `error`. You can +inspect the proxy's response via `proxy.statusCode` and `proxy.headers`. + +```js +proxy.on('error', function(error) { + console.error(error.message); + console.log(proxy.statusCode); + console.log(proxy.headers); +}); +``` + +Before calling `proxy.start()` you can set custom headers using +`proxy.setHeader()`: + +```js +proxy.setHeader('User-Agent', 'node'); +proxy.start(); +``` + + +### Driver API + +Drivers are created using one of the following methods: + +```js +driver = websocket.http(request, options) +driver = websocket.server(options) +driver = websocket.client(url, options) +``` + +The `http` method returns a driver chosen using the headers from a Node HTTP +request object. The `server` method returns a driver that will parse an HTTP +request and then decide which driver to use for it using the `http` method. The +`client` method always returns a driver for the RFC version of the protocol with +masking enabled on outgoing frames. + +The `options` argument is optional, and is an object. It may contain the +following fields: + +- `maxLength` - the maximum allowed size of incoming message frames, in bytes. + The default value is `2^26 - 1`, or 1 byte short of 64 MiB. +- `protocols` - an array of strings representing acceptable subprotocols for use + over the socket. The driver will negotiate one of these to use via the + `Sec-WebSocket-Protocol` header if supported by the other peer. + +A driver has two duplex streams attached to it: + +- **`driver.io`** - this stream should be attached to an I/O socket like a TCP + stream. Pipe incoming TCP chunks to this stream for them to be parsed, and + pipe this stream back into TCP to send outgoing frames. +- **`driver.messages`** - this stream emits messages received over the + WebSocket. Writing to it sends messages to the other peer by emitting frames + via the `driver.io` stream. + +All drivers respond to the following API methods, but some of them are no-ops +depending on whether the client supports the behaviour. + +Note that most of these methods are commands: if they produce data that should +be sent over the socket, they will give this to you by emitting `data` events on +the `driver.io` stream. + +#### `driver.on('open', function(event) {})` + +Adds a callback to execute when the socket becomes open. + +#### `driver.on('message', function(event) {})` + +Adds a callback to execute when a message is received. `event` will have a +`data` attribute containing either a string in the case of a text message or a +`Buffer` in the case of a binary message. + +You can also listen for messages using the `driver.messages.on('data')` event, +which emits strings for text messages and buffers for binary messages. + +#### `driver.on('error', function(event) {})` + +Adds a callback to execute when a protocol error occurs due to the other peer +sending an invalid byte sequence. `event` will have a `message` attribute +describing the error. + +#### `driver.on('close', function(event) {})` + +Adds a callback to execute when the socket becomes closed. The `event` object +has `code` and `reason` attributes. + +#### `driver.on('ping', function(event) {})` + +Adds a callback block to execute when a ping is received. You do not need to +handle this by sending a pong frame yourself; the driver handles this for you. + +#### `driver.on('pong', function(event) {})` + +Adds a callback block to execute when a pong is received. If this was in +response to a ping you sent, you can also handle this event via the +`driver.ping(message, function() { ... })` callback. + +#### `driver.addExtension(extension)` + +Registers a protocol extension whose operation will be negotiated via the +`Sec-WebSocket-Extensions` header. `extension` is any extension compatible with +the [websocket-extensions](https://github.com/faye/websocket-extensions-node) +framework. + +#### `driver.setHeader(name, value)` + +Sets a custom header to be sent as part of the handshake response, either from +the server or from the client. Must be called before `start()`, since this is +when the headers are serialized and sent. + +#### `driver.start()` + +Initiates the protocol by sending the handshake - either the response for a +server-side driver or the request for a client-side one. This should be the +first method you invoke. Returns `true` if and only if a handshake was sent. + +#### `driver.parse(string)` + +Takes a string and parses it, potentially resulting in message events being +emitted (see `on('message')` above) or in data being sent to `driver.io`. You +should send all data you receive via I/O to this method by piping a stream into +`driver.io`. + +#### `driver.text(string)` + +Sends a text message over the socket. If the socket handshake is not yet +complete, the message will be queued until it is. Returns `true` if the message +was sent or queued, and `false` if the socket can no longer send messages. + +This method is equivalent to `driver.messages.write(string)`. + +#### `driver.binary(buffer)` + +Takes a `Buffer` and sends it as a binary message. Will queue and return `true` +or `false` the same way as the `text` method. It will also return `false` if the +driver does not support binary messages. + +This method is equivalent to `driver.messages.write(buffer)`. + +#### `driver.ping(string = '', function() {})` + +Sends a ping frame over the socket, queueing it if necessary. `string` and the +callback are both optional. If a callback is given, it will be invoked when the +socket receives a pong frame whose content matches `string`. Returns `false` if +frames can no longer be sent, or if the driver does not support ping/pong. + +#### `driver.pong(string = '')` + +Sends a pong frame over the socket, queueing it if necessary. `string` is +optional. Returns `false` if frames can no longer be sent, or if the driver does +not support ping/pong. + +You don't need to call this when a ping frame is received; pings are replied to +automatically by the driver. This method is for sending unsolicited pongs. + +#### `driver.close()` + +Initiates the closing handshake if the socket is still open. For drivers with no +closing handshake, this will result in the immediate execution of the +`on('close')` driver. For drivers with a closing handshake, this sends a closing +frame and `emit('close')` will execute when a response is received or a protocol +error occurs. + +#### `driver.version` + +Returns the WebSocket version in use as a string. Will either be `hixie-75`, +`hixie-76` or `hybi-$version`. + +#### `driver.protocol` + +Returns a string containing the selected subprotocol, if any was agreed upon +using the `Sec-WebSocket-Protocol` mechanism. This value becomes available after +`emit('open')` has fired. diff --git a/node_modules/websocket-driver/lib/websocket/driver.js b/node_modules/websocket-driver/lib/websocket/driver.js new file mode 100644 index 0000000..3d701cc --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver.js @@ -0,0 +1,43 @@ +'use strict'; + +// Protocol references: +// +// * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 +// * http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 +// * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 + +var Base = require('./driver/base'), + Client = require('./driver/client'), + Server = require('./driver/server'); + +var Driver = { + client: function(url, options) { + options = options || {}; + if (options.masking === undefined) options.masking = true; + return new Client(url, options); + }, + + server: function(options) { + options = options || {}; + if (options.requireMasking === undefined) options.requireMasking = true; + return new Server(options); + }, + + http: function() { + return Server.http.apply(Server, arguments); + }, + + isSecureRequest: function(request) { + return Server.isSecureRequest(request); + }, + + isWebSocket: function(request) { + return Base.isWebSocket(request); + }, + + validateOptions: function(options, validKeys) { + Base.validateOptions(options, validKeys); + } +}; + +module.exports = Driver; diff --git a/node_modules/websocket-driver/lib/websocket/driver/base.js b/node_modules/websocket-driver/lib/websocket/driver/base.js new file mode 100644 index 0000000..f05af5f --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/base.js @@ -0,0 +1,193 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + Emitter = require('events').EventEmitter, + util = require('util'), + streams = require('../streams'), + Headers = require('./headers'), + Reader = require('./stream_reader'); + +var Base = function(request, url, options) { + Emitter.call(this); + Base.validateOptions(options || {}, ['maxLength', 'masking', 'requireMasking', 'protocols']); + + this._request = request; + this._reader = new Reader(); + this._options = options || {}; + this._maxLength = this._options.maxLength || this.MAX_LENGTH; + this._headers = new Headers(); + this.__queue = []; + this.readyState = 0; + this.url = url; + + this.io = new streams.IO(this); + this.messages = new streams.Messages(this); + this._bindEventListeners(); +}; +util.inherits(Base, Emitter); + +Base.isWebSocket = function(request) { + var connection = request.headers.connection || '', + upgrade = request.headers.upgrade || ''; + + return request.method === 'GET' && + connection.toLowerCase().split(/ *, */).indexOf('upgrade') >= 0 && + upgrade.toLowerCase() === 'websocket'; +}; + +Base.validateOptions = function(options, validKeys) { + for (var key in options) { + if (validKeys.indexOf(key) < 0) + throw new Error('Unrecognized option: ' + key); + } +}; + +var instance = { + // This is 64MB, small enough for an average VPS to handle without + // crashing from process out of memory + MAX_LENGTH: 0x3ffffff, + + STATES: ['connecting', 'open', 'closing', 'closed'], + + _bindEventListeners: function() { + var self = this; + + // Protocol errors are informational and do not have to be handled + this.messages.on('error', function() {}); + + this.on('message', function(event) { + var messages = self.messages; + if (messages.readable) messages.emit('data', event.data); + }); + + this.on('error', function(error) { + var messages = self.messages; + if (messages.readable) messages.emit('error', error); + }); + + this.on('close', function() { + var messages = self.messages; + if (!messages.readable) return; + messages.readable = messages.writable = false; + messages.emit('end'); + }); + }, + + getState: function() { + return this.STATES[this.readyState] || null; + }, + + addExtension: function(extension) { + return false; + }, + + setHeader: function(name, value) { + if (this.readyState > 0) return false; + this._headers.set(name, value); + return true; + }, + + start: function() { + if (this.readyState !== 0) return false; + + if (!Base.isWebSocket(this._request)) + return this._failHandshake(new Error('Not a WebSocket request')); + + var response; + + try { + response = this._handshakeResponse(); + } catch (error) { + return this._failHandshake(error); + } + + this._write(response); + if (this._stage !== -1) this._open(); + return true; + }, + + _failHandshake: function(error) { + var headers = new Headers(); + headers.set('Content-Type', 'text/plain'); + headers.set('Content-Length', Buffer.byteLength(error.message, 'utf8')); + + headers = ['HTTP/1.1 400 Bad Request', headers.toString(), error.message]; + this._write(Buffer.from(headers.join('\r\n'), 'utf8')); + this._fail('protocol_error', error.message); + + return false; + }, + + text: function(message) { + return this.frame(message); + }, + + binary: function(message) { + return false; + }, + + ping: function() { + return false; + }, + + pong: function() { + return false; + }, + + close: function(reason, code) { + if (this.readyState !== 1) return false; + this.readyState = 3; + this.emit('close', new Base.CloseEvent(null, null)); + return true; + }, + + _open: function() { + this.readyState = 1; + this.__queue.forEach(function(args) { this.frame.apply(this, args) }, this); + this.__queue = []; + this.emit('open', new Base.OpenEvent()); + }, + + _queue: function(message) { + this.__queue.push(message); + return true; + }, + + _write: function(chunk) { + var io = this.io; + if (io.readable) io.emit('data', chunk); + }, + + _fail: function(type, message) { + this.readyState = 2; + this.emit('error', new Error(message)); + this.close(); + } +}; + +for (var key in instance) + Base.prototype[key] = instance[key]; + + +Base.ConnectEvent = function() {}; + +Base.OpenEvent = function() {}; + +Base.CloseEvent = function(code, reason) { + this.code = code; + this.reason = reason; +}; + +Base.MessageEvent = function(data) { + this.data = data; +}; + +Base.PingEvent = function(data) { + this.data = data; +}; + +Base.PongEvent = function(data) { + this.data = data; +}; + +module.exports = Base; diff --git a/node_modules/websocket-driver/lib/websocket/driver/client.js b/node_modules/websocket-driver/lib/websocket/driver/client.js new file mode 100644 index 0000000..f24d645 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/client.js @@ -0,0 +1,142 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + crypto = require('crypto'), + url = require('url'), + util = require('util'), + HttpParser = require('../http_parser'), + Base = require('./base'), + Hybi = require('./hybi'), + Proxy = require('./proxy'); + +var Client = function(_url, options) { + this.version = 'hybi-' + Hybi.VERSION; + Hybi.call(this, null, _url, options); + + this.readyState = -1; + this._key = Client.generateKey(); + this._accept = Hybi.generateAccept(this._key); + this._http = new HttpParser('response'); + + var uri = url.parse(this.url), + auth = uri.auth && Buffer.from(uri.auth, 'utf8').toString('base64'); + + if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0) + throw new Error(this.url + ' is not a valid WebSocket URL'); + + this._pathname = (uri.pathname || '/') + (uri.search || ''); + + this._headers.set('Host', uri.host); + this._headers.set('Upgrade', 'websocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Key', this._key); + this._headers.set('Sec-WebSocket-Version', Hybi.VERSION); + + if (this._protocols.length > 0) + this._headers.set('Sec-WebSocket-Protocol', this._protocols.join(', ')); + + if (auth) + this._headers.set('Authorization', 'Basic ' + auth); +}; +util.inherits(Client, Hybi); + +Client.generateKey = function() { + return crypto.randomBytes(16).toString('base64'); +}; + +var instance = { + VALID_PROTOCOLS: ['ws:', 'wss:'], + + proxy: function(origin, options) { + return new Proxy(this, origin, options); + }, + + start: function() { + if (this.readyState !== -1) return false; + this._write(this._handshakeRequest()); + this.readyState = 0; + return true; + }, + + parse: function(chunk) { + if (this.readyState === 3) return; + if (this.readyState > 0) return Hybi.prototype.parse.call(this, chunk); + + this._http.parse(chunk); + if (!this._http.isComplete()) return; + + this._validateHandshake(); + if (this.readyState === 3) return; + + this._open(); + this.parse(this._http.body); + }, + + _handshakeRequest: function() { + var extensions = this._extensions.generateOffer(); + if (extensions) + this._headers.set('Sec-WebSocket-Extensions', extensions); + + var start = 'GET ' + this._pathname + ' HTTP/1.1', + headers = [start, this._headers.toString(), '']; + + return Buffer.from(headers.join('\r\n'), 'utf8'); + }, + + _failHandshake: function(message) { + message = 'Error during WebSocket handshake: ' + message; + this.readyState = 3; + this.emit('error', new Error(message)); + this.emit('close', new Base.CloseEvent(this.ERRORS.protocol_error, message)); + }, + + _validateHandshake: function() { + this.statusCode = this._http.statusCode; + this.headers = this._http.headers; + + if (this._http.error) + return this._failHandshake(this._http.error.message); + + if (this._http.statusCode !== 101) + return this._failHandshake('Unexpected response code: ' + this._http.statusCode); + + var headers = this._http.headers, + upgrade = headers['upgrade'] || '', + connection = headers['connection'] || '', + accept = headers['sec-websocket-accept'] || '', + protocol = headers['sec-websocket-protocol'] || ''; + + if (upgrade === '') + return this._failHandshake("'Upgrade' header is missing"); + if (upgrade.toLowerCase() !== 'websocket') + return this._failHandshake("'Upgrade' header value is not 'WebSocket'"); + + if (connection === '') + return this._failHandshake("'Connection' header is missing"); + if (connection.toLowerCase() !== 'upgrade') + return this._failHandshake("'Connection' header value is not 'Upgrade'"); + + if (accept !== this._accept) + return this._failHandshake('Sec-WebSocket-Accept mismatch'); + + this.protocol = null; + + if (protocol !== '') { + if (this._protocols.indexOf(protocol) < 0) + return this._failHandshake('Sec-WebSocket-Protocol mismatch'); + else + this.protocol = protocol; + } + + try { + this._extensions.activate(this.headers['sec-websocket-extensions']); + } catch (e) { + return this._failHandshake(e.message); + } + } +}; + +for (var key in instance) + Client.prototype[key] = instance[key]; + +module.exports = Client; diff --git a/node_modules/websocket-driver/lib/websocket/driver/draft75.js b/node_modules/websocket-driver/lib/websocket/driver/draft75.js new file mode 100644 index 0000000..583f985 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/draft75.js @@ -0,0 +1,123 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + Base = require('./base'), + util = require('util'); + +var Draft75 = function(request, url, options) { + Base.apply(this, arguments); + this._stage = 0; + this.version = 'hixie-75'; + + this._headers.set('Upgrade', 'WebSocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('WebSocket-Origin', this._request.headers.origin); + this._headers.set('WebSocket-Location', this.url); +}; +util.inherits(Draft75, Base); + +var instance = { + close: function() { + if (this.readyState === 3) return false; + this.readyState = 3; + this.emit('close', new Base.CloseEvent(null, null)); + return true; + }, + + parse: function(chunk) { + if (this.readyState > 1) return; + + this._reader.put(chunk); + + this._reader.eachByte(function(octet) { + var message; + + switch (this._stage) { + case -1: + this._body.push(octet); + this._sendHandshakeBody(); + break; + + case 0: + this._parseLeadingByte(octet); + break; + + case 1: + this._length = (octet & 0x7F) + 128 * this._length; + + if (this._closing && this._length === 0) { + return this.close(); + } + else if ((octet & 0x80) !== 0x80) { + if (this._length === 0) { + this._stage = 0; + } + else { + this._skipped = 0; + this._stage = 2; + } + } + break; + + case 2: + if (octet === 0xFF) { + this._stage = 0; + message = Buffer.from(this._buffer).toString('utf8', 0, this._buffer.length); + this.emit('message', new Base.MessageEvent(message)); + } + else { + if (this._length) { + this._skipped += 1; + if (this._skipped === this._length) + this._stage = 0; + } else { + this._buffer.push(octet); + if (this._buffer.length > this._maxLength) return this.close(); + } + } + break; + } + }, this); + }, + + frame: function(buffer) { + if (this.readyState === 0) return this._queue([buffer]); + if (this.readyState > 1) return false; + + if (typeof buffer !== 'string') buffer = buffer.toString(); + + var length = Buffer.byteLength(buffer), + frame = Buffer.allocUnsafe(length + 2); + + frame[0] = 0x00; + frame.write(buffer, 1); + frame[frame.length - 1] = 0xFF; + + this._write(frame); + return true; + }, + + _handshakeResponse: function() { + var start = 'HTTP/1.1 101 Web Socket Protocol Handshake', + headers = [start, this._headers.toString(), '']; + + return Buffer.from(headers.join('\r\n'), 'utf8'); + }, + + _parseLeadingByte: function(octet) { + if ((octet & 0x80) === 0x80) { + this._length = 0; + this._stage = 1; + } else { + delete this._length; + delete this._skipped; + this._buffer = []; + this._stage = 2; + } + } +}; + +for (var key in instance) + Draft75.prototype[key] = instance[key]; + +module.exports = Draft75; diff --git a/node_modules/websocket-driver/lib/websocket/driver/draft76.js b/node_modules/websocket-driver/lib/websocket/driver/draft76.js new file mode 100644 index 0000000..bdaab31 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/draft76.js @@ -0,0 +1,117 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + Base = require('./base'), + Draft75 = require('./draft75'), + crypto = require('crypto'), + util = require('util'); + + +var numberFromKey = function(key) { + return parseInt((key.match(/[0-9]/g) || []).join(''), 10); +}; + +var spacesInKey = function(key) { + return (key.match(/ /g) || []).length; +}; + + +var Draft76 = function(request, url, options) { + Draft75.apply(this, arguments); + this._stage = -1; + this._body = []; + this.version = 'hixie-76'; + + this._headers.clear(); + + this._headers.set('Upgrade', 'WebSocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Origin', this._request.headers.origin); + this._headers.set('Sec-WebSocket-Location', this.url); +}; +util.inherits(Draft76, Draft75); + +var instance = { + BODY_SIZE: 8, + + start: function() { + if (!Draft75.prototype.start.call(this)) return false; + this._started = true; + this._sendHandshakeBody(); + return true; + }, + + close: function() { + if (this.readyState === 3) return false; + if (this.readyState === 1) this._write(Buffer.from([0xFF, 0x00])); + this.readyState = 3; + this.emit('close', new Base.CloseEvent(null, null)); + return true; + }, + + _handshakeResponse: function() { + var headers = this._request.headers, + key1 = headers['sec-websocket-key1'], + key2 = headers['sec-websocket-key2']; + + if (!key1) throw new Error('Missing required header: Sec-WebSocket-Key1'); + if (!key2) throw new Error('Missing required header: Sec-WebSocket-Key2'); + + var number1 = numberFromKey(key1), + spaces1 = spacesInKey(key1), + + number2 = numberFromKey(key2), + spaces2 = spacesInKey(key2); + + if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0) + throw new Error('Client sent invalid Sec-WebSocket-Key headers'); + + this._keyValues = [number1 / spaces1, number2 / spaces2]; + + var start = 'HTTP/1.1 101 WebSocket Protocol Handshake', + headers = [start, this._headers.toString(), '']; + + return Buffer.from(headers.join('\r\n'), 'binary'); + }, + + _handshakeSignature: function() { + if (this._body.length < this.BODY_SIZE) return null; + + var md5 = crypto.createHash('md5'), + buffer = Buffer.allocUnsafe(8 + this.BODY_SIZE); + + buffer.writeUInt32BE(this._keyValues[0], 0); + buffer.writeUInt32BE(this._keyValues[1], 4); + Buffer.from(this._body).copy(buffer, 8, 0, this.BODY_SIZE); + + md5.update(buffer); + return Buffer.from(md5.digest('binary'), 'binary'); + }, + + _sendHandshakeBody: function() { + if (!this._started) return; + var signature = this._handshakeSignature(); + if (!signature) return; + + this._write(signature); + this._stage = 0; + this._open(); + + if (this._body.length > this.BODY_SIZE) + this.parse(this._body.slice(this.BODY_SIZE)); + }, + + _parseLeadingByte: function(octet) { + if (octet !== 0xFF) + return Draft75.prototype._parseLeadingByte.call(this, octet); + + this._closing = true; + this._length = 0; + this._stage = 1; + } +}; + +for (var key in instance) + Draft76.prototype[key] = instance[key]; + +module.exports = Draft76; diff --git a/node_modules/websocket-driver/lib/websocket/driver/headers.js b/node_modules/websocket-driver/lib/websocket/driver/headers.js new file mode 100644 index 0000000..bc96b7d --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/headers.js @@ -0,0 +1,35 @@ +'use strict'; + +var Headers = function() { + this.clear(); +}; + +Headers.prototype.ALLOWED_DUPLICATES = ['set-cookie', 'set-cookie2', 'warning', 'www-authenticate']; + +Headers.prototype.clear = function() { + this._sent = {}; + this._lines = []; +}; + +Headers.prototype.set = function(name, value) { + if (value === undefined) return; + + name = this._strip(name); + value = this._strip(value); + + var key = name.toLowerCase(); + if (!this._sent.hasOwnProperty(key) || this.ALLOWED_DUPLICATES.indexOf(key) >= 0) { + this._sent[key] = true; + this._lines.push(name + ': ' + value + '\r\n'); + } +}; + +Headers.prototype.toString = function() { + return this._lines.join(''); +}; + +Headers.prototype._strip = function(string) { + return string.toString().replace(/^ */, '').replace(/ *$/, ''); +}; + +module.exports = Headers; diff --git a/node_modules/websocket-driver/lib/websocket/driver/hybi.js b/node_modules/websocket-driver/lib/websocket/driver/hybi.js new file mode 100644 index 0000000..9027f90 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/hybi.js @@ -0,0 +1,483 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + crypto = require('crypto'), + util = require('util'), + Extensions = require('websocket-extensions'), + Base = require('./base'), + Frame = require('./hybi/frame'), + Message = require('./hybi/message'); + +var Hybi = function(request, url, options) { + Base.apply(this, arguments); + + this._extensions = new Extensions(); + this._stage = 0; + this._masking = this._options.masking; + this._protocols = this._options.protocols || []; + this._requireMasking = this._options.requireMasking; + this._pingCallbacks = {}; + + if (typeof this._protocols === 'string') + this._protocols = this._protocols.split(/ *, */); + + if (!this._request) return; + + var protos = this._request.headers['sec-websocket-protocol'], + supported = this._protocols; + + if (protos !== undefined) { + if (typeof protos === 'string') protos = protos.split(/ *, */); + this.protocol = protos.filter(function(p) { return supported.indexOf(p) >= 0 })[0]; + } + + this.version = 'hybi-' + Hybi.VERSION; +}; +util.inherits(Hybi, Base); + +Hybi.VERSION = '13'; + +Hybi.mask = function(payload, mask, offset) { + if (!mask || mask.length === 0) return payload; + offset = offset || 0; + + for (var i = 0, n = payload.length - offset; i < n; i++) { + payload[offset + i] = payload[offset + i] ^ mask[i % 4]; + } + return payload; +}; + +Hybi.generateAccept = function(key) { + var sha1 = crypto.createHash('sha1'); + sha1.update(key + Hybi.GUID); + return sha1.digest('base64'); +}; + +Hybi.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; + +var instance = { + FIN: 0x80, + MASK: 0x80, + RSV1: 0x40, + RSV2: 0x20, + RSV3: 0x10, + OPCODE: 0x0F, + LENGTH: 0x7F, + + OPCODES: { + continuation: 0, + text: 1, + binary: 2, + close: 8, + ping: 9, + pong: 10 + }, + + OPCODE_CODES: [0, 1, 2, 8, 9, 10], + MESSAGE_OPCODES: [0, 1, 2], + OPENING_OPCODES: [1, 2], + + ERRORS: { + normal_closure: 1000, + going_away: 1001, + protocol_error: 1002, + unacceptable: 1003, + encoding_error: 1007, + policy_violation: 1008, + too_large: 1009, + extension_error: 1010, + unexpected_condition: 1011 + }, + + ERROR_CODES: [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011], + DEFAULT_ERROR_CODE: 1000, + MIN_RESERVED_ERROR: 3000, + MAX_RESERVED_ERROR: 4999, + + // http://www.w3.org/International/questions/qa-forms-utf-8.en.php + UTF8_MATCH: /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/, + + addExtension: function(extension) { + this._extensions.add(extension); + return true; + }, + + parse: function(chunk) { + this._reader.put(chunk); + var buffer = true; + while (buffer) { + switch (this._stage) { + case 0: + buffer = this._reader.read(1); + if (buffer) this._parseOpcode(buffer[0]); + break; + + case 1: + buffer = this._reader.read(1); + if (buffer) this._parseLength(buffer[0]); + break; + + case 2: + buffer = this._reader.read(this._frame.lengthBytes); + if (buffer) this._parseExtendedLength(buffer); + break; + + case 3: + buffer = this._reader.read(4); + if (buffer) { + this._stage = 4; + this._frame.maskingKey = buffer; + } + break; + + case 4: + buffer = this._reader.read(this._frame.length); + if (buffer) { + this._stage = 0; + this._emitFrame(buffer); + } + break; + + default: + buffer = null; + } + } + }, + + text: function(message) { + if (this.readyState > 1) return false; + return this.frame(message, 'text'); + }, + + binary: function(message) { + if (this.readyState > 1) return false; + return this.frame(message, 'binary'); + }, + + ping: function(message, callback) { + if (this.readyState > 1) return false; + message = message || ''; + if (callback) this._pingCallbacks[message] = callback; + return this.frame(message, 'ping'); + }, + + pong: function(message) { + if (this.readyState > 1) return false; + message = message ||''; + return this.frame(message, 'pong'); + }, + + close: function(reason, code) { + reason = reason || ''; + code = code || this.ERRORS.normal_closure; + + if (this.readyState <= 0) { + this.readyState = 3; + this.emit('close', new Base.CloseEvent(code, reason)); + return true; + } else if (this.readyState === 1) { + this.readyState = 2; + this._extensions.close(function() { this.frame(reason, 'close', code) }, this); + return true; + } else { + return false; + } + }, + + frame: function(buffer, type, code) { + if (this.readyState <= 0) return this._queue([buffer, type, code]); + if (this.readyState > 2) return false; + + if (buffer instanceof Array) buffer = Buffer.from(buffer); + if (typeof buffer === 'number') buffer = buffer.toString(); + + var message = new Message(), + isText = (typeof buffer === 'string'), + payload, copy; + + message.rsv1 = message.rsv2 = message.rsv3 = false; + message.opcode = this.OPCODES[type || (isText ? 'text' : 'binary')]; + + payload = isText ? Buffer.from(buffer, 'utf8') : buffer; + + if (code) { + copy = payload; + payload = Buffer.allocUnsafe(2 + copy.length); + payload.writeUInt16BE(code, 0); + copy.copy(payload, 2); + } + message.data = payload; + + var onMessageReady = function(message) { + var frame = new Frame(); + + frame.final = true; + frame.rsv1 = message.rsv1; + frame.rsv2 = message.rsv2; + frame.rsv3 = message.rsv3; + frame.opcode = message.opcode; + frame.masked = !!this._masking; + frame.length = message.data.length; + frame.payload = message.data; + + if (frame.masked) frame.maskingKey = crypto.randomBytes(4); + + this._sendFrame(frame); + }; + + if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0) + this._extensions.processOutgoingMessage(message, function(error, message) { + if (error) return this._fail('extension_error', error.message); + onMessageReady.call(this, message); + }, this); + else + onMessageReady.call(this, message); + + return true; + }, + + _sendFrame: function(frame) { + var length = frame.length, + header = (length <= 125) ? 2 : (length <= 65535 ? 4 : 10), + offset = header + (frame.masked ? 4 : 0), + buffer = Buffer.allocUnsafe(offset + length), + masked = frame.masked ? this.MASK : 0; + + buffer[0] = (frame.final ? this.FIN : 0) | + (frame.rsv1 ? this.RSV1 : 0) | + (frame.rsv2 ? this.RSV2 : 0) | + (frame.rsv3 ? this.RSV3 : 0) | + frame.opcode; + + if (length <= 125) { + buffer[1] = masked | length; + } else if (length <= 65535) { + buffer[1] = masked | 126; + buffer.writeUInt16BE(length, 2); + } else { + buffer[1] = masked | 127; + buffer.writeUInt32BE(Math.floor(length / 0x100000000), 2); + buffer.writeUInt32BE(length % 0x100000000, 6); + } + + frame.payload.copy(buffer, offset); + + if (frame.masked) { + frame.maskingKey.copy(buffer, header); + Hybi.mask(buffer, frame.maskingKey, offset); + } + + this._write(buffer); + }, + + _handshakeResponse: function() { + var secKey = this._request.headers['sec-websocket-key'], + version = this._request.headers['sec-websocket-version']; + + if (version !== Hybi.VERSION) + throw new Error('Unsupported WebSocket version: ' + version); + + if (typeof secKey !== 'string') + throw new Error('Missing handshake request header: Sec-WebSocket-Key'); + + this._headers.set('Upgrade', 'websocket'); + this._headers.set('Connection', 'Upgrade'); + this._headers.set('Sec-WebSocket-Accept', Hybi.generateAccept(secKey)); + + if (this.protocol) this._headers.set('Sec-WebSocket-Protocol', this.protocol); + + var extensions = this._extensions.generateResponse(this._request.headers['sec-websocket-extensions']); + if (extensions) this._headers.set('Sec-WebSocket-Extensions', extensions); + + var start = 'HTTP/1.1 101 Switching Protocols', + headers = [start, this._headers.toString(), '']; + + return Buffer.from(headers.join('\r\n'), 'utf8'); + }, + + _shutdown: function(code, reason, error) { + delete this._frame; + delete this._message; + this._stage = 5; + + var sendCloseFrame = (this.readyState === 1); + this.readyState = 2; + + this._extensions.close(function() { + if (sendCloseFrame) this.frame(reason, 'close', code); + this.readyState = 3; + if (error) this.emit('error', new Error(reason)); + this.emit('close', new Base.CloseEvent(code, reason)); + }, this); + }, + + _fail: function(type, message) { + if (this.readyState > 1) return; + this._shutdown(this.ERRORS[type], message, true); + }, + + _parseOpcode: function(octet) { + var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) { + return (octet & rsv) === rsv; + }); + + var frame = this._frame = new Frame(); + + frame.final = (octet & this.FIN) === this.FIN; + frame.rsv1 = rsvs[0]; + frame.rsv2 = rsvs[1]; + frame.rsv3 = rsvs[2]; + frame.opcode = (octet & this.OPCODE); + + this._stage = 1; + + if (!this._extensions.validFrameRsv(frame)) + return this._fail('protocol_error', + 'One or more reserved bits are on: reserved1 = ' + (frame.rsv1 ? 1 : 0) + + ', reserved2 = ' + (frame.rsv2 ? 1 : 0) + + ', reserved3 = ' + (frame.rsv3 ? 1 : 0)); + + if (this.OPCODE_CODES.indexOf(frame.opcode) < 0) + return this._fail('protocol_error', 'Unrecognized frame opcode: ' + frame.opcode); + + if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final) + return this._fail('protocol_error', 'Received fragmented control frame: opcode = ' + frame.opcode); + + if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0) + return this._fail('protocol_error', 'Received new data frame but previous continuous frame is unfinished'); + }, + + _parseLength: function(octet) { + var frame = this._frame; + frame.masked = (octet & this.MASK) === this.MASK; + frame.length = (octet & this.LENGTH); + + if (frame.length >= 0 && frame.length <= 125) { + this._stage = frame.masked ? 3 : 4; + if (!this._checkFrameLength()) return; + } else { + this._stage = 2; + frame.lengthBytes = (frame.length === 126 ? 2 : 8); + } + + if (this._requireMasking && !frame.masked) + return this._fail('unacceptable', 'Received unmasked frame but masking is required'); + }, + + _parseExtendedLength: function(buffer) { + var frame = this._frame; + frame.length = this._readUInt(buffer); + + this._stage = frame.masked ? 3 : 4; + + if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125) + return this._fail('protocol_error', 'Received control frame having too long payload: ' + frame.length); + + if (!this._checkFrameLength()) return; + }, + + _checkFrameLength: function() { + var length = this._message ? this._message.length : 0; + + if (length + this._frame.length > this._maxLength) { + this._fail('too_large', 'WebSocket frame length too large'); + return false; + } else { + return true; + } + }, + + _emitFrame: function(buffer) { + var frame = this._frame, + payload = frame.payload = Hybi.mask(buffer, frame.maskingKey), + opcode = frame.opcode, + message, + code, reason, + callbacks, callback; + + delete this._frame; + + if (opcode === this.OPCODES.continuation) { + if (!this._message) return this._fail('protocol_error', 'Received unexpected continuation frame'); + this._message.pushFrame(frame); + } + + if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) { + this._message = new Message(); + this._message.pushFrame(frame); + } + + if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0) + return this._emitMessage(this._message); + + if (opcode === this.OPCODES.close) { + code = (payload.length >= 2) ? payload.readUInt16BE(0) : null; + reason = (payload.length > 2) ? this._encode(payload.slice(2)) : null; + + if (!(payload.length === 0) && + !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) && + this.ERROR_CODES.indexOf(code) < 0) + code = this.ERRORS.protocol_error; + + if (payload.length > 125 || (payload.length > 2 && !reason)) + code = this.ERRORS.protocol_error; + + this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || ''); + } + + if (opcode === this.OPCODES.ping) { + this.frame(payload, 'pong'); + this.emit('ping', new Base.PingEvent(payload.toString())) + } + + if (opcode === this.OPCODES.pong) { + callbacks = this._pingCallbacks; + message = this._encode(payload); + callback = callbacks[message]; + + delete callbacks[message]; + if (callback) callback() + + this.emit('pong', new Base.PongEvent(payload.toString())) + } + }, + + _emitMessage: function(message) { + var message = this._message; + message.read(); + + delete this._message; + + this._extensions.processIncomingMessage(message, function(error, message) { + if (error) return this._fail('extension_error', error.message); + + var payload = message.data; + if (message.opcode === this.OPCODES.text) payload = this._encode(payload); + + if (payload === null) + return this._fail('encoding_error', 'Could not decode a text frame as UTF-8'); + else + this.emit('message', new Base.MessageEvent(payload)); + }, this); + }, + + _encode: function(buffer) { + try { + var string = buffer.toString('binary', 0, buffer.length); + if (!this.UTF8_MATCH.test(string)) return null; + } catch (e) {} + return buffer.toString('utf8', 0, buffer.length); + }, + + _readUInt: function(buffer) { + if (buffer.length === 2) return buffer.readUInt16BE(0); + + return buffer.readUInt32BE(0) * 0x100000000 + + buffer.readUInt32BE(4); + } +}; + +for (var key in instance) + Hybi.prototype[key] = instance[key]; + +module.exports = Hybi; diff --git a/node_modules/websocket-driver/lib/websocket/driver/hybi/frame.js b/node_modules/websocket-driver/lib/websocket/driver/hybi/frame.js new file mode 100644 index 0000000..0fb003f --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/hybi/frame.js @@ -0,0 +1,21 @@ +'use strict'; + +var Frame = function() {}; + +var instance = { + final: false, + rsv1: false, + rsv2: false, + rsv3: false, + opcode: null, + masked: false, + maskingKey: null, + lengthBytes: 1, + length: 0, + payload: null +}; + +for (var key in instance) + Frame.prototype[key] = instance[key]; + +module.exports = Frame; diff --git a/node_modules/websocket-driver/lib/websocket/driver/hybi/message.js b/node_modules/websocket-driver/lib/websocket/driver/hybi/message.js new file mode 100644 index 0000000..e881273 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/hybi/message.js @@ -0,0 +1,34 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var Message = function() { + this.rsv1 = false; + this.rsv2 = false; + this.rsv3 = false; + this.opcode = null; + this.length = 0; + this._chunks = []; +}; + +var instance = { + read: function() { + return this.data = this.data || Buffer.concat(this._chunks, this.length); + }, + + pushFrame: function(frame) { + this.rsv1 = this.rsv1 || frame.rsv1; + this.rsv2 = this.rsv2 || frame.rsv2; + this.rsv3 = this.rsv3 || frame.rsv3; + + if (this.opcode === null) this.opcode = frame.opcode; + + this._chunks.push(frame.payload); + this.length += frame.length; + } +}; + +for (var key in instance) + Message.prototype[key] = instance[key]; + +module.exports = Message; diff --git a/node_modules/websocket-driver/lib/websocket/driver/proxy.js b/node_modules/websocket-driver/lib/websocket/driver/proxy.js new file mode 100644 index 0000000..2fdd32e --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/proxy.js @@ -0,0 +1,99 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer, + Stream = require('stream').Stream, + url = require('url'), + util = require('util'), + Base = require('./base'), + Headers = require('./headers'), + HttpParser = require('../http_parser'); + +var PORTS = { 'ws:': 80, 'wss:': 443 }; + +var Proxy = function(client, origin, options) { + this._client = client; + this._http = new HttpParser('response'); + this._origin = (typeof client.url === 'object') ? client.url : url.parse(client.url); + this._url = (typeof origin === 'object') ? origin : url.parse(origin); + this._options = options || {}; + this._state = 0; + + this.readable = this.writable = true; + this._paused = false; + + this._headers = new Headers(); + this._headers.set('Host', this._origin.host); + this._headers.set('Connection', 'keep-alive'); + this._headers.set('Proxy-Connection', 'keep-alive'); + + var auth = this._url.auth && Buffer.from(this._url.auth, 'utf8').toString('base64'); + if (auth) this._headers.set('Proxy-Authorization', 'Basic ' + auth); +}; +util.inherits(Proxy, Stream); + +var instance = { + setHeader: function(name, value) { + if (this._state !== 0) return false; + this._headers.set(name, value); + return true; + }, + + start: function() { + if (this._state !== 0) return false; + this._state = 1; + + var origin = this._origin, + port = origin.port || PORTS[origin.protocol], + start = 'CONNECT ' + origin.hostname + ':' + port + ' HTTP/1.1'; + + var headers = [start, this._headers.toString(), '']; + + this.emit('data', Buffer.from(headers.join('\r\n'), 'utf8')); + return true; + }, + + pause: function() { + this._paused = true; + }, + + resume: function() { + this._paused = false; + this.emit('drain'); + }, + + write: function(chunk) { + if (!this.writable) return false; + + this._http.parse(chunk); + if (!this._http.isComplete()) return !this._paused; + + this.statusCode = this._http.statusCode; + this.headers = this._http.headers; + + if (this.statusCode === 200) { + this.emit('connect', new Base.ConnectEvent()); + } else { + var message = "Can't establish a connection to the server at " + this._origin.href; + this.emit('error', new Error(message)); + } + this.end(); + return !this._paused; + }, + + end: function(chunk) { + if (!this.writable) return; + if (chunk !== undefined) this.write(chunk); + this.readable = this.writable = false; + this.emit('close'); + this.emit('end'); + }, + + destroy: function() { + this.end(); + } +}; + +for (var key in instance) + Proxy.prototype[key] = instance[key]; + +module.exports = Proxy; diff --git a/node_modules/websocket-driver/lib/websocket/driver/server.js b/node_modules/websocket-driver/lib/websocket/driver/server.js new file mode 100644 index 0000000..dc635b0 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/server.js @@ -0,0 +1,112 @@ +'use strict'; + +var util = require('util'), + HttpParser = require('../http_parser'), + Base = require('./base'), + Draft75 = require('./draft75'), + Draft76 = require('./draft76'), + Hybi = require('./hybi'); + +var Server = function(options) { + Base.call(this, null, null, options); + this._http = new HttpParser('request'); +}; +util.inherits(Server, Base); + +var instance = { + EVENTS: ['open', 'message', 'error', 'close', 'ping', 'pong'], + + _bindEventListeners: function() { + this.messages.on('error', function() {}); + this.on('error', function() {}); + }, + + parse: function(chunk) { + if (this._delegate) return this._delegate.parse(chunk); + + this._http.parse(chunk); + if (!this._http.isComplete()) return; + + this.method = this._http.method; + this.url = this._http.url; + this.headers = this._http.headers; + this.body = this._http.body; + + var self = this; + this._delegate = Server.http(this, this._options); + this._delegate.messages = this.messages; + this._delegate.io = this.io; + this._open(); + + this.EVENTS.forEach(function(event) { + this._delegate.on(event, function(e) { self.emit(event, e) }); + }, this); + + this.protocol = this._delegate.protocol; + this.version = this._delegate.version; + + this.parse(this._http.body); + this.emit('connect', new Base.ConnectEvent()); + }, + + _open: function() { + this.__queue.forEach(function(msg) { + this._delegate[msg[0]].apply(this._delegate, msg[1]); + }, this); + this.__queue = []; + } +}; + +['addExtension', 'setHeader', 'start', 'frame', 'text', 'binary', 'ping', 'close'].forEach(function(method) { + instance[method] = function() { + if (this._delegate) { + return this._delegate[method].apply(this._delegate, arguments); + } else { + this.__queue.push([method, arguments]); + return true; + } + }; +}); + +for (var key in instance) + Server.prototype[key] = instance[key]; + +Server.isSecureRequest = function(request) { + if (request.connection && request.connection.authorized !== undefined) return true; + if (request.socket && request.socket.secure) return true; + + var headers = request.headers; + if (!headers) return false; + if (headers['https'] === 'on') return true; + if (headers['x-forwarded-ssl'] === 'on') return true; + if (headers['x-forwarded-scheme'] === 'https') return true; + if (headers['x-forwarded-proto'] === 'https') return true; + + return false; +}; + +Server.determineUrl = function(request) { + var scheme = this.isSecureRequest(request) ? 'wss:' : 'ws:'; + return scheme + '//' + request.headers.host + request.url; +}; + +Server.http = function(request, options) { + options = options || {}; + if (options.requireMasking === undefined) options.requireMasking = true; + + var headers = request.headers, + version = headers['sec-websocket-version'], + key = headers['sec-websocket-key'], + key1 = headers['sec-websocket-key1'], + key2 = headers['sec-websocket-key2'], + url = this.determineUrl(request); + + if (version || key) + return new Hybi(request, url, options); + else if (key1 || key2) + return new Draft76(request, url, options); + else + return new Draft75(request, url, options); +}; + +module.exports = Server; diff --git a/node_modules/websocket-driver/lib/websocket/driver/stream_reader.js b/node_modules/websocket-driver/lib/websocket/driver/stream_reader.js new file mode 100644 index 0000000..3564da8 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/driver/stream_reader.js @@ -0,0 +1,69 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var StreamReader = function() { + this._queue = []; + this._queueSize = 0; + this._offset = 0; +}; + +StreamReader.prototype.put = function(buffer) { + if (!buffer || buffer.length === 0) return; + if (!Buffer.isBuffer(buffer)) buffer = Buffer.from(buffer); + this._queue.push(buffer); + this._queueSize += buffer.length; +}; + +StreamReader.prototype.read = function(length) { + if (length > this._queueSize) return null; + if (length === 0) return Buffer.alloc(0); + + this._queueSize -= length; + + var queue = this._queue, + remain = length, + first = queue[0], + buffers, buffer; + + if (first.length >= length) { + if (first.length === length) { + return queue.shift(); + } else { + buffer = first.slice(0, length); + queue[0] = first.slice(length); + return buffer; + } + } + + for (var i = 0, n = queue.length; i < n; i++) { + if (remain < queue[i].length) break; + remain -= queue[i].length; + } + buffers = queue.splice(0, i); + + if (remain > 0 && queue.length > 0) { + buffers.push(queue[0].slice(0, remain)); + queue[0] = queue[0].slice(remain); + } + return Buffer.concat(buffers, length); +}; + +StreamReader.prototype.eachByte = function(callback, context) { + var buffer, n, index; + + while (this._queue.length > 0) { + buffer = this._queue[0]; + n = buffer.length; + + while (this._offset < n) { + index = this._offset; + this._offset += 1; + callback.call(context, buffer[index]); + } + this._offset = 0; + this._queue.shift(); + } +}; + +module.exports = StreamReader; diff --git a/node_modules/websocket-driver/lib/websocket/http_parser.js b/node_modules/websocket-driver/lib/websocket/http_parser.js new file mode 100644 index 0000000..1396656 --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/http_parser.js @@ -0,0 +1,135 @@ +'use strict'; + +var NodeHTTPParser = require('http-parser-js').HTTPParser, + Buffer = require('safe-buffer').Buffer; + +var TYPES = { + request: NodeHTTPParser.REQUEST || 'request', + response: NodeHTTPParser.RESPONSE || 'response' +}; + +var HttpParser = function(type) { + this._type = type; + this._parser = new NodeHTTPParser(TYPES[type]); + this._complete = false; + this.headers = {}; + + var current = null, + self = this; + + this._parser.onHeaderField = function(b, start, length) { + current = b.toString('utf8', start, start + length).toLowerCase(); + }; + + this._parser.onHeaderValue = function(b, start, length) { + var value = b.toString('utf8', start, start + length); + + if (self.headers.hasOwnProperty(current)) + self.headers[current] += ', ' + value; + else + self.headers[current] = value; + }; + + this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] = + function(majorVersion, minorVersion, headers, method, pathname, statusCode) { + var info = arguments[0]; + + if (typeof info === 'object') { + method = info.method; + pathname = info.url; + statusCode = info.statusCode; + headers = info.headers; + } + + self.method = (typeof method === 'number') ? HttpParser.METHODS[method] : method; + self.statusCode = statusCode; + self.url = pathname; + + if (!headers) return; + + for (var i = 0, n = headers.length, key, value; i < n; i += 2) { + key = headers[i].toLowerCase(); + value = headers[i+1]; + if (self.headers.hasOwnProperty(key)) + self.headers[key] += ', ' + value; + else + self.headers[key] = value; + } + + self._complete = true; + }; +}; + +HttpParser.METHODS = { + 0: 'DELETE', + 1: 'GET', + 2: 'HEAD', + 3: 'POST', + 4: 'PUT', + 5: 'CONNECT', + 6: 'OPTIONS', + 7: 'TRACE', + 8: 'COPY', + 9: 'LOCK', + 10: 'MKCOL', + 11: 'MOVE', + 12: 'PROPFIND', + 13: 'PROPPATCH', + 14: 'SEARCH', + 15: 'UNLOCK', + 16: 'BIND', + 17: 'REBIND', + 18: 'UNBIND', + 19: 'ACL', + 20: 'REPORT', + 21: 'MKACTIVITY', + 22: 'CHECKOUT', + 23: 'MERGE', + 24: 'M-SEARCH', + 25: 'NOTIFY', + 26: 'SUBSCRIBE', + 27: 'UNSUBSCRIBE', + 28: 'PATCH', + 29: 'PURGE', + 30: 'MKCALENDAR', + 31: 'LINK', + 32: 'UNLINK' +}; + +var VERSION = process.version + ? process.version.match(/[0-9]+/g).map(function(n) { return parseInt(n, 10) }) + : []; + +if (VERSION[0] === 0 && VERSION[1] === 12) { + HttpParser.METHODS[16] = 'REPORT'; + HttpParser.METHODS[17] = 'MKACTIVITY'; + HttpParser.METHODS[18] = 'CHECKOUT'; + HttpParser.METHODS[19] = 'MERGE'; + HttpParser.METHODS[20] = 'M-SEARCH'; + HttpParser.METHODS[21] = 'NOTIFY'; + HttpParser.METHODS[22] = 'SUBSCRIBE'; + HttpParser.METHODS[23] = 'UNSUBSCRIBE'; + HttpParser.METHODS[24] = 'PATCH'; + HttpParser.METHODS[25] = 'PURGE'; +} + +HttpParser.prototype.isComplete = function() { + return this._complete; +}; + +HttpParser.prototype.parse = function(chunk) { + var consumed = this._parser.execute(chunk, 0, chunk.length); + + if (typeof consumed !== 'number') { + this.error = consumed; + this._complete = true; + return; + } + + if (this._complete) + this.body = (consumed < chunk.length) + ? chunk.slice(consumed) + : Buffer.alloc(0); +}; + +module.exports = HttpParser; diff --git a/node_modules/websocket-driver/lib/websocket/streams.js b/node_modules/websocket-driver/lib/websocket/streams.js new file mode 100644 index 0000000..96ab31f --- /dev/null +++ b/node_modules/websocket-driver/lib/websocket/streams.js @@ -0,0 +1,146 @@ +'use strict'; + +/** + +Streams in a WebSocket connection +--------------------------------- + +We model a WebSocket as two duplex streams: one stream is for the wire protocol +over an I/O socket, and the other is for incoming/outgoing messages. + + + +----------+ +---------+ +----------+ + [1] write(chunk) -->| ~~~~~~~~ +----->| parse() +----->| ~~~~~~~~ +--> emit('data') [2] + | | +----+----+ | | + | | | | | + | IO | | [5] | Messages | + | | V | | + | | +---------+ | | + [4] emit('data') <--+ ~~~~~~~~ |<-----+ frame() |<-----+ ~~~~~~~~ |<-- write(chunk) [3] + +----------+ +---------+ +----------+ + + +Message transfer in each direction is simple: IO receives a byte stream [1] and +sends this stream for parsing. The parser will periodically emit a complete +message text on the Messages stream [2]. Similarly, when messages are written +to the Messages stream [3], they are framed using the WebSocket wire format and +emitted via IO [4]. + +There is a feedback loop via [5] since some input from [1] will be things like +ping, pong and close frames. In these cases the protocol responds by emitting +responses directly back to [4] rather than emitting messages via [2]. + +For the purposes of flow control, we consider the sources of each Readable +stream to be as follows: + +* [2] receives input from [1] +* [4] receives input from [1] and [3] + +The classes below express the relationships described above without prescribing +anything about how parse() and frame() work, other than assuming they emit +'data' events to the IO and Messages streams. They will work with any protocol +driver having these two methods. +**/ + + +var Stream = require('stream').Stream, + util = require('util'); + + +var IO = function(driver) { + this.readable = this.writable = true; + this._paused = false; + this._driver = driver; +}; +util.inherits(IO, Stream); + +// The IO pause() and resume() methods will be called when the socket we are +// piping to gets backed up and drains. Since IO output [4] comes from IO input +// [1] and Messages input [3], we need to tell both of those to return false +// from write() when this stream is paused. + +IO.prototype.pause = function() { + this._paused = true; + this._driver.messages._paused = true; +}; + +IO.prototype.resume = function() { + this._paused = false; + this.emit('drain'); + + var messages = this._driver.messages; + messages._paused = false; + messages.emit('drain'); +}; + +// When we receive input from a socket, send it to the parser and tell the +// source whether to back off. +IO.prototype.write = function(chunk) { + if (!this.writable) return false; + this._driver.parse(chunk); + return !this._paused; +}; + +// The IO end() method will be called when the socket piping into it emits +// 'close' or 'end', i.e. the socket is closed. In this situation the Messages +// stream will not emit any more data so we emit 'end'. +IO.prototype.end = function(chunk) { + if (!this.writable) return; + if (chunk !== undefined) this.write(chunk); + this.writable = false; + + var messages = this._driver.messages; + if (messages.readable) { + messages.readable = messages.writable = false; + messages.emit('end'); + } +}; + +IO.prototype.destroy = function() { + this.end(); +}; + + +var Messages = function(driver) { + this.readable = this.writable = true; + this._paused = false; + this._driver = driver; +}; +util.inherits(Messages, Stream); + +// The Messages pause() and resume() methods will be called when the app that's +// processing the messages gets backed up and drains. If we're emitting +// messages too fast we should tell the source to slow down. Message output [2] +// comes from IO input [1]. + +Messages.prototype.pause = function() { + this._driver.io._paused = true; +}; + +Messages.prototype.resume = function() { + this._driver.io._paused = false; + this._driver.io.emit('drain'); +}; + +// When we receive messages from the user, send them to the formatter and tell +// the source whether to back off. +Messages.prototype.write = function(message) { + if (!this.writable) return false; + if (typeof message === 'string') this._driver.text(message); + else this._driver.binary(message); + return !this._paused; +}; + +// The Messages end() method will be called when a stream piping into it emits +// 'end'. Many streams may be piped into the WebSocket and one of them ending +// does not mean the whole socket is done, so just process the input and move +// on leaving the socket open. +Messages.prototype.end = function(message) { + if (message !== undefined) this.write(message); +}; + +Messages.prototype.destroy = function() {}; + + +exports.IO = IO; +exports.Messages = Messages; diff --git a/node_modules/websocket-driver/package.json b/node_modules/websocket-driver/package.json new file mode 100644 index 0000000..f9a7ea2 --- /dev/null +++ b/node_modules/websocket-driver/package.json @@ -0,0 +1,69 @@ +{ + "_args": [ + [ + "websocket-driver@0.7.4", + "/home/other/discord_bot" + ] + ], + "_from": "websocket-driver@0.7.4", + "_id": "websocket-driver@0.7.4", + "_inBundle": false, + "_integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "_location": "/websocket-driver", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "websocket-driver@0.7.4", + "name": "websocket-driver", + "escapedName": "websocket-driver", + "rawSpec": "0.7.4", + "saveSpec": null, + "fetchSpec": "0.7.4" + }, + "_requiredBy": [ + "/faye-websocket" + ], + "_resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "_spec": "0.7.4", + "_where": "/home/other/discord_bot", + "author": { + "name": "James Coglan", + "email": "jcoglan@gmail.com", + "url": "http://jcoglan.com/" + }, + "bugs": { + "url": "https://github.com/faye/websocket-driver-node/issues" + }, + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "description": "WebSocket protocol handler with pluggable I/O", + "devDependencies": { + "jstest": "*", + "permessage-deflate": "*" + }, + "engines": { + "node": ">=0.8.0" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/faye/websocket-driver-node", + "keywords": [ + "websocket" + ], + "license": "Apache-2.0", + "main": "./lib/websocket/driver", + "name": "websocket-driver", + "repository": { + "type": "git", + "url": "git://github.com/faye/websocket-driver-node.git" + }, + "scripts": { + "test": "jstest spec/runner.js" + }, + "version": "0.7.4" +} diff --git a/node_modules/websocket-extensions/CHANGELOG.md b/node_modules/websocket-extensions/CHANGELOG.md new file mode 100644 index 0000000..bb84f5a --- /dev/null +++ b/node_modules/websocket-extensions/CHANGELOG.md @@ -0,0 +1,28 @@ +### 0.1.4 / 2020-06-02 + +- Remove a ReDoS vulnerability in the header parser (CVE-2020-7662, reported by + Robert McLaughlin) +- Change license from MIT to Apache 2.0 + +### 0.1.3 / 2017-11-11 + +- Accept extension names and parameters including uppercase letters +- Handle extension names that clash with `Object.prototype` properties + +### 0.1.2 / 2017-09-10 + +- Catch synchronous exceptions thrown when calling an extension +- Fix race condition caused when a message is pushed after a cell has stopped + due to an error +- Fix failure of `close()` to return if a message that's queued after one that + produces an error never finishes being processed + +### 0.1.1 / 2015-02-19 + +- Prevent sessions being closed before they have finished processing messages +- Add a callback to `Extensions.close()` so the caller can tell when it's safe + to close the socket + +### 0.1.0 / 2014-12-12 + +- Initial release diff --git a/node_modules/websocket-extensions/LICENSE.md b/node_modules/websocket-extensions/LICENSE.md new file mode 100644 index 0000000..3a88e51 --- /dev/null +++ b/node_modules/websocket-extensions/LICENSE.md @@ -0,0 +1,12 @@ +Copyright 2014-2020 James Coglan + +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/websocket-extensions/README.md b/node_modules/websocket-extensions/README.md new file mode 100644 index 0000000..68694ea --- /dev/null +++ b/node_modules/websocket-extensions/README.md @@ -0,0 +1,331 @@ +# websocket-extensions [![Build status](https://secure.travis-ci.org/faye/websocket-extensions-node.svg)](http://travis-ci.org/faye/websocket-extensions-node) + +A minimal framework that supports the implementation of WebSocket extensions in +a way that's decoupled from the main protocol. This library aims to allow a +WebSocket extension to be written and used with any protocol library, by +defining abstract representations of frames and messages that allow modules to +co-operate. + +`websocket-extensions` provides a container for registering extension plugins, +and provides all the functions required to negotiate which extensions to use +during a session via the `Sec-WebSocket-Extensions` header. By implementing the +APIs defined in this document, an extension may be used by any WebSocket library +based on this framework. + +## Installation + +``` +$ npm install websocket-extensions +``` + +## Usage + +There are two main audiences for this library: authors implementing the +WebSocket protocol, and authors implementing extensions. End users of a +WebSocket library or an extension should be able to use any extension by passing +it as an argument to their chosen protocol library, without needing to know how +either of them work, or how the `websocket-extensions` framework operates. + +The library is designed with the aim that any protocol implementation and any +extension can be used together, so long as they support the same abstract +representation of frames and messages. + +### Data types + +The APIs provided by the framework rely on two data types; extensions will +expect to be given data and to be able to return data in these formats: + +#### *Frame* + +*Frame* is a structure representing a single WebSocket frame of any type. Frames +are simple objects that must have at least the following properties, which +represent the data encoded in the frame: + +| property | description | +| ------------ | ------------------------------------------------------------------ | +| `final` | `true` if the `FIN` bit is set, `false` otherwise | +| `rsv1` | `true` if the `RSV1` bit is set, `false` otherwise | +| `rsv2` | `true` if the `RSV2` bit is set, `false` otherwise | +| `rsv3` | `true` if the `RSV3` bit is set, `false` otherwise | +| `opcode` | the numeric opcode (`0`, `1`, `2`, `8`, `9`, or `10`) of the frame | +| `masked` | `true` if the `MASK` bit is set, `false` otherwise | +| `maskingKey` | a 4-byte `Buffer` if `masked` is `true`, otherwise `null` | +| `payload` | a `Buffer` containing the (unmasked) application data | + +#### *Message* + +A *Message* represents a complete application message, which can be formed from +text, binary and continuation frames. It has the following properties: + +| property | description | +| -------- | ----------------------------------------------------------------- | +| `rsv1` | `true` if the first frame of the message has the `RSV1` bit set | +| `rsv2` | `true` if the first frame of the message has the `RSV2` bit set | +| `rsv3` | `true` if the first frame of the message has the `RSV3` bit set | +| `opcode` | the numeric opcode (`1` or `2`) of the first frame of the message | +| `data` | the concatenation of all the frame payloads in the message | + +### For driver authors + +A driver author is someone implementing the WebSocket protocol proper, and who +wishes end users to be able to use WebSocket extensions with their library. + +At the start of a WebSocket session, on both the client and the server side, +they should begin by creating an extension container and adding whichever +extensions they want to use. + +```js +var Extensions = require('websocket-extensions'), + deflate = require('permessage-deflate'); + +var exts = new Extensions(); +exts.add(deflate); +``` + +In the following examples, `exts` refers to this `Extensions` instance. + +#### Client sessions + +Clients will use the methods `generateOffer()` and `activate(header)`. + +As part of the handshake process, the client must send a +`Sec-WebSocket-Extensions` header to advertise that it supports the registered +extensions. This header should be generated using: + +```js +request.headers['sec-websocket-extensions'] = exts.generateOffer(); +``` + +This returns a string, for example `"permessage-deflate; +client_max_window_bits"`, that represents all the extensions the client is +offering to use, and their parameters. This string may contain multiple offers +for the same extension. + +When the client receives the handshake response from the server, it should pass +the incoming `Sec-WebSocket-Extensions` header in to `exts` to activate the +extensions the server has accepted: + +```js +exts.activate(response.headers['sec-websocket-extensions']); +``` + +If the server has sent any extension responses that the client does not +recognize, or are in conflict with one another for use of RSV bits, or that use +invalid parameters for the named extensions, then `exts.activate()` will +`throw`. In this event, the client driver should fail the connection with +closing code `1010`. + +#### Server sessions + +Servers will use the method `generateResponse(header)`. + +A server session needs to generate a `Sec-WebSocket-Extensions` header to send +in its handshake response: + +```js +var clientOffer = request.headers['sec-websocket-extensions'], + extResponse = exts.generateResponse(clientOffer); + +response.headers['sec-websocket-extensions'] = extResponse; +``` + +Calling `exts.generateResponse(header)` activates those extensions the client +has asked to use, if they are registered, asks each extension for a set of +response parameters, and returns a string containing the response parameters for +all accepted extensions. + +#### In both directions + +Both clients and servers will use the methods `validFrameRsv(frame)`, +`processIncomingMessage(message)` and `processOutgoingMessage(message)`. + +The WebSocket protocol requires that frames do not have any of the `RSV` bits +set unless there is an extension in use that allows otherwise. When processing +an incoming frame, sessions should pass a *Frame* object to: + +```js +exts.validFrameRsv(frame) +``` + +If this method returns `false`, the session should fail the WebSocket connection +with closing code `1002`. + +To pass incoming messages through the extension stack, a session should +construct a *Message* object according to the above datatype definitions, and +call: + +```js +exts.processIncomingMessage(message, function(error, msg) { + // hand the message off to the application +}); +``` + +If any extensions fail to process the message, then the callback will yield an +error and the session should fail the WebSocket connection with closing code +`1010`. If `error` is `null`, then `msg` should be passed on to the application. + +To pass outgoing messages through the extension stack, a session should +construct a *Message* as before, and call: + +```js +exts.processOutgoingMessage(message, function(error, msg) { + // write message to the transport +}); +``` + +If any extensions fail to process the message, then the callback will yield an +error and the session should fail the WebSocket connection with closing code +`1010`. If `error` is `null`, then `message` should be converted into frames +(with the message's `rsv1`, `rsv2`, `rsv3` and `opcode` set on the first frame) +and written to the transport. + +At the end of the WebSocket session (either when the protocol is explicitly +ended or the transport connection disconnects), the driver should call: + +```js +exts.close(function() {}) +``` + +The callback is invoked when all extensions have finished processing any +messages in the pipeline and it's safe to close the socket. + +### For extension authors + +An extension author is someone implementing an extension that transforms +WebSocket messages passing between the client and server. They would like to +implement their extension once and have it work with any protocol library. + +Extension authors will not install `websocket-extensions` or call it directly. +Instead, they should implement the following API to allow their extension to +plug into the `websocket-extensions` framework. + +An `Extension` is any object that has the following properties: + +| property | description | +| -------- | ---------------------------------------------------------------------------- | +| `name` | a string containing the name of the extension as used in negotiation headers | +| `type` | a string, must be `"permessage"` | +| `rsv1` | either `true` if the extension uses the RSV1 bit, `false` otherwise | +| `rsv2` | either `true` if the extension uses the RSV2 bit, `false` otherwise | +| `rsv3` | either `true` if the extension uses the RSV3 bit, `false` otherwise | + +It must also implement the following methods: + +```js +ext.createClientSession() +``` + +This returns a *ClientSession*, whose interface is defined below. + +```js +ext.createServerSession(offers) +``` + +This takes an array of offer params and returns a *ServerSession*, whose +interface is defined below. For example, if the client handshake contains the +offer header: + +``` +Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; server_max_window_bits=8, \ + permessage-deflate; server_max_window_bits=15 +``` + +then the `permessage-deflate` extension will receive the call: + +```js +ext.createServerSession([ + { server_no_context_takeover: true, server_max_window_bits: 8 }, + { server_max_window_bits: 15 } +]); +``` + +The extension must decide which set of parameters it wants to accept, if any, +and return a *ServerSession* if it wants to accept the parameters and `null` +otherwise. + +#### *ClientSession* + +A *ClientSession* is the type returned by `ext.createClientSession()`. It must +implement the following methods, as well as the *Session* API listed below. + +```js +clientSession.generateOffer() +// e.g. -> [ +// { server_no_context_takeover: true, server_max_window_bits: 8 }, +// { server_max_window_bits: 15 } +// ] +``` + +This must return a set of parameters to include in the client's +`Sec-WebSocket-Extensions` offer header. If the session wants to offer multiple +configurations, it can return an array of sets of parameters as shown above. + +```js +clientSession.activate(params) // -> true +``` + +This must take a single set of parameters from the server's handshake response +and use them to configure the client session. If the client accepts the given +parameters, then this method must return `true`. If it returns any other value, +the framework will interpret this as the client rejecting the response, and will +`throw`. + +#### *ServerSession* + +A *ServerSession* is the type returned by `ext.createServerSession(offers)`. It +must implement the following methods, as well as the *Session* API listed below. + +```js +serverSession.generateResponse() +// e.g. -> { server_max_window_bits: 8 } +``` + +This returns the set of parameters the server session wants to send in its +`Sec-WebSocket-Extensions` response header. Only one set of parameters is +returned to the client per extension. Server sessions that would confict on +their use of RSV bits are not activated. + +#### *Session* + +The *Session* API must be implemented by both client and server sessions. It +contains two methods, `processIncomingMessage(message)` and +`processOutgoingMessage(message)`. + +```js +session.processIncomingMessage(message, function(error, msg) { ... }) +``` + +The session must implement this method to take an incoming *Message* as defined +above, transform it in any way it needs, then return it via the callback. If +there is an error processing the message, this method should yield an error as +the first argument. + +```js +session.processOutgoingMessage(message, function(error, msg) { ... }) +``` + +The session must implement this method to take an outgoing *Message* as defined +above, transform it in any way it needs, then return it via the callback. If +there is an error processing the message, this method should yield an error as +the first argument. + +Note that both `processIncomingMessage()` and `processOutgoingMessage()` can +perform their logic asynchronously, are allowed to process multiple messages +concurrently, and are not required to complete working on messages in the same +order the messages arrive. `websocket-extensions` will reorder messages as your +extension emits them and will make sure every extension is given messages in the +order they arrive from the driver. This allows extensions to maintain state that +depends on the messages' wire order, for example keeping a DEFLATE compression +context between messages. + +```js +session.close() +``` + +The framework will call this method when the WebSocket session ends, allowing +the session to release any resources it's using. + +## Examples + +- Consumer: [websocket-driver](https://github.com/faye/websocket-driver-node) +- Provider: [permessage-deflate](https://github.com/faye/permessage-deflate-node) diff --git a/node_modules/websocket-extensions/lib/parser.js b/node_modules/websocket-extensions/lib/parser.js new file mode 100644 index 0000000..533767e --- /dev/null +++ b/node_modules/websocket-extensions/lib/parser.js @@ -0,0 +1,103 @@ +'use strict'; + +var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)/, + NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z])/g, + QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/, + PARAM = new RegExp(TOKEN.source + '(?:=(?:' + TOKEN.source + '|' + QUOTED.source + '))?'), + EXT = new RegExp(TOKEN.source + '(?: *; *' + PARAM.source + ')*', 'g'), + EXT_LIST = new RegExp('^' + EXT.source + '(?: *, *' + EXT.source + ')*$'), + NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/; + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +var Parser = { + parseHeader: function(header) { + var offers = new Offers(); + if (header === '' || header === undefined) return offers; + + if (!EXT_LIST.test(header)) + throw new SyntaxError('Invalid Sec-WebSocket-Extensions header: ' + header); + + var values = header.match(EXT); + + values.forEach(function(value) { + var params = value.match(new RegExp(PARAM.source, 'g')), + name = params.shift(), + offer = {}; + + params.forEach(function(param) { + var args = param.match(PARAM), key = args[1], data; + + if (args[2] !== undefined) { + data = args[2]; + } else if (args[3] !== undefined) { + data = args[3].replace(/\\/g, ''); + } else { + data = true; + } + if (NUMBER.test(data)) data = parseFloat(data); + + if (hasOwnProperty.call(offer, key)) { + offer[key] = [].concat(offer[key]); + offer[key].push(data); + } else { + offer[key] = data; + } + }, this); + offers.push(name, offer); + }, this); + + return offers; + }, + + serializeParams: function(name, params) { + var values = []; + + var print = function(key, value) { + if (value instanceof Array) { + value.forEach(function(v) { print(key, v) }); + } else if (value === true) { + values.push(key); + } else if (typeof value === 'number') { + values.push(key + '=' + value); + } else if (NOTOKEN.test(value)) { + values.push(key + '="' + value.replace(/"/g, '\\"') + '"'); + } else { + values.push(key + '=' + value); + } + }; + + for (var key in params) print(key, params[key]); + + return [name].concat(values).join('; '); + } +}; + +var Offers = function() { + this._byName = {}; + this._inOrder = []; +}; + +Offers.prototype.push = function(name, params) { + if (!hasOwnProperty.call(this._byName, name)) + this._byName[name] = []; + + this._byName[name].push(params); + this._inOrder.push({ name: name, params: params }); +}; + +Offers.prototype.eachOffer = function(callback, context) { + var list = this._inOrder; + for (var i = 0, n = list.length; i < n; i++) + callback.call(context, list[i].name, list[i].params); +}; + +Offers.prototype.byName = function(name) { + return this._byName[name] || []; +}; + +Offers.prototype.toArray = function() { + return this._inOrder.slice(); +}; + +module.exports = Parser; diff --git a/node_modules/websocket-extensions/lib/pipeline/README.md b/node_modules/websocket-extensions/lib/pipeline/README.md new file mode 100644 index 0000000..322a9c5 --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/README.md @@ -0,0 +1,607 @@ +# Extension pipelining + +`websocket-extensions` models the extension negotiation and processing pipeline +of the WebSocket protocol. Between the driver parsing messages from the TCP +stream and handing those messages off to the application, there may exist a +stack of extensions that transform the message somehow. + +In the parlance of this framework, a *session* refers to a single instance of an +extension, acting on a particular socket on either the server or the client +side. A session may transform messages both incoming to the application and +outgoing from the application, for example the `permessage-deflate` extension +compresses outgoing messages and decompresses incoming messages. Message streams +in either direction are independent; that is, incoming and outgoing messages +cannot be assumed to 'pair up' as in a request-response protocol. + +Asynchronous processing of messages poses a number of problems that this +pipeline construction is intended to solve. + + +## Overview + +Logically, we have the following: + + + +-------------+ out +---+ +---+ +---+ +--------+ + | |------>| |---->| |---->| |------>| | + | Application | | A | | B | | C | | Driver | + | |<------| |<----| |<----| |<------| | + +-------------+ in +---+ +---+ +---+ +--------+ + + \ / + +----------o----------+ + | + sessions + + +For outgoing messages, the driver receives the result of + + C.outgoing(B.outgoing(A.outgoing(message))) + + or, [A, B, C].reduce(((m, ext) => ext.outgoing(m)), message) + +For incoming messages, the application receives the result of + + A.incoming(B.incoming(C.incoming(message))) + + or, [C, B, A].reduce(((m, ext) => ext.incoming(m)), message) + +A session is of the following type, to borrow notation from pseudo-Haskell: + + type Session = { + incoming :: Message -> Message + outgoing :: Message -> Message + close :: () -> () + } + +(That `() -> ()` syntax is intended to mean that `close()` is a nullary void +method; I apologise to any Haskell readers for not using the right monad.) + +The `incoming()` and `outgoing()` methods perform message transformation in the +respective directions; `close()` is called when a socket closes so the session +can release any resources it's holding, for example a DEFLATE de/compression +context. + +However because this is JavaScript, the `incoming()` and `outgoing()` methods +may be asynchronous (indeed, `permessage-deflate` is based on `zlib`, whose API +is stream-based). So their interface is strictly: + + type Session = { + incoming :: Message -> Callback -> () + outgoing :: Message -> Callback -> () + close :: () -> () + } + + type Callback = Either Error Message -> () + +This means a message *m2* can be pushed into a session while it's still +processing the preceding message *m1*. The messages can be processed +concurrently but they *must* be given to the next session in line (or to the +application) in the same order they came in. Applications will expect to receive +messages in the order they arrived over the wire, and sessions require this too. +So ordering of messages must be preserved throughout the pipeline. + +Consider the following highly simplified extension that deflates messages on the +wire. `message` is a value conforming the type: + + type Message = { + rsv1 :: Boolean + rsv2 :: Boolean + rsv3 :: Boolean + opcode :: Number + data :: Buffer + } + +Here's the extension: + +```js +var zlib = require('zlib'); + +var deflate = { + outgoing: function(message, callback) { + zlib.deflateRaw(message.data, function(error, result) { + message.rsv1 = true; + message.data = result; + callback(error, message); + }); + }, + + incoming: function(message, callback) { + // decompress inbound messages (elided) + }, + + close: function() { + // no state to clean up + } +}; +``` + +We can call it with a large message followed by a small one, and the small one +will be returned first: + +```js +var crypto = require('crypto'), + large = crypto.randomBytes(1 << 14), + small = new Buffer('hi'); + +deflate.outgoing({ data: large }, function() { + console.log(1, 'large'); +}); + +deflate.outgoing({ data: small }, function() { + console.log(2, 'small'); +}); + +/* prints: 2 'small' + 1 'large' */ +``` + +So a session that processes messages asynchronously may fail to preserve message +ordering. + +Now, this extension is stateless, so it can process messages in any order and +still produce the same output. But some extensions are stateful and require +message order to be preserved. + +For example, when using `permessage-deflate` without `no_context_takeover` set, +the session retains a DEFLATE de/compression context between messages, which +accumulates state as it consumes data (later messages can refer to sections of +previous ones to improve compression). Reordering parts of the DEFLATE stream +will result in a failed decompression. Messages must be decompressed in the same +order they were compressed by the peer in order for the DEFLATE protocol to +work. + +Finally, there is the problem of closing a socket. When a WebSocket is closed by +the application, or receives a closing request from the other peer, there may be +messages outgoing from the application and incoming from the peer in the +pipeline. If we close the socket and pipeline immediately, two problems arise: + +* We may send our own closing frame to the peer before all prior messages we + sent have been written to the socket, and before we have finished processing + all prior messages from the peer +* The session may be instructed to close its resources (e.g. its de/compression + context) while it's in the middle of processing a message, or before it has + received messages that are upstream of it in the pipeline + +Essentially, we must defer closing the sessions and sending a closing frame +until after all prior messages have exited the pipeline. + + +## Design goals + +* Message order must be preserved between the protocol driver, the extension + sessions, and the application +* Messages should be handed off to sessions and endpoints as soon as possible, + to maximise throughput of stateless sessions +* The closing procedure should block any further messages from entering the + pipeline, and should allow all existing messages to drain +* Sessions should be closed as soon as possible to prevent them holding memory + and other resources when they have no more messages to handle +* The closing API should allow the caller to detect when the pipeline is empty + and it is safe to continue the WebSocket closing procedure +* Individual extensions should remain as simple as possible to facilitate + modularity and independent authorship + +The final point about modularity is an important one: this framework is designed +to facilitate extensions existing as plugins, by decoupling the protocol driver, +extensions, and application. In an ideal world, plugins should only need to +contain code for their specific functionality, and not solve these problems that +apply to all sessions. Also, solving some of these problems requires +consideration of all active sessions collectively, which an individual session +is incapable of doing. + +For example, it is entirely possible to take the simple `deflate` extension +above and wrap its `incoming()` and `outgoing()` methods in two `Transform` +streams, producing this type: + + type Session = { + incoming :: TransformStream + outtoing :: TransformStream + close :: () -> () + } + +The `Transform` class makes it easy to wrap an async function such that message +order is preserved: + +```js +var stream = require('stream'), + session = new stream.Transform({ objectMode: true }); + +session._transform = function(message, _, callback) { + var self = this; + deflate.outgoing(message, function(error, result) { + self.push(result); + callback(); + }); +}; +``` + +However, this has a negative impact on throughput: it works by deferring +`callback()` until the async function has 'returned', which blocks `Transform` +from passing further input into the `_transform()` method until the current +message is dealt with completely. This would prevent sessions from processing +messages concurrently, and would unnecessarily reduce the throughput of +stateless extensions. + +So, input should be handed off to sessions as soon as possible, and all we need +is a mechanism to reorder the output so that message order is preserved for the +next session in line. + + +## Solution + +We now describe the model implemented here and how it meets the above design +goals. The above diagram where a stack of extensions sit between the driver and +application describes the data flow, but not the object graph. That looks like +this: + + + +--------+ + | Driver | + +---o----+ + | + V + +------------+ +----------+ + | Extensions o----->| Pipeline | + +------------+ +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + + +A driver using this framework holds an instance of the `Extensions` class, which +it uses to register extension plugins, negotiate headers and transform messages. +The `Extensions` instance itself holds a `Pipeline`, which contains an array of +`Cell` objects, each of which wraps one of the sessions. + + +### Message processing + +Both the `Pipeline` and `Cell` classes have `incoming()` and `outgoing()` +methods; the `Pipeline` interface pushes messages into the pipe, delegates the +message to each `Cell` in turn, then returns it back to the driver. Outgoing +messages pass through `A` then `B` then `C`, and incoming messages in the +reverse order. + +Internally, a `Cell` contains two `Functor` objects. A `Functor` wraps an async +function and makes sure its output messages maintain the order of its input +messages. This name is due to [@fronx](https://github.com/fronx), on the basis +that, by preserving message order, the abstraction preserves the *mapping* +between input and output messages. To use our simple `deflate` extension from +above: + +```js +var functor = new Functor(deflate, 'outgoing'); + +functor.call({ data: large }, function() { + console.log(1, 'large'); +}); + +functor.call({ data: small }, function() { + console.log(2, 'small'); +}); + +/* -> 1 'large' + 2 'small' */ +``` + +A `Cell` contains two of these, one for each direction: + + + +-----------------------+ + +---->| Functor [A, incoming] | + +----------+ | +-----------------------+ + | Cell [A] o------+ + +----------+ | +-----------------------+ + +---->| Functor [A, outgoing] | + +-----------------------+ + + +This satisfies the message transformation requirements: the `Pipeline` simply +loops over the cells in the appropriate direction to transform each message. +Because each `Cell` will preserve message order, we can pass a message to the +next `Cell` in line as soon as the current `Cell` returns it. This gives each +`Cell` all the messages in order while maximising throughput. + + +### Session closing + +We want to close each session as soon as possible, after all existing messages +have drained. To do this, each `Cell` begins with a pending message counter in +each direction, labelled `in` and `out` below. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 0 out: 0 + + +When a message *m1* enters the pipeline, say in the `outgoing` direction, we +increment the `pending.out` counter on all cells immediately. + + + +----------+ + m1 => | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 1 out: 1 out: 1 + + +*m1* is handed off to `A`, meanwhile a second message `m2` arrives in the same +direction. All `pending.out` counters are again incremented. + + + +----------+ + m2 => | Pipeline | + +-----o----+ + | + +---------------+---------------+ + m1 | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 2 out: 2 out: 2 + + +When the first cell's `A.outgoing` functor finishes processing *m1*, the first +`pending.out` counter is decremented and *m1* is handed off to cell `B`. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + m2 | m1 | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 1 out: 2 out: 2 + + + +As `B` finishes with *m1*, and as `A` finishes with *m2*, the `pending.out` +counters continue to decrement. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | m2 | m1 | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 1 out: 2 + + + +Say `C` is a little slow, and begins processing *m2* while still processing +*m1*. That's fine, the `Functor` mechanism will keep *m1* ahead of *m2* in the +output. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | m2 | m1 + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 0 out: 2 + + +Once all messages are dealt with, the counters return to `0`. + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 0 out: 0 + + +The same process applies in the `incoming` direction, the only difference being +that messages are passed to `C` first. + +This makes closing the sessions quite simple. When the driver wants to close the +socket, it calls `Pipeline.close()`. This *immediately* calls `close()` on all +the cells. If a cell has `in == out == 0`, then it immediately calls +`session.close()`. Otherwise, it stores the closing call and defers it until +`in` and `out` have both ticked down to zero. The pipeline will not accept new +messages after `close()` has been called, so we know the pending counts will not +increase after this point. + +This means each session is closed as soon as possible: `A` can close while the +slow `C` session is still working, because it knows there are no more messages +on the way. Similarly, `C` will defer closing if `close()` is called while *m1* +is still in `B`, and *m2* in `A`, because its pending count means it knows it +has work yet to do, even if it's not received those messages yet. This concern +cannot be addressed by extensions acting only on their own local state, unless +we pollute individual extensions by making them all implement this same +mechanism. + +The actual closing API at each level is slightly different: + + type Session = { + close :: () -> () + } + + type Cell = { + close :: () -> Promise () + } + + type Pipeline = { + close :: Callback -> () + } + +This might appear inconsistent so it's worth explaining. Remember that a +`Pipeline` holds a list of `Cell` objects, each wrapping a `Session`. The driver +talks (via the `Extensions` API) to the `Pipeline` interface, and it wants +`Pipeline.close()` to do two things: close all the sessions, and tell me when +it's safe to start the closing procedure (i.e. when all messages have drained +from the pipe and been handed off to the application or socket). A callback API +works well for that. + +At the other end of the stack, `Session.close()` is a nullary void method with +no callback or promise API because we don't care what it does, and whatever it +does do will not block the WebSocket protocol; we're not going to hold off +processing messages while a session closes its de/compression context. We just +tell it to close itself, and don't want to wait while it does that. + +In the middle, `Cell.close()` returns a promise rather than using a callback. +This is for two reasons. First, `Cell.close()` might not do anything +immediately, it might have to defer its effect while messages drain. So, if +given a callback, it would have to store it in a queue for later execution. +Callbacks work fine if your method does something and can then invoke the +callback itself, but if you need to store callbacks somewhere so another method +can execute them, a promise is a better fit. Second, it better serves the +purposes of `Pipeline.close()`: it wants to call `close()` on each of a list of +cells, and wait for all of them to finish. This is simple and idiomatic using +promises: + +```js +var closed = cells.map((cell) => cell.close()); +Promise.all(closed).then(callback); +``` + +(We don't actually use a full *Promises/A+* compatible promise here, we use a +much simplified construction that acts as a callback aggregater and resolves +synchronously and does not support chaining, but the principle is the same.) + + +### Error handling + +We've not mentioned error handling so far but it bears some explanation. The +above counter system still applies, but behaves slightly differently in the +presence of errors. + +Say we push three messages into the pipe in the outgoing direction: + + + +----------+ + m3, m2, m1 => | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 3 out: 3 out: 3 + + +They pass through the cells successfully up to this point: + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + m3 | m2 | m1 | + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 1 out: 2 out: 3 + + +At this point, session `B` produces an error while processing *m2*, that is *m2* +becomes *e2*. *m1* is still in the pipeline, and *m3* is queued behind *m2*. +What ought to happen is that *m1* is handed off to the socket, then *m2* is +released to the driver, which will detect the error and begin closing the +socket. No further processing should be done on *m3* and it should not be +released to the driver after the error is emitted. + +To handle this, we allow errors to pass down the pipeline just like messages do, +to maintain ordering. But, once a cell sees its session produce an error, or it +receives an error from upstream, it should refuse to accept any further +messages. Session `B` might have begun processing *m3* by the time it produces +the error *e2*, but `C` will have been given *e2* before it receives *m3*, and +can simply drop *m3*. + +Now, say *e2* reaches the slow session `C` while *m1* is still present, +meanwhile *m3* has been dropped. `C` will never receive *m3* since it will have +been dropped upstream. Under the present model, its `out` counter will be `3` +but it is only going to emit two more values: *m1* and *e2*. In order for +closing to work, we need to decrement `out` to reflect this. The situation +should look like this: + + + +----------+ + | Pipeline | + +-----o----+ + | + +---------------+---------------+ + | | e2 | m1 + +-----o----+ +-----o----+ +-----o----+ + | Cell [A] | | Cell [B] | | Cell [C] | + +----------+ +----------+ +----------+ + in: 0 in: 0 in: 0 + out: 0 out: 0 out: 2 + + +When a cell sees its session emit an error, or when it receives an error from +upstream, it sets its pending count in the appropriate direction to equal the +number of messages it is *currently* processing. It will not accept any messages +after it sees the error, so this will allow the counter to reach zero. + +Note that while *e2* is in the pipeline, `Pipeline` should drop any further +messages in the outgoing direction, but should continue to accept incoming +messages. Until *e2* makes it out of the pipe to the driver, behind previous +successful messages, the driver does not know an error has happened, and a +message may arrive over the socket and make it all the way through the incoming +pipe in the meantime. We only halt processing in the affected direction to avoid +doing unnecessary work since messages arriving after an error should not be +processed. + +Some unnecessary work may happen, for example any messages already in the +pipeline following *m2* will be processed by `A`, since it's upstream of the +error. Those messages will be dropped by `B`. + + +## Alternative ideas + +I am considering implementing `Functor` as an object-mode transform stream +rather than what is essentially an async function. Being object-mode, a stream +would preserve message boundaries and would also possibly help address +back-pressure. I'm not sure whether this would require external API changes so +that such streams could be connected to the downstream driver's streams. + + +## Acknowledgements + +Credit is due to [@mnowster](https://github.com/mnowster) for helping with the +design and to [@fronx](https://github.com/fronx) for helping name things. diff --git a/node_modules/websocket-extensions/lib/pipeline/cell.js b/node_modules/websocket-extensions/lib/pipeline/cell.js new file mode 100644 index 0000000..b2901ba --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/cell.js @@ -0,0 +1,53 @@ +'use strict'; + +var Functor = require('./functor'), + Pledge = require('./pledge'); + +var Cell = function(tuple) { + this._ext = tuple[0]; + this._session = tuple[1]; + + this._functors = { + incoming: new Functor(this._session, 'processIncomingMessage'), + outgoing: new Functor(this._session, 'processOutgoingMessage') + }; +}; + +Cell.prototype.pending = function(direction) { + var functor = this._functors[direction]; + if (!functor._stopped) functor.pending += 1; +}; + +Cell.prototype.incoming = function(error, message, callback, context) { + this._exec('incoming', error, message, callback, context); +}; + +Cell.prototype.outgoing = function(error, message, callback, context) { + this._exec('outgoing', error, message, callback, context); +}; + +Cell.prototype.close = function() { + this._closed = this._closed || new Pledge(); + this._doClose(); + return this._closed; +}; + +Cell.prototype._exec = function(direction, error, message, callback, context) { + this._functors[direction].call(error, message, function(err, msg) { + if (err) err.message = this._ext.name + ': ' + err.message; + callback.call(context, err, msg); + this._doClose(); + }, this); +}; + +Cell.prototype._doClose = function() { + var fin = this._functors.incoming, + fout = this._functors.outgoing; + + if (!this._closed || fin.pending + fout.pending !== 0) return; + if (this._session) this._session.close(); + this._session = null; + this._closed.done(); +}; + +module.exports = Cell; diff --git a/node_modules/websocket-extensions/lib/pipeline/functor.js b/node_modules/websocket-extensions/lib/pipeline/functor.js new file mode 100644 index 0000000..fadb49a --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/functor.js @@ -0,0 +1,72 @@ +'use strict'; + +var RingBuffer = require('./ring_buffer'); + +var Functor = function(session, method) { + this._session = session; + this._method = method; + this._queue = new RingBuffer(Functor.QUEUE_SIZE); + this._stopped = false; + this.pending = 0; +}; + +Functor.QUEUE_SIZE = 8; + +Functor.prototype.call = function(error, message, callback, context) { + if (this._stopped) return; + + var record = { error: error, message: message, callback: callback, context: context, done: false }, + called = false, + self = this; + + this._queue.push(record); + + if (record.error) { + record.done = true; + this._stop(); + return this._flushQueue(); + } + + var handler = function(err, msg) { + if (!(called ^ (called = true))) return; + + if (err) { + self._stop(); + record.error = err; + record.message = null; + } else { + record.message = msg; + } + + record.done = true; + self._flushQueue(); + }; + + try { + this._session[this._method](message, handler); + } catch (err) { + handler(err); + } +}; + +Functor.prototype._stop = function() { + this.pending = this._queue.length; + this._stopped = true; +}; + +Functor.prototype._flushQueue = function() { + var queue = this._queue, record; + + while (queue.length > 0 && queue.peek().done) { + record = queue.shift(); + if (record.error) { + this.pending = 0; + queue.clear(); + } else { + this.pending -= 1; + } + record.callback.call(record.context, record.error, record.message); + } +}; + +module.exports = Functor; diff --git a/node_modules/websocket-extensions/lib/pipeline/index.js b/node_modules/websocket-extensions/lib/pipeline/index.js new file mode 100644 index 0000000..930bbc8 --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/index.js @@ -0,0 +1,47 @@ +'use strict'; + +var Cell = require('./cell'), + Pledge = require('./pledge'); + +var Pipeline = function(sessions) { + this._cells = sessions.map(function(session) { return new Cell(session) }); + this._stopped = { incoming: false, outgoing: false }; +}; + +Pipeline.prototype.processIncomingMessage = function(message, callback, context) { + if (this._stopped.incoming) return; + this._loop('incoming', this._cells.length - 1, -1, -1, message, callback, context); +}; + +Pipeline.prototype.processOutgoingMessage = function(message, callback, context) { + if (this._stopped.outgoing) return; + this._loop('outgoing', 0, this._cells.length, 1, message, callback, context); +}; + +Pipeline.prototype.close = function(callback, context) { + this._stopped = { incoming: true, outgoing: true }; + + var closed = this._cells.map(function(a) { return a.close() }); + if (callback) + Pledge.all(closed).then(function() { callback.call(context) }); +}; + +Pipeline.prototype._loop = function(direction, start, end, step, message, callback, context) { + var cells = this._cells, + n = cells.length, + self = this; + + while (n--) cells[n].pending(direction); + + var pipe = function(index, error, msg) { + if (index === end) return callback.call(context, error, msg); + + cells[index][direction](error, msg, function(err, m) { + if (err) self._stopped[direction] = true; + pipe(index + step, err, m); + }); + }; + pipe(start, null, message); +}; + +module.exports = Pipeline; diff --git a/node_modules/websocket-extensions/lib/pipeline/pledge.js b/node_modules/websocket-extensions/lib/pipeline/pledge.js new file mode 100644 index 0000000..8a1f45d --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/pledge.js @@ -0,0 +1,37 @@ +'use strict'; + +var RingBuffer = require('./ring_buffer'); + +var Pledge = function() { + this._complete = false; + this._callbacks = new RingBuffer(Pledge.QUEUE_SIZE); +}; + +Pledge.QUEUE_SIZE = 4; + +Pledge.all = function(list) { + var pledge = new Pledge(), + pending = list.length, + n = pending; + + if (pending === 0) pledge.done(); + + while (n--) list[n].then(function() { + pending -= 1; + if (pending === 0) pledge.done(); + }); + return pledge; +}; + +Pledge.prototype.then = function(callback) { + if (this._complete) callback(); + else this._callbacks.push(callback); +}; + +Pledge.prototype.done = function() { + this._complete = true; + var callbacks = this._callbacks, callback; + while (callback = callbacks.shift()) callback(); +}; + +module.exports = Pledge; diff --git a/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js b/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js new file mode 100644 index 0000000..676ff94 --- /dev/null +++ b/node_modules/websocket-extensions/lib/pipeline/ring_buffer.js @@ -0,0 +1,66 @@ +'use strict'; + +var RingBuffer = function(bufferSize) { + this._bufferSize = bufferSize; + this.clear(); +}; + +RingBuffer.prototype.clear = function() { + this._buffer = new Array(this._bufferSize); + this._ringOffset = 0; + this._ringSize = this._bufferSize; + this._head = 0; + this._tail = 0; + this.length = 0; +}; + +RingBuffer.prototype.push = function(value) { + var expandBuffer = false, + expandRing = false; + + if (this._ringSize < this._bufferSize) { + expandBuffer = (this._tail === 0); + } else if (this._ringOffset === this._ringSize) { + expandBuffer = true; + expandRing = (this._tail === 0); + } + + if (expandBuffer) { + this._tail = this._bufferSize; + this._buffer = this._buffer.concat(new Array(this._bufferSize)); + this._bufferSize = this._buffer.length; + + if (expandRing) + this._ringSize = this._bufferSize; + } + + this._buffer[this._tail] = value; + this.length += 1; + if (this._tail < this._ringSize) this._ringOffset += 1; + this._tail = (this._tail + 1) % this._bufferSize; +}; + +RingBuffer.prototype.peek = function() { + if (this.length === 0) return void 0; + return this._buffer[this._head]; +}; + +RingBuffer.prototype.shift = function() { + if (this.length === 0) return void 0; + + var value = this._buffer[this._head]; + this._buffer[this._head] = void 0; + this.length -= 1; + this._ringOffset -= 1; + + if (this._ringOffset === 0 && this.length > 0) { + this._head = this._ringSize; + this._ringOffset = this.length; + this._ringSize = this._bufferSize; + } else { + this._head = (this._head + 1) % this._ringSize; + } + return value; +}; + +module.exports = RingBuffer; diff --git a/node_modules/websocket-extensions/lib/websocket_extensions.js b/node_modules/websocket-extensions/lib/websocket_extensions.js new file mode 100644 index 0000000..48adad8 --- /dev/null +++ b/node_modules/websocket-extensions/lib/websocket_extensions.js @@ -0,0 +1,162 @@ +'use strict'; + +var Parser = require('./parser'), + Pipeline = require('./pipeline'); + +var Extensions = function() { + this._rsv1 = this._rsv2 = this._rsv3 = null; + + this._byName = {}; + this._inOrder = []; + this._sessions = []; + this._index = {}; +}; + +Extensions.MESSAGE_OPCODES = [1, 2]; + +var instance = { + add: function(ext) { + if (typeof ext.name !== 'string') throw new TypeError('extension.name must be a string'); + if (ext.type !== 'permessage') throw new TypeError('extension.type must be "permessage"'); + + if (typeof ext.rsv1 !== 'boolean') throw new TypeError('extension.rsv1 must be true or false'); + if (typeof ext.rsv2 !== 'boolean') throw new TypeError('extension.rsv2 must be true or false'); + if (typeof ext.rsv3 !== 'boolean') throw new TypeError('extension.rsv3 must be true or false'); + + if (this._byName.hasOwnProperty(ext.name)) + throw new TypeError('An extension with name "' + ext.name + '" is already registered'); + + this._byName[ext.name] = ext; + this._inOrder.push(ext); + }, + + generateOffer: function() { + var sessions = [], + offer = [], + index = {}; + + this._inOrder.forEach(function(ext) { + var session = ext.createClientSession(); + if (!session) return; + + var record = [ext, session]; + sessions.push(record); + index[ext.name] = record; + + var offers = session.generateOffer(); + offers = offers ? [].concat(offers) : []; + + offers.forEach(function(off) { + offer.push(Parser.serializeParams(ext.name, off)); + }, this); + }, this); + + this._sessions = sessions; + this._index = index; + + return offer.length > 0 ? offer.join(', ') : null; + }, + + activate: function(header) { + var responses = Parser.parseHeader(header), + sessions = []; + + responses.eachOffer(function(name, params) { + var record = this._index[name]; + + if (!record) + throw new Error('Server sent an extension response for unknown extension "' + name + '"'); + + var ext = record[0], + session = record[1], + reserved = this._reserved(ext); + + if (reserved) + throw new Error('Server sent two extension responses that use the RSV' + + reserved[0] + ' bit: "' + + reserved[1] + '" and "' + ext.name + '"'); + + if (session.activate(params) !== true) + throw new Error('Server sent unacceptable extension parameters: ' + + Parser.serializeParams(name, params)); + + this._reserve(ext); + sessions.push(record); + }, this); + + this._sessions = sessions; + this._pipeline = new Pipeline(sessions); + }, + + generateResponse: function(header) { + var sessions = [], + response = [], + offers = Parser.parseHeader(header); + + this._inOrder.forEach(function(ext) { + var offer = offers.byName(ext.name); + if (offer.length === 0 || this._reserved(ext)) return; + + var session = ext.createServerSession(offer); + if (!session) return; + + this._reserve(ext); + sessions.push([ext, session]); + response.push(Parser.serializeParams(ext.name, session.generateResponse())); + }, this); + + this._sessions = sessions; + this._pipeline = new Pipeline(sessions); + + return response.length > 0 ? response.join(', ') : null; + }, + + validFrameRsv: function(frame) { + var allowed = { rsv1: false, rsv2: false, rsv3: false }, + ext; + + if (Extensions.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) { + for (var i = 0, n = this._sessions.length; i < n; i++) { + ext = this._sessions[i][0]; + allowed.rsv1 = allowed.rsv1 || ext.rsv1; + allowed.rsv2 = allowed.rsv2 || ext.rsv2; + allowed.rsv3 = allowed.rsv3 || ext.rsv3; + } + } + + return (allowed.rsv1 || !frame.rsv1) && + (allowed.rsv2 || !frame.rsv2) && + (allowed.rsv3 || !frame.rsv3); + }, + + processIncomingMessage: function(message, callback, context) { + this._pipeline.processIncomingMessage(message, callback, context); + }, + + processOutgoingMessage: function(message, callback, context) { + this._pipeline.processOutgoingMessage(message, callback, context); + }, + + close: function(callback, context) { + if (!this._pipeline) return callback.call(context); + this._pipeline.close(callback, context); + }, + + _reserve: function(ext) { + this._rsv1 = this._rsv1 || (ext.rsv1 && ext.name); + this._rsv2 = this._rsv2 || (ext.rsv2 && ext.name); + this._rsv3 = this._rsv3 || (ext.rsv3 && ext.name); + }, + + _reserved: function(ext) { + if (this._rsv1 && ext.rsv1) return [1, this._rsv1]; + if (this._rsv2 && ext.rsv2) return [2, this._rsv2]; + if (this._rsv3 && ext.rsv3) return [3, this._rsv3]; + return false; + } +}; + +for (var key in instance) + Extensions.prototype[key] = instance[key]; + +module.exports = Extensions; diff --git a/node_modules/websocket-extensions/package.json b/node_modules/websocket-extensions/package.json new file mode 100644 index 0000000..f6ec4c1 --- /dev/null +++ b/node_modules/websocket-extensions/package.json @@ -0,0 +1,63 @@ +{ + "_args": [ + [ + "websocket-extensions@0.1.4", + "/home/other/discord_bot" + ] + ], + "_from": "websocket-extensions@0.1.4", + "_id": "websocket-extensions@0.1.4", + "_inBundle": false, + "_integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "_location": "/websocket-extensions", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "websocket-extensions@0.1.4", + "name": "websocket-extensions", + "escapedName": "websocket-extensions", + "rawSpec": "0.1.4", + "saveSpec": null, + "fetchSpec": "0.1.4" + }, + "_requiredBy": [ + "/websocket-driver" + ], + "_resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "_spec": "0.1.4", + "_where": "/home/other/discord_bot", + "author": { + "name": "James Coglan", + "email": "jcoglan@gmail.com", + "url": "http://jcoglan.com/" + }, + "bugs": { + "url": "http://github.com/faye/websocket-extensions-node/issues" + }, + "description": "Generic extension manager for WebSocket connections", + "devDependencies": { + "jstest": "*" + }, + "engines": { + "node": ">=0.8.0" + }, + "files": [ + "lib" + ], + "homepage": "http://github.com/faye/websocket-extensions-node", + "keywords": [ + "websocket" + ], + "license": "Apache-2.0", + "main": "./lib/websocket_extensions", + "name": "websocket-extensions", + "repository": { + "type": "git", + "url": "git://github.com/faye/websocket-extensions-node.git" + }, + "scripts": { + "test": "jstest spec/runner.js" + }, + "version": "0.1.4" +} diff --git a/node_modules/whatwg-url/LICENSE.txt b/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 0000000..54dfac3 --- /dev/null +++ b/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +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/whatwg-url/README.md b/node_modules/whatwg-url/README.md new file mode 100644 index 0000000..4347a7f --- /dev/null +++ b/node_modules/whatwg-url/README.md @@ -0,0 +1,67 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). + +## Current Status + +whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). + +## API + +### The `URL` Constructor + +The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) +- [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. diff --git a/node_modules/whatwg-url/lib/URL-impl.js b/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 0000000..dc7452c --- /dev/null +++ b/node_modules/whatwg-url/lib/URL-impl.js @@ -0,0 +1,200 @@ +"use strict"; +const usm = require("./url-state-machine"); + +exports.implementation = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === "failure") { + throw new TypeError("Invalid base URL"); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + + // TODO: query stuff + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return "?" + this._url.query; + } + + set search(v) { + // TODO: query stuff + + const url = this._url; + + if (v === "") { + url.query = null; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; diff --git a/node_modules/whatwg-url/lib/URL.js b/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 0000000..78c7207 --- /dev/null +++ b/node_modules/whatwg-url/lib/URL.js @@ -0,0 +1,196 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); +const Impl = require(".//URL-impl.js"); + +const impl = utils.implSymbol; + +function URL(url) { + if (!this || this[impl] || !(this instanceof URL)) { + throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); + } + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + args[0] = conversions["USVString"](args[0]); + if (args[1] !== undefined) { + args[1] = conversions["USVString"](args[1]); + } + + module.exports.setup(this, args); +} + +URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + const args = []; + for (let i = 0; i < arguments.length && i < 0; ++i) { + args[i] = arguments[i]; + } + return this[impl].toJSON.apply(this[impl], args); +}; +Object.defineProperty(URL.prototype, "href", { + get() { + return this[impl].href; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].href = V; + }, + enumerable: true, + configurable: true +}); + +URL.prototype.toString = function () { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this.href; +}; + +Object.defineProperty(URL.prototype, "origin", { + get() { + return this[impl].origin; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "protocol", { + get() { + return this[impl].protocol; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].protocol = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "username", { + get() { + return this[impl].username; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].username = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "password", { + get() { + return this[impl].password; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].password = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "host", { + get() { + return this[impl].host; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].host = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hostname", { + get() { + return this[impl].hostname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hostname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "port", { + get() { + return this[impl].port; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].port = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "pathname", { + get() { + return this[impl].pathname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].pathname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "search", { + get() { + return this[impl].search; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].search = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hash", { + get() { + return this[impl].hash; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hash = V; + }, + enumerable: true, + configurable: true +}); + + +module.exports = { + is(obj) { + return !!obj && obj[impl] instanceof Impl.implementation; + }, + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + this.setup(obj, constructorArgs, privateData); + return obj; + }, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + privateData.wrapper = obj; + + obj[impl] = new Impl.implementation(constructorArgs, privateData); + obj[impl][utils.wrapperSymbol] = obj; + }, + interface: URL, + expose: { + Window: { URL: URL }, + Worker: { URL: URL } + } +}; + diff --git a/node_modules/whatwg-url/lib/public-api.js b/node_modules/whatwg-url/lib/public-api.js new file mode 100644 index 0000000..932dcad --- /dev/null +++ b/node_modules/whatwg-url/lib/public-api.js @@ -0,0 +1,11 @@ +"use strict"; + +exports.URL = require("./URL").interface; +exports.serializeURL = require("./url-state-machine").serializeURL; +exports.serializeURLOrigin = require("./url-state-machine").serializeURLOrigin; +exports.basicURLParse = require("./url-state-machine").basicURLParse; +exports.setTheUsername = require("./url-state-machine").setTheUsername; +exports.setThePassword = require("./url-state-machine").setThePassword; +exports.serializeHost = require("./url-state-machine").serializeHost; +exports.serializeInteger = require("./url-state-machine").serializeInteger; +exports.parseURL = require("./url-state-machine").parseURL; diff --git a/node_modules/whatwg-url/lib/url-state-machine.js b/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 0000000..c25dbc2 --- /dev/null +++ b/node_modules/whatwg-url/lib/url-state-machine.js @@ -0,0 +1,1297 @@ +"use strict"; +const punycode = require("punycode"); +const tr46 = require("tr46"); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/node_modules/whatwg-url/lib/utils.js b/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 0000000..a562009 --- /dev/null +++ b/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,20 @@ +"use strict"; + +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; + +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); + +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; + +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; + diff --git a/node_modules/whatwg-url/package.json b/node_modules/whatwg-url/package.json new file mode 100644 index 0000000..3d0ccd0 --- /dev/null +++ b/node_modules/whatwg-url/package.json @@ -0,0 +1,67 @@ +{ + "_from": "whatwg-url@^5.0.0", + "_id": "whatwg-url@5.0.0", + "_inBundle": false, + "_integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "_location": "/whatwg-url", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "whatwg-url@^5.0.0", + "name": "whatwg-url", + "escapedName": "whatwg-url", + "rawSpec": "^5.0.0", + "saveSpec": null, + "fetchSpec": "^5.0.0" + }, + "_requiredBy": [ + "/node-fetch" + ], + "_resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "_shasum": "966454e8765462e37644d3626f6742ce8b70965d", + "_spec": "whatwg-url@^5.0.0", + "_where": "/home/other/discord_bot/node_modules/node-fetch", + "author": { + "name": "Sebastian Mayr", + "email": "github@smayr.name" + }, + "bugs": { + "url": "https://github.com/jsdom/whatwg-url/issues" + }, + "bundleDependencies": false, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + }, + "deprecated": false, + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "devDependencies": { + "eslint": "^2.6.0", + "istanbul": "~0.4.3", + "mocha": "^2.2.4", + "recast": "~0.10.29", + "request": "^2.55.0", + "webidl2js": "^3.0.2" + }, + "files": [ + "lib/" + ], + "homepage": "https://github.com/jsdom/whatwg-url#readme", + "license": "MIT", + "main": "lib/public-api.js", + "name": "whatwg-url", + "repository": { + "type": "git", + "url": "git+https://github.com/jsdom/whatwg-url.git" + }, + "scripts": { + "build": "node scripts/transform.js && node scripts/convert-idl.js", + "coverage": "istanbul cover node_modules/mocha/bin/_mocha", + "lint": "eslint .", + "prepublish": "npm run build", + "pretest": "node scripts/get-latest-platform-tests.js && npm run build", + "test": "mocha" + }, + "version": "5.0.0" +} diff --git a/node_modules/widest-line/index.d.ts b/node_modules/widest-line/index.d.ts new file mode 100644 index 0000000..845ceaa --- /dev/null +++ b/node_modules/widest-line/index.d.ts @@ -0,0 +1,21 @@ +declare const widestLine: { + /** + Get the visual width of the widest line in a string - the number of columns required to display it. + + @example + ``` + import widestLine = require('widest-line'); + + widestLine('古\n\u001B[1m@\u001B[22m'); + //=> 2 + ``` + */ + (input: string): number; + + // TODO: remove this in the next major version, refactor definition to: + // declare function widestLine(input: string): number; + // export = widestLine; + default: typeof widestLine; +}; + +export = widestLine; diff --git a/node_modules/widest-line/index.js b/node_modules/widest-line/index.js new file mode 100644 index 0000000..98f8ce4 --- /dev/null +++ b/node_modules/widest-line/index.js @@ -0,0 +1,16 @@ +'use strict'; +const stringWidth = require('string-width'); + +const widestLine = input => { + let max = 0; + + for (const line of input.split('\n')) { + max = Math.max(max, stringWidth(line)); + } + + return max; +}; + +module.exports = widestLine; +// TODO: remove this in the next major version +module.exports.default = widestLine; diff --git a/node_modules/widest-line/license b/node_modules/widest-line/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/widest-line/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/widest-line/package.json b/node_modules/widest-line/package.json new file mode 100644 index 0000000..7d61137 --- /dev/null +++ b/node_modules/widest-line/package.json @@ -0,0 +1,90 @@ +{ + "_args": [ + [ + "widest-line@3.1.0", + "/home/other/discord_bot" + ] + ], + "_from": "widest-line@3.1.0", + "_id": "widest-line@3.1.0", + "_inBundle": false, + "_integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==", + "_location": "/widest-line", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "widest-line@3.1.0", + "name": "widest-line", + "escapedName": "widest-line", + "rawSpec": "3.1.0", + "saveSpec": null, + "fetchSpec": "3.1.0" + }, + "_requiredBy": [ + "/boxen", + "/nodemon/boxen" + ], + "_resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz", + "_spec": "3.1.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/widest-line/issues" + }, + "dependencies": { + "string-width": "^4.0.0" + }, + "description": "Get the visual width of the widest line in a string - the number of columns required to display it", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/widest-line#readme", + "keywords": [ + "string", + "character", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "license": "MIT", + "name": "widest-line", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/widest-line.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "3.1.0" +} diff --git a/node_modules/widest-line/readme.md b/node_modules/widest-line/readme.md new file mode 100644 index 0000000..20e02d5 --- /dev/null +++ b/node_modules/widest-line/readme.md @@ -0,0 +1,34 @@ +# widest-line [![Build Status](https://travis-ci.org/sindresorhus/widest-line.svg?branch=master)](https://travis-ci.org/sindresorhus/widest-line) + +> Get the visual width of the widest line in a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to know the maximum width a string will take up in the terminal. + + +## Install + +``` +$ npm install widest-line +``` + + +## Usage + +```js +const widestLine = require('widest-line'); + +widestLine('古\n\u001B[1m@\u001B[22m'); +//=> 2 +``` + + +## Related + +- [string-width](https://github.com/sindresorhus/string-width) - Get the visual width of a string + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/wrap-ansi/index.js b/node_modules/wrap-ansi/index.js new file mode 100755 index 0000000..d502255 --- /dev/null +++ b/node_modules/wrap-ansi/index.js @@ -0,0 +1,216 @@ +'use strict'; +const stringWidth = require('string-width'); +const stripAnsi = require('strip-ansi'); +const ansiStyles = require('ansi-styles'); + +const ESCAPES = new Set([ + '\u001B', + '\u009B' +]); + +const END_CODE = 39; + +const ANSI_ESCAPE_BELL = '\u0007'; +const ANSI_CSI = '['; +const ANSI_OSC = ']'; +const ANSI_SGR_TERMINATOR = 'm'; +const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; + +const wrapAnsi = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; +const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, columns) => { + const characters = [...word]; + + let isInsideEscape = false; + let isInsideLinkEscape = false; + let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES.has(character)) { + isInsideEscape = true; + isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); + } + + if (isInsideEscape) { + if (isInsideLinkEscape) { + if (character === ANSI_ESCAPE_BELL) { + isInsideEscape = false; + isInsideLinkEscape = false; + } + } else if (character === ANSI_SGR_TERMINATOR) { + isInsideEscape = false; + } + + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = string => { + const words = string.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return string; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more than columns characters +// +// 'soft' allows long words to expand past the column length +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let returnValue = ''; + let escapeCode; + let escapeUrl; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimStart(); + } + + let rowLength = stringWidth(rows[rows.length - 1]); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(stringVisibleTrimSpacesRight); + } + + const pre = [...rows.join('\n')]; + + for (const [index, character] of pre.entries()) { + returnValue += character; + + if (ESCAPES.has(character)) { + const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; + if (groups.code !== undefined) { + const code = Number.parseFloat(groups.code); + escapeCode = code === END_CODE ? undefined : code; + } else if (groups.uri !== undefined) { + escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; + } + } + + const code = ansiStyles.codes.get(Number(escapeCode)); + + if (pre[index + 1] === '\n') { + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(''); + } + + if (escapeCode && code) { + returnValue += wrapAnsi(code); + } + } else if (character === '\n') { + if (escapeCode && code) { + returnValue += wrapAnsi(escapeCode); + } + + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(escapeUrl); + } + } + } + + return returnValue; +}; + +// For each newline, invoke the method separately +module.exports = (string, columns, options) => { + return String(string) + .normalize() + .replace(/\r\n/g, '\n') + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +}; diff --git a/node_modules/wrap-ansi/license b/node_modules/wrap-ansi/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/wrap-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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/wrap-ansi/package.json b/node_modules/wrap-ansi/package.json new file mode 100644 index 0000000..c19d44a --- /dev/null +++ b/node_modules/wrap-ansi/package.json @@ -0,0 +1,97 @@ +{ + "_args": [ + [ + "wrap-ansi@7.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "wrap-ansi@7.0.0", + "_id": "wrap-ansi@7.0.0", + "_inBundle": false, + "_integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "_location": "/wrap-ansi", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "wrap-ansi@7.0.0", + "name": "wrap-ansi", + "escapedName": "wrap-ansi", + "rawSpec": "7.0.0", + "saveSpec": null, + "fetchSpec": "7.0.0" + }, + "_requiredBy": [ + "/boxen" + ], + "_resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "_spec": "7.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/chalk/wrap-ansi/issues" + }, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "description": "Wordwrap a string with ANSI escape codes", + "devDependencies": { + "ava": "^2.1.0", + "chalk": "^4.0.0", + "coveralls": "^3.0.3", + "has-ansi": "^4.0.0", + "nyc": "^15.0.1", + "xo": "^0.29.1" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js" + ], + "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", + "homepage": "https://github.com/chalk/wrap-ansi#readme", + "keywords": [ + "wrap", + "break", + "wordwrap", + "wordbreak", + "linewrap", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "name": "wrap-ansi", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/wrap-ansi.git" + }, + "scripts": { + "test": "xo && nyc ava" + }, + "version": "7.0.0" +} diff --git a/node_modules/wrap-ansi/readme.md b/node_modules/wrap-ansi/readme.md new file mode 100644 index 0000000..68779ba --- /dev/null +++ b/node_modules/wrap-ansi/readme.md @@ -0,0 +1,91 @@ +# wrap-ansi [![Build Status](https://travis-ci.com/chalk/wrap-ansi.svg?branch=master)](https://travis-ci.com/chalk/wrap-ansi) [![Coverage Status](https://coveralls.io/repos/github/chalk/wrap-ansi/badge.svg?branch=master)](https://coveralls.io/github/chalk/wrap-ansi?branch=master) + +> Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) + +## Install + +``` +$ npm install wrap-ansi +``` + +## Usage + +```js +const chalk = require('chalk'); +const wrapAnsi = require('wrap-ansi'); + +const input = 'The quick brown ' + chalk.red('fox jumped over ') + + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); + +console.log(wrapAnsi(input, 20)); +``` + + + +## API + +### wrapAnsi(string, columns, options?) + +Wrap words to the specified column width. + +#### string + +Type: `string` + +String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. + +#### columns + +Type: `number` + +Number of columns to wrap the text to. + +#### options + +Type: `object` + +##### hard + +Type: `boolean`\ +Default: `false` + +By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. + +##### wordWrap + +Type: `boolean`\ +Default: `true` + +By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. + +##### trim + +Type: `boolean`\ +Default: `true` + +Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. + +## Related + +- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes +- [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right +- [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures. + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) +- [Benjamin Coe](https://github.com/bcoe) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/wrappy/LICENSE b/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/wrappy/README.md b/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/wrappy/package.json b/node_modules/wrappy/package.json new file mode 100644 index 0000000..e121224 --- /dev/null +++ b/node_modules/wrappy/package.json @@ -0,0 +1,61 @@ +{ + "_args": [ + [ + "wrappy@1.0.2", + "/home/other/discord_bot" + ] + ], + "_from": "wrappy@1.0.2", + "_id": "wrappy@1.0.2", + "_inBundle": false, + "_integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "_location": "/wrappy", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "wrappy@1.0.2", + "name": "wrappy", + "escapedName": "wrappy", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/once" + ], + "_resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "_spec": "1.0.2", + "_where": "/home/other/discord_bot", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "dependencies": {}, + "description": "Callback wrapping utility", + "devDependencies": { + "tap": "^2.3.1" + }, + "directories": { + "test": "test" + }, + "files": [ + "wrappy.js" + ], + "homepage": "https://github.com/npm/wrappy", + "license": "ISC", + "main": "wrappy.js", + "name": "wrappy", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/wrappy.git" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "version": "1.0.2" +} diff --git a/node_modules/wrappy/wrappy.js b/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/node_modules/write-file-atomic/CHANGELOG.md b/node_modules/write-file-atomic/CHANGELOG.md new file mode 100644 index 0000000..d1a6c1b --- /dev/null +++ b/node_modules/write-file-atomic/CHANGELOG.md @@ -0,0 +1,32 @@ +# 3.0.0 + +* Implement options.tmpfileCreated callback. +* Drop Node.js 6, modernize code, return Promise from async function. +* Support write TypedArray's like in node fs.writeFile. +* Remove graceful-fs dependency. + +# 2.4.3 + +* Ignore errors raised by `fs.closeSync` when cleaning up after a write + error. + +# 2.4.2 + +* A pair of patches to fix some fd leaks. We would leak fds with sync use + when errors occured and with async use any time fsync was not in use. (#34) + +# 2.4.1 + +* Fix a bug where `signal-exit` instances would be leaked. This was fixed when addressing #35. + +# 2.4.0 + +## Features + +* Allow chown and mode options to be set to false to disable the defaulting behavior. (#20) +* Support passing encoding strings in options slot for compat with Node.js API. (#31) +* Add support for running inside of worker threads (#37) + +## Fixes + +* Remove unneeded call when returning success (#36) diff --git a/node_modules/write-file-atomic/LICENSE b/node_modules/write-file-atomic/LICENSE new file mode 100644 index 0000000..95e65a7 --- /dev/null +++ b/node_modules/write-file-atomic/LICENSE @@ -0,0 +1,6 @@ +Copyright (c) 2015, Rebecca Turner + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/write-file-atomic/README.md b/node_modules/write-file-atomic/README.md new file mode 100644 index 0000000..caea799 --- /dev/null +++ b/node_modules/write-file-atomic/README.md @@ -0,0 +1,72 @@ +write-file-atomic +----------------- + +This is an extension for node's `fs.writeFile` that makes its operation +atomic and allows you set ownership (uid/gid of the file). + +### var writeFileAtomic = require('write-file-atomic')
writeFileAtomic(filename, data, [options], [callback]) + +* filename **String** +* data **String** | **Buffer** +* options **Object** | **String** + * chown **Object** default, uid & gid of existing file, if any + * uid **Number** + * gid **Number** + * encoding **String** | **Null** default = 'utf8' + * fsync **Boolean** default = true + * mode **Number** default, from existing file, if any + * tmpfileCreated **Function** called when the tmpfile is created +* callback **Function** + +Atomically and asynchronously writes data to a file, replacing the file if it already +exists. data can be a string or a buffer. + +The file is initially named `filename + "." + murmurhex(__filename, process.pid, ++invocations)`. +Note that `require('worker_threads').threadId` is used in addition to `process.pid` if running inside of a worker thread. +If writeFile completes successfully then, if passed the **chown** option it will change +the ownership of the file. Finally it renames the file back to the filename you specified. If +it encounters errors at any of these steps it will attempt to unlink the temporary file and then +pass the error back to the caller. +If multiple writes are concurrently issued to the same file, the write operations are put into a queue and serialized in the order they were called, using Promises. Writes to different files are still executed in parallel. + +If provided, the **chown** option requires both **uid** and **gid** properties or else +you'll get an error. If **chown** is not specified it will default to using +the owner of the previous file. To prevent chown from being ran you can +also pass `false`, in which case the file will be created with the current user's credentials. + +If **mode** is not specified, it will default to using the permissions from +an existing file, if any. Expicitly setting this to `false` remove this default, resulting +in a file created with the system default permissions. + +If options is a String, it's assumed to be the **encoding** option. The **encoding** option is ignored if **data** is a buffer. It defaults to 'utf8'. + +If the **fsync** option is **false**, writeFile will skip the final fsync call. + +If the **tmpfileCreated** option is specified it will be called with the name of the tmpfile when created. + +Example: + +```javascript +writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}, function (err) { + if (err) throw err; + console.log('It\'s saved!'); +}); +``` + +This function also supports async/await: + +```javascript +(async () => { + try { + await writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}); + console.log('It\'s saved!'); + } catch (err) { + console.error(err); + process.exit(1); + } +})(); +``` + +### var writeFileAtomicSync = require('write-file-atomic').sync
writeFileAtomicSync(filename, data, [options]) + +The synchronous version of **writeFileAtomic**. diff --git a/node_modules/write-file-atomic/index.js b/node_modules/write-file-atomic/index.js new file mode 100644 index 0000000..df5b72a --- /dev/null +++ b/node_modules/write-file-atomic/index.js @@ -0,0 +1,259 @@ +'use strict' +module.exports = writeFile +module.exports.sync = writeFileSync +module.exports._getTmpname = getTmpname // for testing +module.exports._cleanupOnExit = cleanupOnExit + +const fs = require('fs') +const MurmurHash3 = require('imurmurhash') +const onExit = require('signal-exit') +const path = require('path') +const isTypedArray = require('is-typedarray') +const typedArrayToBuffer = require('typedarray-to-buffer') +const { promisify } = require('util') +const activeFiles = {} + +// if we run inside of a worker_thread, `process.pid` is not unique +/* istanbul ignore next */ +const threadId = (function getId () { + try { + const workerThreads = require('worker_threads') + + /// if we are in main thread, this is set to `0` + return workerThreads.threadId + } catch (e) { + // worker_threads are not available, fallback to 0 + return 0 + } +})() + +let invocations = 0 +function getTmpname (filename) { + return filename + '.' + + MurmurHash3(__filename) + .hash(String(process.pid)) + .hash(String(threadId)) + .hash(String(++invocations)) + .result() +} + +function cleanupOnExit (tmpfile) { + return () => { + try { + fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile) + } catch (_) {} + } +} + +function serializeActiveFile (absoluteName) { + return new Promise(resolve => { + // make a queue if it doesn't already exist + if (!activeFiles[absoluteName]) activeFiles[absoluteName] = [] + + activeFiles[absoluteName].push(resolve) // add this job to the queue + if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one + }) +} + +// https://github.com/isaacs/node-graceful-fs/blob/master/polyfills.js#L315-L342 +function isChownErrOk (err) { + if (err.code === 'ENOSYS') { + return true + } + + const nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (err.code === 'EINVAL' || err.code === 'EPERM') { + return true + } + } + + return false +} + +async function writeFileAsync (filename, data, options = {}) { + if (typeof options === 'string') { + options = { encoding: options } + } + + let fd + let tmpfile + /* istanbul ignore next -- The closure only gets called when onExit triggers */ + const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile)) + const absoluteName = path.resolve(filename) + + try { + await serializeActiveFile(absoluteName) + const truename = await promisify(fs.realpath)(filename).catch(() => filename) + tmpfile = getTmpname(truename) + + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + const stats = await promisify(fs.stat)(truename).catch(() => {}) + if (stats) { + if (options.mode == null) { + options.mode = stats.mode + } + + if (options.chown == null && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } + } + } + } + + fd = await promisify(fs.open)(tmpfile, 'w', options.mode) + if (options.tmpfileCreated) { + await options.tmpfileCreated(tmpfile) + } + if (isTypedArray(data)) { + data = typedArrayToBuffer(data) + } + if (Buffer.isBuffer(data)) { + await promisify(fs.write)(fd, data, 0, data.length, 0) + } else if (data != null) { + await promisify(fs.write)(fd, String(data), 0, String(options.encoding || 'utf8')) + } + + if (options.fsync !== false) { + await promisify(fs.fsync)(fd) + } + + await promisify(fs.close)(fd) + fd = null + + if (options.chown) { + await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch(err => { + if (!isChownErrOk(err)) { + throw err + } + }) + } + + if (options.mode) { + await promisify(fs.chmod)(tmpfile, options.mode).catch(err => { + if (!isChownErrOk(err)) { + throw err + } + }) + } + + await promisify(fs.rename)(tmpfile, truename) + } finally { + if (fd) { + await promisify(fs.close)(fd).catch( + /* istanbul ignore next */ + () => {} + ) + } + removeOnExitHandler() + await promisify(fs.unlink)(tmpfile).catch(() => {}) + activeFiles[absoluteName].shift() // remove the element added by serializeSameFile + if (activeFiles[absoluteName].length > 0) { + activeFiles[absoluteName][0]() // start next job if one is pending + } else delete activeFiles[absoluteName] + } +} + +function writeFile (filename, data, options, callback) { + if (options instanceof Function) { + callback = options + options = {} + } + + const promise = writeFileAsync(filename, data, options) + if (callback) { + promise.then(callback, callback) + } + + return promise +} + +function writeFileSync (filename, data, options) { + if (typeof options === 'string') options = { encoding: options } + else if (!options) options = {} + try { + filename = fs.realpathSync(filename) + } catch (ex) { + // it's ok, it'll happen on a not yet existing file + } + const tmpfile = getTmpname(filename) + + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + try { + const stats = fs.statSync(filename) + options = Object.assign({}, options) + if (!options.mode) { + options.mode = stats.mode + } + if (!options.chown && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } + } + } catch (ex) { + // ignore stat errors + } + } + + let fd + const cleanup = cleanupOnExit(tmpfile) + const removeOnExitHandler = onExit(cleanup) + + let threw = true + try { + fd = fs.openSync(tmpfile, 'w', options.mode || 0o666) + if (options.tmpfileCreated) { + options.tmpfileCreated(tmpfile) + } + if (isTypedArray(data)) { + data = typedArrayToBuffer(data) + } + if (Buffer.isBuffer(data)) { + fs.writeSync(fd, data, 0, data.length, 0) + } else if (data != null) { + fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) + } + if (options.fsync !== false) { + fs.fsyncSync(fd) + } + + fs.closeSync(fd) + fd = null + + if (options.chown) { + try { + fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) + } catch (err) { + if (!isChownErrOk(err)) { + throw err + } + } + } + + if (options.mode) { + try { + fs.chmodSync(tmpfile, options.mode) + } catch (err) { + if (!isChownErrOk(err)) { + throw err + } + } + } + + fs.renameSync(tmpfile, filename) + threw = false + } finally { + if (fd) { + try { + fs.closeSync(fd) + } catch (ex) { + // ignore close errors at this stage, error may have closed fd already. + } + } + removeOnExitHandler() + if (threw) { + cleanup() + } + } +} diff --git a/node_modules/write-file-atomic/package.json b/node_modules/write-file-atomic/package.json new file mode 100644 index 0000000..cd97d25 --- /dev/null +++ b/node_modules/write-file-atomic/package.json @@ -0,0 +1,80 @@ +{ + "_args": [ + [ + "write-file-atomic@3.0.3", + "/home/other/discord_bot" + ] + ], + "_from": "write-file-atomic@3.0.3", + "_id": "write-file-atomic@3.0.3", + "_inBundle": false, + "_integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "_location": "/write-file-atomic", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "write-file-atomic@3.0.3", + "name": "write-file-atomic", + "escapedName": "write-file-atomic", + "rawSpec": "3.0.3", + "saveSpec": null, + "fetchSpec": "3.0.3" + }, + "_requiredBy": [ + "/configstore" + ], + "_resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "_spec": "3.0.3", + "_where": "/home/other/discord_bot", + "author": { + "name": "Rebecca Turner", + "email": "me@re-becca.org", + "url": "http://re-becca.org" + }, + "bugs": { + "url": "https://github.com/npm/write-file-atomic/issues" + }, + "dependencies": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + }, + "description": "Write files in an atomic fashion w/configurable ownership", + "devDependencies": { + "mkdirp": "^0.5.1", + "require-inject": "^1.4.4", + "rimraf": "^2.6.3", + "standard": "^14.3.1", + "tap": "^14.10.6" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/npm/write-file-atomic", + "keywords": [ + "writeFile", + "atomic" + ], + "license": "ISC", + "main": "index.js", + "name": "write-file-atomic", + "repository": { + "type": "git", + "url": "git://github.com/npm/write-file-atomic.git" + }, + "scripts": { + "lint": "standard", + "postlint": "rimraf chowncopy good nochmod nochown nofsync nofsyncopt noopen norename \"norename nounlink\" nowrite", + "posttest": "npm run lint", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "preversion": "npm test", + "test": "tap" + }, + "tap": { + "100": true + }, + "version": "3.0.3" +} diff --git a/node_modules/ws/LICENSE b/node_modules/ws/LICENSE new file mode 100644 index 0000000..1da5b96 --- /dev/null +++ b/node_modules/ws/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and contributors + +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/ws/README.md b/node_modules/ws/README.md new file mode 100644 index 0000000..a550ca1 --- /dev/null +++ b/node_modules/ws/README.md @@ -0,0 +1,536 @@ +# ws: a Node.js WebSocket library + +[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) +[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) +[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and +server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a back end with the role of a client in the WebSocket +communication. Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +object. To make the same code work seamlessly on Node.js and the browser, you +can use one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +- [Protocol support](#protocol-support) +- [Installing](#installing) + - [Opt-in for performance](#opt-in-for-performance) +- [API docs](#api-docs) +- [WebSocket compression](#websocket-compression) +- [Usage examples](#usage-examples) + - [Sending and receiving text data](#sending-and-receiving-text-data) + - [Sending binary data](#sending-binary-data) + - [Simple server](#simple-server) + - [External HTTP/S server](#external-https-server) + - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) + - [Client authentication](#client-authentication) + - [Server broadcast](#server-broadcast) + - [Round-trip time](#round-trip-time) + - [Use the Node.js streams API](#use-the-nodejs-streams-api) + - [Other examples](#other-examples) +- [FAQ](#faq) + - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + - [How to connect via a proxy?](#how-to-connect-via-a-proxy) +- [Changelog](#changelog) +- [License](#license) + +## Protocol support + +- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +- **HyBi drafts 13-17** (Current default, alternatively option + `protocolVersion: 13`) + +## Installing + +``` +npm install ws +``` + +### Opt-in for performance + +There are 2 optional modules that can be installed along side with the ws +module. These modules are binary addons that improve the performance of certain +operations. Prebuilt binaries are available for the most popular platforms so +you don't necessarily need to have a C++ compiler installed on your machine. + +- `npm install --save-optional bufferutil`: Allows to efficiently perform + operations such as masking and unmasking the data payload of the WebSocket + frames. +- `npm install --save-optional utf-8-validate`: Allows to efficiently check if a + message contains valid UTF-8. + +To not even try to require and use these modules, use the +[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) and +[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment +variables. These might be useful to enhance security in systems where a user can +put a package in the package search path of an application of another user, due +to how the Node.js resolver algorithm works. + +The `utf-8-validate` module is not needed and is not required, even if it is +already installed, regardless of the value of the `WS_NO_UTF_8_VALIDATE` +environment variable, if [`buffer.isUtf8()`][] is available. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and +utility functions. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which enables +the client and server to negotiate a compression algorithm and its parameters, +and then selectively apply it to the data payloads of each WebSocket message. + +The extension is disabled by default on the server and enabled by default on the +client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to [catastrophic +memory fragmentation][node-zlib-bug] and slow performance. If you intend to use +permessage-deflate in production, it is worthwhile to set up a test +representative of your workload and ensure Node.js/zlib will handle it with +acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { + // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024 // Size (in bytes) below which messages + // should not be compressed if context takeover is disabled. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client set the +`perMessageDeflate` option to `false`. + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function message(data) { + console.log('received: %s', data); +}); +``` + +### Sending binary data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Simple server + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); +``` + +### External HTTP/S server + +```js +import { createServer } from 'https'; +import { readFileSync } from 'fs'; +import { WebSocketServer } from 'ws'; + +const server = createServer({ + cert: readFileSync('/path/to/cert.pem'), + key: readFileSync('/path/to/key.pem') +}); +const wss = new WebSocketServer({ server }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); + +server.listen(8080); +``` + +### Multiple servers sharing a single HTTP/S server + +```js +import { createServer } from 'http'; +import { parse } from 'url'; +import { WebSocketServer } from 'ws'; + +const server = createServer(); +const wss1 = new WebSocketServer({ noServer: true }); +const wss2 = new WebSocketServer({ noServer: true }); + +wss1.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +wss2.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +server.on('upgrade', function upgrade(request, socket, head) { + const { pathname } = parse(request.url); + + if (pathname === '/foo') { + wss1.handleUpgrade(request, socket, head, function done(ws) { + wss1.emit('connection', ws, request); + }); + } else if (pathname === '/bar') { + wss2.handleUpgrade(request, socket, head, function done(ws) { + wss2.emit('connection', ws, request); + }); + } else { + socket.destroy(); + } +}); + +server.listen(8080); +``` + +### Client authentication + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +function onSocketError(err) { + console.error(err); +} + +const server = createServer(); +const wss = new WebSocketServer({ noServer: true }); + +wss.on('connection', function connection(ws, request, client) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log(`Received message ${data} from user ${client}`); + }); +}); + +server.on('upgrade', function upgrade(request, socket, head) { + socket.on('error', onSocketError); + + // This function is not defined on purpose. Implement it with your own logic. + authenticate(request, function next(err, client) { + if (err || !client) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + socket.removeListener('error', onSocketError); + + wss.handleUpgrade(request, socket, head, function done(ws) { + wss.emit('connection', ws, request, client); + }); + }); +}); + +server.listen(8080); +``` + +Also see the provided [example][session-parse-example] using `express-session`. + +### Server broadcast + +A client WebSocket broadcasting to all connected WebSocket clients, including +itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +A client WebSocket broadcasting to every other connected WebSocket clients, +excluding itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +### Round-trip time + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +ws.on('error', console.error); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function message(data) { + console.log(`Round-trip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Use the Node.js streams API + +```js +import WebSocket, { createWebSocketStream } from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); + +duplex.on('error', console.error); + +duplex.pipe(process.stdout); +process.stdin.pipe(duplex); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.socket.remoteAddress; + + ws.on('error', console.error); +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); + + ws.on('error', console.error); +}); +``` + +### How to detect and close broken connections? + +Sometimes the link between the server and the client can be interrupted in a way +that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +import { WebSocketServer } from 'ws'; + +function heartbeat() { + this.isAlive = true; +} + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('error', console.error); + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(); + }); +}, 30000); + +wss.on('close', function close() { + clearInterval(interval); +}); +``` + +Pong messages are automatically sent in response to ping messages as required by +the spec. + +Just like the server example above your clients might as well lose connection +without knowing it. You might want to add a ping listener on your clients to +prevent that. A simple implementation would be: + +```js +import WebSocket from 'ws'; + +function heartbeat() { + clearTimeout(this.pingTimeout); + + // Use `WebSocket#terminate()`, which immediately destroys the connection, + // instead of `WebSocket#close()`, which waits for the close timer. + // Delay should be equal to the interval at which your server + // sends out pings plus a conservative assumption of the latency. + this.pingTimeout = setTimeout(() => { + this.terminate(); + }, 30000 + 1000); +} + +const client = new WebSocket('wss://websocket-echo.com/'); + +client.on('error', console.error); +client.on('open', heartbeat); +client.on('ping', heartbeat); +client.on('close', function clear() { + clearTimeout(this.pingTimeout); +}); +``` + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input +[changelog]: https://github.com/websockets/ws/releases +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: + https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[session-parse-example]: ./examples/express-session-parse +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback diff --git a/node_modules/ws/browser.js b/node_modules/ws/browser.js new file mode 100644 index 0000000..ca4f628 --- /dev/null +++ b/node_modules/ws/browser.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + throw new Error( + 'ws does not work in the browser. Browser clients must use the native ' + + 'WebSocket object' + ); +}; diff --git a/node_modules/ws/index.js b/node_modules/ws/index.js new file mode 100644 index 0000000..41edb3b --- /dev/null +++ b/node_modules/ws/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const WebSocket = require('./lib/websocket'); + +WebSocket.createWebSocketStream = require('./lib/stream'); +WebSocket.Server = require('./lib/websocket-server'); +WebSocket.Receiver = require('./lib/receiver'); +WebSocket.Sender = require('./lib/sender'); + +WebSocket.WebSocket = WebSocket; +WebSocket.WebSocketServer = WebSocket.Server; + +module.exports = WebSocket; diff --git a/node_modules/ws/lib/buffer-util.js b/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000..f7536e2 --- /dev/null +++ b/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,131 @@ +'use strict'; + +const { EMPTY_BUFFER } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + module.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + module.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/node_modules/ws/lib/constants.js b/node_modules/ws/lib/constants.js new file mode 100644 index 0000000..d691b30 --- /dev/null +++ b/node_modules/ws/lib/constants.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; diff --git a/node_modules/ws/lib/event-target.js b/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000..fea4cbc --- /dev/null +++ b/node_modules/ws/lib/event-target.js @@ -0,0 +1,292 @@ +'use strict'; + +const { kForOnEventAttribute, kListener } = require('./constants'); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute] && + listener[kListener] === handler && + !listener[kForOnEventAttribute] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} diff --git a/node_modules/ws/lib/extension.js b/node_modules/ws/lib/extension.js new file mode 100644 index 0000000..3d7895c --- /dev/null +++ b/node_modules/ws/lib/extension.js @@ -0,0 +1,203 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; diff --git a/node_modules/ws/lib/limiter.js b/node_modules/ws/lib/limiter.js new file mode 100644 index 0000000..3fd3578 --- /dev/null +++ b/node_modules/ws/lib/limiter.js @@ -0,0 +1,55 @@ +'use strict'; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; diff --git a/node_modules/ws/lib/permessage-deflate.js b/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000..77d918b --- /dev/null +++ b/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,514 @@ +'use strict'; + +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const Limiter = require('./limiter'); +const { kStatusCode } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/node_modules/ws/lib/receiver.js b/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000..96f572c --- /dev/null +++ b/node_modules/ws/lib/receiver.js @@ -0,0 +1,627 @@ +'use strict'; + +const { Writable } = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = require('./constants'); +const { concat, toArrayBuffer, unmask } = require('./buffer-util'); +const { isValidStatusCode, isValidUTF8 } = require('./validation'); + +const FastBuffer = Buffer[Symbol.species]; +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + let err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + default: + // `INFLATING` + this._loop = false; + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (!this._fragmented) { + this._loop = false; + return error( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + } + + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + this._loop = false; + return error( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } + } else { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + } + } else if (this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64() { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength() { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb( + error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ) + ); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage() { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data, true); + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + this._loop = false; + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('message', buf, false); + } + } + + this._state = GET_INFO; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + return error( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('conclude', code, buf); + this.end(); + } + } else if (this._opcode === 0x09) { + this.emit('ping', data); + } else { + this.emit('pong', data); + } + + this._state = GET_INFO; + } +} + +module.exports = Receiver; + +/** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ +function error(ErrorCtor, message, prefix, statusCode, errorCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; +} diff --git a/node_modules/ws/lib/sender.js b/node_modules/ws/lib/sender.js new file mode 100644 index 0000000..c848853 --- /dev/null +++ b/node_modules/ws/lib/sender.js @@ -0,0 +1,478 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls$" }] */ + +'use strict'; + +const net = require('net'); +const tls = require('tls'); +const { randomFillSync } = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { EMPTY_BUFFER } = require('./constants'); +const { isValidStatusCode } = require('./validation'); +const { mask: applyMask, toBuffer } = require('./buffer-util'); + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {(net.Socket|tls.Socket)} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + randomFillSync(mask, 0, 4); + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender.frame(data, { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1: false + }), + cb + ); + } + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < this._queue.length; i++) { + const params = this._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } + + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; diff --git a/node_modules/ws/lib/stream.js b/node_modules/ws/lib/stream.js new file mode 100644 index 0000000..230734b --- /dev/null +++ b/node_modules/ws/lib/stream.js @@ -0,0 +1,159 @@ +'use strict'; + +const { Duplex } = require('stream'); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) ws.pause(); + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.isPaused) ws.resume(); + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; diff --git a/node_modules/ws/lib/subprotocol.js b/node_modules/ws/lib/subprotocol.js new file mode 100644 index 0000000..d4381e8 --- /dev/null +++ b/node_modules/ws/lib/subprotocol.js @@ -0,0 +1,62 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; diff --git a/node_modules/ws/lib/validation.js b/node_modules/ws/lib/validation.js new file mode 100644 index 0000000..c352e6e --- /dev/null +++ b/node_modules/ws/lib/validation.js @@ -0,0 +1,130 @@ +'use strict'; + +const { isUtf8 } = require('buffer'); + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +module.exports = { + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars +}; + +if (isUtf8) { + module.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/node_modules/ws/lib/websocket-server.js b/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000..bac30eb --- /dev/null +++ b/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,535 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^net|tls|https$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const http = require('http'); +const https = require('https'); +const net = require('net'); +const tls = require('tls'); +const { createHash } = require('crypto'); + +const extension = require('./extension'); +const PerMessageDeflate = require('./permessage-deflate'); +const subprotocol = require('./subprotocol'); +const WebSocket = require('./websocket'); +const { GUID, kWebSocket } = require('./constants'); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (req.headers.upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!key || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 8 && version !== 13) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @private + */ +function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message); + } +} diff --git a/node_modules/ws/lib/websocket.js b/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000..b2b2b09 --- /dev/null +++ b/node_modules/ws/lib/websocket.js @@ -0,0 +1,1311 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Readable$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const https = require('https'); +const http = require('http'); +const net = require('net'); +const tls = require('tls'); +const { randomBytes, createHash } = require('crypto'); +const { Readable } = require('stream'); +const { URL } = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = require('./constants'); +const { + EventTarget: { addEventListener, removeEventListener } +} = require('./event-target'); +const { format, parse } = require('./extension'); +const { toBuffer } = require('./buffer-util'); + +const closeTimeout = 30 * 1000; +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._isServer = true; + } + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the + * required default "blob" type (instead we define a custom "nodebuffer" + * type). + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {(net.Socket|tls.Socket)} socket The network socket between the + * server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + this._sender = new Sender(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + socket.setTimeout(0); + socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + // + // Specify a timeout for the closing handshake to complete. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: undefined, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + websocket._url = address.href; + } else { + try { + parsedUrl = new URL(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + + websocket._url = address; + } + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + if (res.headers.upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + websocket.emit('error', err); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + websocket.pong(data, !websocket._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The listener of the `net.Socket` `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the `net.Socket` `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the `net.Socket` `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the `net.Socket` `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/node_modules/ws/package.json b/node_modules/ws/package.json new file mode 100644 index 0000000..4b5d92b --- /dev/null +++ b/node_modules/ws/package.json @@ -0,0 +1,65 @@ +{ + "name": "ws", + "version": "8.13.0", + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "homepage": "https://github.com/websockets/ws", + "bugs": "https://github.com/websockets/ws/issues", + "repository": "websockets/ws", + "author": "Einar Otto Stangvik (http://2x.io)", + "license": "MIT", + "main": "index.js", + "exports": { + ".": { + "browser": "./browser.js", + "import": "./wrapper.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "browser": "browser.js", + "engines": { + "node": ">=10.0.0" + }, + "files": [ + "browser.js", + "index.js", + "lib/*.js", + "wrapper.mjs" + ], + "scripts": { + "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", + "integration": "mocha --throw-deprecation test/*.integration.js", + "lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + }, + "devDependencies": { + "benchmark": "^2.1.4", + "bufferutil": "^4.0.1", + "eslint": "^8.0.0", + "eslint-config-prettier": "^8.1.0", + "eslint-plugin-prettier": "^4.0.0", + "mocha": "^8.4.0", + "nyc": "^15.0.0", + "prettier": "^2.0.5", + "utf-8-validate": "^6.0.0" + } +} diff --git a/node_modules/ws/wrapper.mjs b/node_modules/ws/wrapper.mjs new file mode 100644 index 0000000..7245ad1 --- /dev/null +++ b/node_modules/ws/wrapper.mjs @@ -0,0 +1,8 @@ +import createWebSocketStream from './lib/stream.js'; +import Receiver from './lib/receiver.js'; +import Sender from './lib/sender.js'; +import WebSocket from './lib/websocket.js'; +import WebSocketServer from './lib/websocket-server.js'; + +export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer }; +export default WebSocket; diff --git a/node_modules/xdg-basedir/index.d.ts b/node_modules/xdg-basedir/index.d.ts new file mode 100644 index 0000000..c70b7d4 --- /dev/null +++ b/node_modules/xdg-basedir/index.d.ts @@ -0,0 +1,81 @@ +declare const xdgBasedir: { + /** + Directory for user-specific data files. + + @example + ```js + import xdgBasedir = require('xdg-basedir'); + + xdgBasedir.data; + //=> '/home/sindresorhus/.local/share' + ``` + */ + readonly data?: string; + + /** + Directory for user-specific configuration files. + + @example + ```js + import xdgBasedir = require('xdg-basedir'); + + xdgBasedir.config; + //=> '/home/sindresorhus/.config' + ``` + */ + readonly config?: string; + + /** + Directory for user-specific non-essential data files. + + @example + ```js + import xdgBasedir = require('xdg-basedir'); + + xdgBasedir.cache; + //=> '/home/sindresorhus/.cache' + ``` + */ + readonly cache?: string; + + /** + Directory for user-specific non-essential runtime files and other file objects (such as sockets, named pipes, etc). + + @example + ```js + import xdgBasedir = require('xdg-basedir'); + + xdgBasedir.runtime; + //=> '/run/user/sindresorhus' + ``` + */ + readonly runtime?: string; + + /** + Preference-ordered array of base directories to search for data files in addition to `.data`. + + @example + ```js + import xdgBasedir = require('xdg-basedir'); + + xdgBasedir.dataDirs + //=> ['/home/sindresorhus/.local/share', '/usr/local/share/', '/usr/share/'] + ``` + */ + readonly dataDirs: readonly string[]; + + /** + Preference-ordered array of base directories to search for configuration files in addition to `.config`. + + @example + ```js + import xdgBasedir = require('xdg-basedir'); + + xdgBasedir.configDirs; + //=> ['/home/sindresorhus/.config', '/etc/xdg'] + ``` + */ + readonly configDirs: readonly string[]; +}; + +export = xdgBasedir; diff --git a/node_modules/xdg-basedir/index.js b/node_modules/xdg-basedir/index.js new file mode 100644 index 0000000..0da1f2f --- /dev/null +++ b/node_modules/xdg-basedir/index.js @@ -0,0 +1,28 @@ +'use strict'; +const os = require('os'); +const path = require('path'); + +const homeDirectory = os.homedir(); +const {env} = process; + +exports.data = env.XDG_DATA_HOME || + (homeDirectory ? path.join(homeDirectory, '.local', 'share') : undefined); + +exports.config = env.XDG_CONFIG_HOME || + (homeDirectory ? path.join(homeDirectory, '.config') : undefined); + +exports.cache = env.XDG_CACHE_HOME || (homeDirectory ? path.join(homeDirectory, '.cache') : undefined); + +exports.runtime = env.XDG_RUNTIME_DIR || undefined; + +exports.dataDirs = (env.XDG_DATA_DIRS || '/usr/local/share/:/usr/share/').split(':'); + +if (exports.data) { + exports.dataDirs.unshift(exports.data); +} + +exports.configDirs = (env.XDG_CONFIG_DIRS || '/etc/xdg').split(':'); + +if (exports.config) { + exports.configDirs.unshift(exports.config); +} diff --git a/node_modules/xdg-basedir/license b/node_modules/xdg-basedir/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/xdg-basedir/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/xdg-basedir/package.json b/node_modules/xdg-basedir/package.json new file mode 100644 index 0000000..37e83a9 --- /dev/null +++ b/node_modules/xdg-basedir/package.json @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "xdg-basedir@4.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "xdg-basedir@4.0.0", + "_id": "xdg-basedir@4.0.0", + "_inBundle": false, + "_integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", + "_location": "/xdg-basedir", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "xdg-basedir@4.0.0", + "name": "xdg-basedir", + "escapedName": "xdg-basedir", + "rawSpec": "4.0.0", + "saveSpec": null, + "fetchSpec": "4.0.0" + }, + "_requiredBy": [ + "/configstore", + "/nodemon/update-notifier", + "/update-notifier" + ], + "_resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", + "_spec": "4.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/xdg-basedir/issues" + }, + "description": "Get XDG Base Directory paths", + "devDependencies": { + "ava": "^1.4.1", + "import-fresh": "^3.0.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/xdg-basedir#readme", + "keywords": [ + "xdg", + "base", + "directory", + "basedir", + "path", + "data", + "config", + "cache", + "linux", + "unix", + "spec" + ], + "license": "MIT", + "name": "xdg-basedir", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/xdg-basedir.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "4.0.0" +} diff --git a/node_modules/xdg-basedir/readme.md b/node_modules/xdg-basedir/readme.md new file mode 100644 index 0000000..f7aca05 --- /dev/null +++ b/node_modules/xdg-basedir/readme.md @@ -0,0 +1,60 @@ +# xdg-basedir [![Build Status](https://travis-ci.org/sindresorhus/xdg-basedir.svg?branch=master)](https://travis-ci.org/sindresorhus/xdg-basedir) + +> Get [XDG Base Directory](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) paths + + +## Install + +``` +$ npm install xdg-basedir +``` + + +## Usage + +```js +const xdgBasedir = require('xdg-basedir'); + +xdgBasedir.data; +//=> '/home/sindresorhus/.local/share' + +xdgBasedir.config; +//=> '/home/sindresorhus/.config' + +xdgBasedir.dataDirs +//=> ['/home/sindresorhus/.local/share', '/usr/local/share/', '/usr/share/'] +``` + + +## API + +The properties `.data`, `.config`, `.cache`, `.runtime` will return `null` in the uncommon case that both the XDG environment variable is not set and the users home directory can't be found. You need to handle this case. A common solution is to [fall back to a temp directory](https://github.com/yeoman/configstore/blob/b82690fc401318ad18dcd7d151a0003a4898a314/index.js#L15). + +### .data + +Directory for user-specific data files. + +### .config + +Directory for user-specific configuration files. + +### .cache + +Directory for user-specific non-essential data files. + +### .runtime + +Directory for user-specific non-essential runtime files and other file objects (such as sockets, named pipes, etc). + +### .dataDirs + +Preference-ordered array of base directories to search for data files in addition to `.data`. + +### .configDirs + +Preference-ordered array of base directories to search for configuration files in addition to `.config`. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/yallist/LICENSE b/node_modules/yallist/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/yallist/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/yallist/README.md b/node_modules/yallist/README.md new file mode 100644 index 0000000..f586101 --- /dev/null +++ b/node_modules/yallist/README.md @@ -0,0 +1,204 @@ +# yallist + +Yet Another Linked List + +There are many doubly-linked list implementations like it, but this +one is mine. + +For when an array would be too big, and a Map can't be iterated in +reverse order. + + +[![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) + +## basic usage + +```javascript +var yallist = require('yallist') +var myList = yallist.create([1, 2, 3]) +myList.push('foo') +myList.unshift('bar') +// of course pop() and shift() are there, too +console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] +myList.forEach(function (k) { + // walk the list head to tail +}) +myList.forEachReverse(function (k, index, list) { + // walk the list tail to head +}) +var myDoubledList = myList.map(function (k) { + return k + k +}) +// now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] +// mapReverse is also a thing +var myDoubledListReverse = myList.mapReverse(function (k) { + return k + k +}) // ['foofoo', 6, 4, 2, 'barbar'] + +var reduced = myList.reduce(function (set, entry) { + set += entry + return set +}, 'start') +console.log(reduced) // 'startfoo123bar' +``` + +## api + +The whole API is considered "public". + +Functions with the same name as an Array method work more or less the +same way. + +There's reverse versions of most things because that's the point. + +### Yallist + +Default export, the class that holds and manages a list. + +Call it with either a forEach-able (like an array) or a set of +arguments, to initialize the list. + +The Array-ish methods all act like you'd expect. No magic length, +though, so if you change that it won't automatically prune or add +empty spots. + +### Yallist.create(..) + +Alias for Yallist function. Some people like factories. + +#### yallist.head + +The first node in the list + +#### yallist.tail + +The last node in the list + +#### yallist.length + +The number of nodes in the list. (Change this at your peril. It is +not magic like Array length.) + +#### yallist.toArray() + +Convert the list to an array. + +#### yallist.forEach(fn, [thisp]) + +Call a function on each item in the list. + +#### yallist.forEachReverse(fn, [thisp]) + +Call a function on each item in the list, in reverse order. + +#### yallist.get(n) + +Get the data at position `n` in the list. If you use this a lot, +probably better off just using an Array. + +#### yallist.getReverse(n) + +Get the data at position `n`, counting from the tail. + +#### yallist.map(fn, thisp) + +Create a new Yallist with the result of calling the function on each +item. + +#### yallist.mapReverse(fn, thisp) + +Same as `map`, but in reverse. + +#### yallist.pop() + +Get the data from the list tail, and remove the tail from the list. + +#### yallist.push(item, ...) + +Insert one or more items to the tail of the list. + +#### yallist.reduce(fn, initialValue) + +Like Array.reduce. + +#### yallist.reduceReverse + +Like Array.reduce, but in reverse. + +#### yallist.reverse + +Reverse the list in place. + +#### yallist.shift() + +Get the data from the list head, and remove the head from the list. + +#### yallist.slice([from], [to]) + +Just like Array.slice, but returns a new Yallist. + +#### yallist.sliceReverse([from], [to]) + +Just like yallist.slice, but the result is returned in reverse. + +#### yallist.toArray() + +Create an array representation of the list. + +#### yallist.toArrayReverse() + +Create a reversed array representation of the list. + +#### yallist.unshift(item, ...) + +Insert one or more items to the head of the list. + +#### yallist.unshiftNode(node) + +Move a Node object to the front of the list. (That is, pull it out of +wherever it lives, and make it the new head.) + +If the node belongs to a different list, then that list will remove it +first. + +#### yallist.pushNode(node) + +Move a Node object to the end of the list. (That is, pull it out of +wherever it lives, and make it the new tail.) + +If the node belongs to a list already, then that list will remove it +first. + +#### yallist.removeNode(node) + +Remove a node from the list, preserving referential integrity of head +and tail and other nodes. + +Will throw an error if you try to have a list remove a node that +doesn't belong to it. + +### Yallist.Node + +The class that holds the data and is actually the list. + +Call with `var n = new Node(value, previousNode, nextNode)` + +Note that if you do direct operations on Nodes themselves, it's very +easy to get into weird states where the list is broken. Be careful :) + +#### node.next + +The next node in the list. + +#### node.prev + +The previous node in the list. + +#### node.value + +The data the node contains. + +#### node.list + +The list to which this node belongs. (Null if it does not belong to +any list.) diff --git a/node_modules/yallist/iterator.js b/node_modules/yallist/iterator.js new file mode 100644 index 0000000..d41c97a --- /dev/null +++ b/node_modules/yallist/iterator.js @@ -0,0 +1,8 @@ +'use strict' +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } +} diff --git a/node_modules/yallist/package.json b/node_modules/yallist/package.json new file mode 100644 index 0000000..ce6e20b --- /dev/null +++ b/node_modules/yallist/package.json @@ -0,0 +1,65 @@ +{ + "_args": [ + [ + "yallist@4.0.0", + "/home/other/discord_bot" + ] + ], + "_from": "yallist@4.0.0", + "_id": "yallist@4.0.0", + "_inBundle": false, + "_integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "_location": "/yallist", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "yallist@4.0.0", + "name": "yallist", + "escapedName": "yallist", + "rawSpec": "4.0.0", + "saveSpec": null, + "fetchSpec": "4.0.0" + }, + "_requiredBy": [ + "/lru-cache" + ], + "_resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "_spec": "4.0.0", + "_where": "/home/other/discord_bot", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/yallist/issues" + }, + "dependencies": {}, + "description": "Yet Another Linked List", + "devDependencies": { + "tap": "^12.1.0" + }, + "directories": { + "test": "test" + }, + "files": [ + "yallist.js", + "iterator.js" + ], + "homepage": "https://github.com/isaacs/yallist#readme", + "license": "ISC", + "main": "yallist.js", + "name": "yallist", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/yallist.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap test/*.js --100" + }, + "version": "4.0.0" +} diff --git a/node_modules/yallist/yallist.js b/node_modules/yallist/yallist.js new file mode 100644 index 0000000..4e83ab1 --- /dev/null +++ b/node_modules/yallist/yallist.js @@ -0,0 +1,426 @@ +'use strict' +module.exports = Yallist + +Yallist.Node = Node +Yallist.create = Yallist + +function Yallist (list) { + var self = this + if (!(self instanceof Yallist)) { + self = new Yallist() + } + + self.tail = null + self.head = null + self.length = 0 + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item) + }) + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]) + } + } + + return self +} + +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next + var prev = node.prev + + if (next) { + next.prev = prev + } + + if (prev) { + prev.next = next + } + + if (node === this.head) { + this.head = next + } + if (node === this.tail) { + this.tail = prev + } + + node.list.length-- + node.next = null + node.prev = null + node.list = null + + return next +} + +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var head = this.head + node.list = this + node.next = head + if (head) { + head.prev = node + } + + this.head = node + if (!this.tail) { + this.tail = node + } + this.length++ +} + +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var tail = this.tail + node.list = this + node.prev = tail + if (tail) { + tail.next = node + } + + this.tail = node + if (!this.head) { + this.head = node + } + this.length++ +} + +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value + this.tail = this.tail.prev + if (this.tail) { + this.tail.next = null + } else { + this.head = null + } + this.length-- + return res +} + +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value + this.head = this.head.next + if (this.head) { + this.head.prev = null + } else { + this.tail = null + } + this.length-- + return res +} + +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this) + walker = walker.next + } +} + +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this) + walker = walker.prev + } +} + +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.next + } + return res +} + +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.prev + } + return res +} + +Yallist.prototype.reduce = function (fn, initial) { + var acc + var walker = this.head + if (arguments.length > 1) { + acc = initial + } else if (this.head) { + walker = this.head.next + acc = this.head.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i) + walker = walker.next + } + + return acc +} + +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc + var walker = this.tail + if (arguments.length > 1) { + acc = initial + } else if (this.tail) { + walker = this.tail.prev + acc = this.tail.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i) + walker = walker.prev + } + + return acc +} + +Yallist.prototype.toArray = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value + walker = walker.next + } + return arr +} + +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value + walker = walker.prev + } + return arr +} + +Yallist.prototype.slice = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1 + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next + } + + var ret = [] + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value) + walker = this.removeNode(walker) + } + if (walker === null) { + walker = this.tail + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]) + } + return ret; +} + +Yallist.prototype.reverse = function () { + var head = this.head + var tail = this.tail + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev + walker.prev = walker.next + walker.next = p + } + this.head = tail + this.tail = head + return this +} + +function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self) + + if (inserted.next === null) { + self.tail = inserted + } + if (inserted.prev === null) { + self.head = inserted + } + + self.length++ + + return inserted +} + +function push (self, item) { + self.tail = new Node(item, self.tail, null, self) + if (!self.head) { + self.head = self.tail + } + self.length++ +} + +function unshift (self, item) { + self.head = new Node(item, null, self.head, self) + if (!self.tail) { + self.tail = self.head + } + self.length++ +} + +function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } + + this.list = list + this.value = value + + if (prev) { + prev.next = this + this.prev = prev + } else { + this.prev = null + } + + if (next) { + next.prev = this + this.next = next + } else { + this.next = null + } +} + +try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist) +} catch (er) {} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..4b887e9 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2117 @@ +{ + "name": "discord_bot", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@discordjs/voice": "^0.15.0", + "discord.js": "^14.8.0", + "getstream": "^7.2.10", + "node-fetch": "^2.6.9", + "nodemon": "^2.0.22", + "picomatch": "^2.3.0", + "update-notifier": "^5.1.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.15.3", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.15.3.tgz", + "integrity": "sha512-OvwMLqNXkCXSz1kSm58sEsNuhqOx/fKpnUnKnFB5v8uDda5bLNEHNgKPvhDN6IU0LDcnHQ90LlJ0Q6jnyBSIBA==", + "dependencies": { + "regenerator-runtime": "^0.13.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@discordjs/builders": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.5.0.tgz", + "integrity": "sha512-7XxT78mnNBPigHn2y6KAXkicxIBFtZREGWaRZ249EC1l6gBUEP8IyVY5JTciIjJArxkF+tg675aZvsTNTKBpmA==", + "dependencies": { + "@discordjs/formatters": "^0.2.0", + "@discordjs/util": "^0.2.0", + "@sapphire/shapeshift": "^3.8.1", + "discord-api-types": "^0.37.35", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.3", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/collection": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.4.0.tgz", + "integrity": "sha512-hiOJyk2CPFf1+FL3a4VKCuu1f448LlROVuu8nLz1+jCOAPokUcdFAV+l4pd3B3h6uJlJQSASoZzrdyNdjdtfzQ==", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.2.0.tgz", + "integrity": "sha512-vn4oMSXuMZUm8ITqVOtvE7/fMMISj4cI5oLsR09PEQXHKeKDAMLltG/DWeeIs7Idfy6V8Fk3rn1e69h7NfzuNA==", + "dependencies": { + "discord-api-types": "^0.37.35" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/rest": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.6.0.tgz", + "integrity": "sha512-HGvqNCZ5Z5j0tQHjmT1lFvE5ETO4hvomJ1r0cbnpC1zM23XhCpZ9wgTCiEmaxKz05cyf2CI9p39+9LL+6Yz1bA==", + "dependencies": { + "@discordjs/collection": "^1.4.0", + "@discordjs/util": "^0.2.0", + "@sapphire/async-queue": "^1.5.0", + "@sapphire/snowflake": "^3.4.0", + "discord-api-types": "^0.37.35", + "file-type": "^18.2.1", + "tslib": "^2.5.0", + "undici": "^5.20.0" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/util": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.2.0.tgz", + "integrity": "sha512-/8qNbebFzLWKOOg+UV+RB8itp4SmU5jw0tBUD3ifElW6rYNOj1Ku5JaSW7lLl/WgjjxF01l/1uQPCzkwr110vg==", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/voice": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@discordjs/voice/-/voice-0.15.0.tgz", + "integrity": "sha512-YEvrRchDhjB0QbI9QYOF/qgDwvGb9sNGUyks5d3Srl+VRoMoKkMzWY+wcEfVbAgdMIAdLi5vyrTKP/gLND26jA==", + "dependencies": { + "@types/ws": "^8.5.4", + "discord-api-types": "^0.37.35", + "prism-media": "^1.3.5", + "tslib": "^2.5.0", + "ws": "^8.12.1" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.0.tgz", + "integrity": "sha512-JkLdIsP8fPAdh9ZZjrbHWR/+mZj0wvKS5ICibcLrRI1j84UmLMshx5n9QmL8b95d4onJ2xxiyugTgSAX7AalmA==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.8.1.tgz", + "integrity": "sha512-xG1oXXBhCjPKbxrRTlox9ddaZTvVpOhYLmKmApD/vIWOV1xEYXnpoFs68zHIZBGbqztq6FrUPNPerIrO1Hqeaw==", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.4.0.tgz", + "integrity": "sha512-zZxymtVO6zeXVMPds+6d7gv/OfnCc25M1Z+7ZLB0oPmeMTPeRWVPQSS16oDJy5ZsyCOLj7M6mbZml5gWXcVRNw==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sindresorhus/is": { + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-0.14.0.tgz", + "integrity": "sha512-9NET910DNaIPngYnLLPeg+Ogzqsi9uM4mSboU5y6p8S5DzMTVEsJZrawi+BoDNUVBa2DhJqQYUFvMDfgU062LQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/@szmarczak/http-timer": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-1.1.2.tgz", + "integrity": "sha512-XIB2XbzHTN6ieIjfIMV9hlVcfPU26s2vafYWQcZHWXHOxiaRZYEDKEwdl129Zyg50+foYV2jCgtrqSA6qNuNSA==", + "dependencies": { + "defer-to-connect": "^1.0.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==" + }, + "node_modules/@types/jsonwebtoken": { + "version": "8.5.4", + "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-8.5.4.tgz", + "integrity": "sha512-4L8msWK31oXwdtC81RmRBAULd0ShnAHjBuKT9MRQpjP0piNrZdXyTRcKY9/UIfhGeKIT4PvF5amOOUbbT/9Wpg==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/jwt-decode": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@types/jwt-decode/-/jwt-decode-2.2.1.tgz", + "integrity": "sha512-aWw2YTtAdT7CskFyxEX2K21/zSDStuf/ikI3yBqmwpwJF0pS+/IX5DWv+1UFffZIbruP6cnT9/LAJV1gFwAT1A==" + }, + "node_modules/@types/node": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.6.1.tgz", + "integrity": "sha512-Sr7BhXEAer9xyGuCN3Ek9eg9xPviCF2gfu9kTfuU2HkTVAMYSDeX40fvpmo72n5nansg3nsBjuQBrsS28r+NUw==" + }, + "node_modules/@types/qs": { + "version": "6.9.7", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.7.tgz", + "integrity": "sha512-FGa1F62FT09qcrueBA6qYTrJPVDzah9a+493+o2PCXsesWHIn27G98TsSMs3WPNbZIEj4+VJf6saSFpvD+3Zsw==" + }, + "node_modules/@types/ws": { + "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/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, + "node_modules/ansi-align": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.0.tgz", + "integrity": "sha512-ZpClVKqXN3RGBmKibdfWzqCY4lnjEuoNzU5T0oEFpfd/z5qJHVarukridD4juLO2FXMiwUQxr9WqQtaYa8XRYw==", + "dependencies": { + "string-width": "^3.0.0" + } + }, + "node_modules/ansi-align/node_modules/ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-align/node_modules/emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==" + }, + "node_modules/ansi-align/node_modules/is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "engines": { + "node": ">=4" + } + }, + "node_modules/ansi-align/node_modules/string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dependencies": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-align/node_modules/strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dependencies": { + "ansi-regex": "^4.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=" + }, + "node_modules/axios": { + "version": "0.21.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", + "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", + "dependencies": { + "follow-redirects": "^1.14.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/boxen": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/boxen/-/boxen-5.1.2.tgz", + "integrity": "sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==", + "dependencies": { + "ansi-align": "^3.0.0", + "camelcase": "^6.2.0", + "chalk": "^4.1.0", + "cli-boxes": "^2.2.1", + "string-width": "^4.2.2", + "type-fest": "^0.20.2", + "widest-line": "^3.1.0", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, + "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" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/cacheable-request": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-6.1.0.tgz", + "integrity": "sha512-Oj3cAGPCqOZX7Rz64Uny2GYAZNliQSqfbePrgAQ1wKAihYmCUnraBtJtKcGR4xz7wF+LoJC+ssFZvv5BgF9Igg==", + "dependencies": { + "clone-response": "^1.0.2", + "get-stream": "^5.1.0", + "http-cache-semantics": "^4.0.0", + "keyv": "^3.0.0", + "lowercase-keys": "^2.0.0", + "normalize-url": "^4.1.0", + "responselike": "^1.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cacheable-request/node_modules/get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cacheable-request/node_modules/lowercase-keys": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz", + "integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camelcase": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz", + "integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==" + }, + "node_modules/cli-boxes": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-2.2.1.tgz", + "integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/clone-response": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.2.tgz", + "integrity": "sha1-0dyXOSAxTfZ/vrlCI7TuNQI56Ws=", + "dependencies": { + "mimic-response": "^1.0.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "node_modules/configstore": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/configstore/-/configstore-5.0.1.tgz", + "integrity": "sha512-aMKprgk5YhBNyH25hj8wGt2+D52Sw1DRRIzqBwLp2Ya9mFmY8KPvvtvmna8SxVR9JMZ4kzMD68N22vlaRpkeFA==", + "dependencies": { + "dot-prop": "^5.2.0", + "graceful-fs": "^4.1.2", + "make-dir": "^3.0.0", + "unique-string": "^2.0.0", + "write-file-atomic": "^3.0.0", + "xdg-basedir": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/crypto-random-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz", + "integrity": "sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/csprng": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/csprng/-/csprng-0.1.2.tgz", + "integrity": "sha1-S8aPEvo2jSUqWYQcusqXSxirReI=", + "dependencies": { + "sequin": "*" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/decompress-response": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-3.3.0.tgz", + "integrity": "sha1-gKTdMjdIOEv6JICDYirt7Jgq3/M=", + "dependencies": { + "mimic-response": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/defer-to-connect": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-1.1.3.tgz", + "integrity": "sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/discord-api-types": { + "version": "0.37.37", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.37.tgz", + "integrity": "sha512-LDMBKzl/zbvHO/yCzno5hevuA6lFIXJwdKSJZQrB+1ToDpFfN9thK+xxgZNR4aVkI7GHRDja0p4Sl2oYVPnHYg==" + }, + "node_modules/discord.js": { + "version": "14.8.0", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.8.0.tgz", + "integrity": "sha512-UOxYtc/YnV7jAJ2gISluJyYeBw4e+j8gWn+IoqG8unaHAVuvZ13DdYN0M1f9fbUgUvSarV798inIrYFtDNDjwQ==", + "dependencies": { + "@discordjs/builders": "^1.5.0", + "@discordjs/collection": "^1.4.0", + "@discordjs/formatters": "^0.2.0", + "@discordjs/rest": "^1.6.0", + "@discordjs/util": "^0.2.0", + "@sapphire/snowflake": "^3.4.0", + "@types/ws": "^8.5.4", + "discord-api-types": "^0.37.35", + "fast-deep-equal": "^3.1.3", + "lodash.snakecase": "^4.1.1", + "tslib": "^2.5.0", + "undici": "^5.20.0", + "ws": "^8.12.1" + }, + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/dot-prop": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", + "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/duplexer3": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz", + "integrity": "sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=" + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/escape-goat": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/escape-goat/-/escape-goat-2.1.1.tgz", + "integrity": "sha512-8/uIhbG12Csjy2JEW7D9pHbreaVaS/OpN3ycnyvElTdwM5n6GY6W6e2IPemfvGZeUMqZ9A/3GqIZMgKnBhAw/Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/faye": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/faye/-/faye-1.4.0.tgz", + "integrity": "sha512-kRrIg4be8VNYhycS2PY//hpBJSzZPr/DBbcy9VWelhZMW3KhyLkQR0HL0k0MNpmVoNFF4EdfMFkNAWjTP65g6w==", + "dependencies": { + "asap": "*", + "csprng": "*", + "faye-websocket": ">=0.9.1", + "safe-buffer": "*", + "tough-cookie": "*", + "tunnel-agent": "*" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/faye-websocket": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", + "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", + "dependencies": { + "websocket-driver": ">=0.5.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/file-type": { + "version": "18.2.1", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-18.2.1.tgz", + "integrity": "sha512-Yw5MtnMv7vgD2/6Bjmmuegc8bQEVA9GmAyaR18bMYWKqsWDG9wgYZ1j4I6gNMF5Y5JBDcUcjRQqNQx7Y8uotcg==", + "dependencies": { + "readable-web-to-node-stream": "^3.0.2", + "strtok3": "^7.0.0", + "token-types": "^5.0.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", + "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "node_modules/get-intrinsic": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.1.tgz", + "integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-stream": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", + "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/getstream": { + "version": "7.2.10", + "resolved": "https://registry.npmjs.org/getstream/-/getstream-7.2.10.tgz", + "integrity": "sha512-cSUBxZ8JiTyfTXwiYl6vwqrg1XTOR0YGA+sYSODtuxGBgAsBZIUWWA9mvWgbmWnzRNboL52+bhwyisvaZhxDAA==", + "dependencies": { + "@babel/runtime": "^7.13.10", + "@types/jsonwebtoken": "^8.5.0", + "@types/jwt-decode": "^2.2.1", + "@types/qs": "^6.9.6", + "axios": "^0.21.1", + "faye": "^1.4.0", + "form-data": "^4.0.0", + "jsonwebtoken": "^8.5.1", + "jwt-decode": "^3.1.2", + "qs": "^6.9.6" + }, + "engines": { + "node": "10 || 12 || >=14" + }, + "peerDependencies": { + "@types/node": ">=10" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/global-dirs": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-dirs/-/global-dirs-3.0.0.tgz", + "integrity": "sha512-v8ho2DS5RiCjftj1nD9NmnfaOzTdud7RRnVd9kFNOjqZbISlx5DQ+OrTkywgd0dIt7oFCvKetZSHoHcP3sDdiA==", + "dependencies": { + "ini": "2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/global-dirs/node_modules/ini": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ini/-/ini-2.0.0.tgz", + "integrity": "sha512-7PnF4oN3CvZF23ADhA5wRaYEQpJ8qygSkbtTXWBeXWXmEVRXK+1ITciHWwHhsjv1TmW0MgacIv6hEi5pX5NQdA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/got": { + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/got/-/got-9.6.0.tgz", + "integrity": "sha512-R7eWptXuGYxwijs0eV+v3o6+XH1IqVK8dJOEecQfTmkncw9AV4dcw/Dhxi8MdlqPthxxpZyizMzyg8RTmEsG+Q==", + "dependencies": { + "@sindresorhus/is": "^0.14.0", + "@szmarczak/http-timer": "^1.1.2", + "cacheable-request": "^6.0.0", + "decompress-response": "^3.3.0", + "duplexer3": "^0.1.4", + "get-stream": "^4.1.0", + "lowercase-keys": "^1.0.1", + "mimic-response": "^1.0.1", + "p-cancelable": "^1.0.0", + "to-readable-stream": "^1.0.0", + "url-parse-lax": "^3.0.0" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz", + "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==" + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-yarn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/has-yarn/-/has-yarn-2.1.0.tgz", + "integrity": "sha512-UqBRqi4ju7T+TqGNdqAO0PaSVGsDGJUBQvk9eUWNGRY1CFGDzYhLWoM7JQEemnlvVcv/YEmc2wNW8BC24EnUsw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/http-cache-semantics": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz", + "integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ==" + }, + "node_modules/http-parser-js": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.3.tgz", + "integrity": "sha512-t7hjvef/5HEK7RWTdUzVUhl8zkEu+LlaE0IYzdMuvbSDipxBRpOn4Uhw8ZyECEa808iVT8XCjzo6xmYt4CiLZg==" + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "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/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==" + }, + "node_modules/import-lazy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-2.1.0.tgz", + "integrity": "sha1-BWmOPUXIjo1+nZLLBYTnfwlvPkM=", + "engines": { + "node": ">=4" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ini": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.7.tgz", + "integrity": "sha512-iKpRpXP+CrP2jyrxvg1kMUpXDyRUFDWurxbnVT1vQPx+Wz9uCYsMIqYuSBLV+PAaZG/d7kRLKRFc9oDMsH+mFQ==" + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", + "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "dependencies": { + "ci-info": "^2.0.0" + }, + "bin": { + "is-ci": "bin.js" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-installed-globally": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/is-installed-globally/-/is-installed-globally-0.4.0.tgz", + "integrity": "sha512-iwGqO3J21aaSkC7jWnHP/difazwS7SFeIqxv6wEtLU8Y5KlzFTjyqcSIT0d8s4+dDhKytsk9PJZ2BkS5eZwQRQ==", + "dependencies": { + "global-dirs": "^3.0.0", + "is-path-inside": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-npm": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-npm/-/is-npm-5.0.0.tgz", + "integrity": "sha512-WW/rQLOazUq+ST/bCAVBp/2oMERWLsR7OrKyt052dNDk4DHcDE0/7QSXITlmi+VBcV13DfIbysG3tZJm5RfdBA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", + "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-path-inside": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", + "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "node_modules/is-yarn-global": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz", + "integrity": "sha512-VjSeb/lHmkoyd8ryPVIKvOCn4D1koMqY+vqyjjUfc3xyKtP4dYOxM44sZrnqQSzSds3xyOrUTLTC9LVCVgLngw==" + }, + "node_modules/json-buffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.0.tgz", + "integrity": "sha1-Wx85evx11ne96Lz8Dkfh+aPZqJg=" + }, + "node_modules/jsonwebtoken": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", + "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", + "dependencies": { + "jws": "^3.2.2", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^5.6.0" + }, + "engines": { + "node": ">=4", + "npm": ">=1.4.28" + } + }, + "node_modules/jwa": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", + "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", + "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "dependencies": { + "jwa": "^1.4.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jwt-decode": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-3.1.2.tgz", + "integrity": "sha512-UfpWE/VZn0iP50d8cz9NrZLM9lSWhcJ+0Gt/nm4by88UL+J1SiKN8/5dkjMmbEzwL2CAe+67GsegCbIKtbp75A==" + }, + "node_modules/keyv": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-3.1.0.tgz", + "integrity": "sha512-9ykJ/46SN/9KPM/sichzQ7OvXyGDYKGTaDlKMGCAlg2UK8KRy4jb0d8sFc+0Tt0YYnThq8X2RZgCg74RPxgcVA==", + "dependencies": { + "json-buffer": "3.0.0" + } + }, + "node_modules/latest-version": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/latest-version/-/latest-version-5.1.0.tgz", + "integrity": "sha512-weT+r0kTkRQdCdYCNtkMwWXQTMEswKrFBkm4ckQOMVhhqhIMI1UT2hMj+1iigIhgSZm5gTmrRXBNoGUgaTY1xA==", + "dependencies": { + "package-json": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==" + }, + "node_modules/lowercase-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-1.0.1.tgz", + "integrity": "sha512-G2Lj61tXDnVFFOi8VZds+SoQjtQC3dgokKdDG2mTm1tx4m50NUHBOZSBwQQHyy0V12A0JTG4icfZQH+xPyh8VA==", + "engines": { + "node": ">=0.10.0" + } + }, + "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/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/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/mime-db": { + "version": "1.46.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.46.0.tgz", + "integrity": "sha512-svXaP8UQRZ5K7or+ZmfNhg2xX3yKDMUzqadsSqi4NCH/KomcH75MAMYAGVlvXn4+b/xOPhS3I2uHKRUzvjY7BQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.29", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.29.tgz", + "integrity": "sha512-Y/jMt/S5sR9OaqteJtslsFZKWOIIqMACsJSiHghlCAyhf7jfVYjKBmLiX8OgpWeW+fjJ2b+Az69aPFPkUOY6xQ==", + "dependencies": { + "mime-db": "1.46.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz", + "integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==", + "engines": { + "node": ">=4" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/node-fetch": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", + "integrity": "sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/nodemon": { + "version": "2.0.22", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-2.0.22.tgz", + "integrity": "sha512-B8YqaKMmyuCO7BowF1Z1/mkPqLk6cs/l63Ojtd6otKjMx47Dq1utxfRxcavH1I7VSaL8n5BUaoutadnsX3AAVQ==", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^3.2.7", + "ignore-by-default": "^1.0.1", + "minimatch": "^3.1.2", + "pstree.remy": "^1.1.8", + "semver": "^5.7.1", + "simple-update-notifier": "^1.0.7", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=8.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/nopt": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-1.0.10.tgz", + "integrity": "sha512-NWmpvLSqUrgrAC9HCuxEvb+PSloHpqVu+FqcO4eeF2h5qYRhA7ev6KvelyQAKtegUbC6RypJnlEOhd8vloNKYg==", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "*" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/normalize-url": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-4.5.1.tgz", + "integrity": "sha512-9UZCFRHQdNrfTpGg8+1INIg93B6zE0aXMVFkw1WFwvO4SlZywU6aLg5Of0Ap/PgcbSw4LNxvMWXMeugwMCX0AA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/object-inspect": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.0.tgz", + "integrity": "sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-cancelable": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz", + "integrity": "sha512-s73XxOZ4zpt1edZYZzvhqFa6uvQc1vwUa0K0BdtIZgQMAJj9IbebH+JkgKZc9h+B05PKHLOTl4ajG1BmNrVZlw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/package-json": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/package-json/-/package-json-6.5.0.tgz", + "integrity": "sha512-k3bdm2n25tkyxcjSKzB5x8kfVxlMdgsbPr0GkZcwHsLpba6cBjqCt1KlcChKEvxHIcTB1FVMuwoijZ26xex5MQ==", + "dependencies": { + "got": "^9.6.0", + "registry-auth-token": "^4.0.0", + "registry-url": "^5.0.0", + "semver": "^6.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/package-json/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/peek-readable": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-5.0.0.tgz", + "integrity": "sha512-YtCKvLUOvwtMGmrniQPdO7MwPjgkFBtFIrmfSbYmYuq3tKDV/mcfAhBth1+C3ru7uXIZasc/pHnb+YDYNkkj4A==", + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/picomatch": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", + "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prepend-http": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/prepend-http/-/prepend-http-2.0.0.tgz", + "integrity": "sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=", + "engines": { + "node": ">=4" + } + }, + "node_modules/prism-media": { + "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 <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" + }, + "peerDependenciesMeta": { + "@discordjs/opus": { + "optional": true + }, + "ffmpeg-static": { + "optional": true + }, + "node-opus": { + "optional": true + }, + "opusscript": { + "optional": true + } + } + }, + "node_modules/psl": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.8.0.tgz", + "integrity": "sha512-RIdOzyoavK+hA18OGGWDqUTsCLhtA7IcZ/6NCs4fFJaHBDab+pDDmDIByWFRQJq2Cd7r1OoQxBGKOaztq+hjIQ==" + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==" + }, + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/pupa": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/pupa/-/pupa-2.1.1.tgz", + "integrity": "sha512-l1jNAspIBSFqbT+y+5FosojNpVpF94nlI+wDUpqP9enwOTfHx9f0gh5nB96vl+6yTpsJsypeNrwfzPrKuHB41A==", + "dependencies": { + "escape-goat": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qs": { + "version": "6.11.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.1.tgz", + "integrity": "sha512-0wsrzgTz/kAVIeuxSjnpGC56rzYtr6JT/2BwEvMaPhFIoYa1aGO8LbzuU1R0uUYQkLpWBTOj0l/CLAJB64J6nQ==", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "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", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/readable-web-to-node-stream": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/readable-web-to-node-stream/-/readable-web-to-node-stream-3.0.2.tgz", + "integrity": "sha512-ePeK6cc1EcKLEhJFt/AebMCLL+GgSKhuygrZ/GLaKZYEecIgIECf4UaUuaByiGtzckwR4ain9VzUh95T1exYGw==", + "dependencies": { + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.9", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.9.tgz", + "integrity": "sha512-p3VT+cOEgxFsRRA9X4lkI1E+k2/CtnKtU4gcxyaCUreilL/vqI6CdZ3wxVUx3UOUg+gnUOQQcRI7BmSI656MYA==" + }, + "node_modules/registry-auth-token": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/registry-auth-token/-/registry-auth-token-4.2.1.tgz", + "integrity": "sha512-6gkSb4U6aWJB4SF2ZvLb76yCBjcvufXBqvvEx1HbmKPkutswjW1xNVRY0+daljIYRbogN7O0etYSlbiaEQyMyw==", + "dependencies": { + "rc": "^1.2.8" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/registry-url": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/registry-url/-/registry-url-5.1.0.tgz", + "integrity": "sha512-8acYXXTI0AkQv6RAOjE3vOaIXZkT9wo4LOFbBKYQEEnnMNBpKqdUrI6S4NT0KPIo/WVvJ5tE/X5LF/TQUf0ekw==", + "dependencies": { + "rc": "^1.2.8" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/responselike": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/responselike/-/responselike-1.0.2.tgz", + "integrity": "sha1-kYcg7ztjHFZCvgaPFa3lpG9Loec=", + "dependencies": { + "lowercase-keys": "^1.0.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "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/semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/semver-diff": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/semver-diff/-/semver-diff-3.1.1.tgz", + "integrity": "sha512-GX0Ix/CJcHyB8c4ykpHGIAvLyOwOobtM/8d+TQkAd81/bEjgPHrfba41Vpesr7jX/t8Uh+R3EX9eAS5be+jQYg==", + "dependencies": { + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/semver-diff/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/sequin": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/sequin/-/sequin-0.1.1.tgz", + "integrity": "sha1-XC04nWajg3NOqvvEXt6ywcsb5wE=", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==" + }, + "node_modules/simple-update-notifier": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-1.1.0.tgz", + "integrity": "sha512-VpsrsJSUcJEseSbMHkrsrAVSdvVS5I96Qo1QAQ4FxQ9wXFcB+pjj7FB7/us9+GcgfW4ziHtYMc1J0PLczb55mg==", + "dependencies": { + "semver": "~7.0.0" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/simple-update-notifier/node_modules/semver": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.0.0.tgz", + "integrity": "sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-width": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", + "integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "dependencies": { + "ansi-regex": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strtok3": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-7.0.0.tgz", + "integrity": "sha512-pQ+V+nYQdC5H3Q7qBZAz/MO6lwGhoC2gOAjuouGf/VO0m7vQRh8QNMl2Uf6SwAtzZ9bOw3UIeBukEGNJl5dtXQ==", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "peek-readable": "^5.0.0" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-readable-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/to-readable-stream/-/to-readable-stream-1.0.0.tgz", + "integrity": "sha512-Iq25XBt6zD5npPhlLVXGFN3/gyR2/qODcKNNyTMd4vbm39HUaOiAM4PMq0eMVC/Tkxz+Zjdsc55g9yyz+Yq00Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/token-types": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-5.0.1.tgz", + "integrity": "sha512-Y2fmSnZjQdDb9W4w4r1tswlMHylzWIeOKpx0aZH9BgGtACHhrk3OkT52AzwcuqTRBZtvvnTjDBh8eynMulu8Vg==", + "dependencies": { + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/touch": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.0.tgz", + "integrity": "sha512-WBx8Uy5TLtOSRtIq+M03/sKDrXCLHxwDcquSP2c43Le03/9serjQBIztjRz6FkJez9D/hleyAXTBGLwwZUw9lA==", + "dependencies": { + "nopt": "~1.0.10" + }, + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tough-cookie": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", + "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", + "dependencies": { + "psl": "^1.1.33", + "punycode": "^2.1.1", + "universalify": "^0.1.2" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/ts-mixer": { + "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.5.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz", + "integrity": "sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/type-fest": { + "version": "0.20.2", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", + "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dependencies": { + "is-typedarray": "^1.0.0" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==" + }, + "node_modules/undici": { + "version": "5.21.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.21.0.tgz", + "integrity": "sha512-HOjK8l6a57b2ZGXOcUsI5NLfoTrfmbOl90ixJDl0AEFG4wgHNDQxtZy15/ZQp7HhjkpaGlp/eneMgtsu1dIlUA==", + "dependencies": { + "busboy": "^1.6.0" + }, + "engines": { + "node": ">=12.18" + } + }, + "node_modules/unique-string": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz", + "integrity": "sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg==", + "dependencies": { + "crypto-random-string": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/update-notifier": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/update-notifier/-/update-notifier-5.1.0.tgz", + "integrity": "sha512-ItnICHbeMh9GqUy31hFPrD1kcuZ3rpxDZbf4KUDavXwS0bW5m7SLbDQpGX3UYr072cbrF5hFUs3r5tUsPwjfHw==", + "dependencies": { + "boxen": "^5.0.0", + "chalk": "^4.1.0", + "configstore": "^5.0.1", + "has-yarn": "^2.1.0", + "import-lazy": "^2.1.0", + "is-ci": "^2.0.0", + "is-installed-globally": "^0.4.0", + "is-npm": "^5.0.0", + "is-yarn-global": "^0.3.0", + "latest-version": "^5.1.0", + "pupa": "^2.1.1", + "semver": "^7.3.4", + "semver-diff": "^3.1.1", + "xdg-basedir": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/yeoman/update-notifier?sponsor=1" + } + }, + "node_modules/update-notifier/node_modules/semver": { + "version": "7.3.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.5.tgz", + "integrity": "sha512-PoeGJYh8HK4BTO/a9Tf6ZG3veo/A7ZVsYrSA6J8ny9nb3B1VrpkuN+z9OE5wfE5p6H4LchYZsegiQgbJD94ZFQ==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/url-parse-lax": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/url-parse-lax/-/url-parse-lax-3.0.0.tgz", + "integrity": "sha1-FrXK/Afb42dsGxmZF3gj1lA6yww=", + "dependencies": { + "prepend-http": "^2.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "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==" + }, + "node_modules/websocket-driver": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.4.tgz", + "integrity": "sha512-b17KeDIQVjvb0ssuSDF2cYXSg2iztliJ4B9WdsuB6J952qCPKmnVq4DyW5motImXHDC1cBT/1UezrJVsKw5zjg==", + "dependencies": { + "http-parser-js": ">=0.5.1", + "safe-buffer": ">=5.1.0", + "websocket-extensions": ">=0.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/websocket-extensions": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", + "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", + "engines": { + "node": ">=0.8.0" + } + }, + "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==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/widest-line": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz", + "integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==", + "dependencies": { + "string-width": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + }, + "node_modules/write-file-atomic": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dependencies": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } + }, + "node_modules/ws": { + "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" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xdg-basedir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-4.0.0.tgz", + "integrity": "sha512-PSNhEJDejZYV7h50BohL09Er9VaIefr2LMAf3OEmpCkjOi34eYyQYAXUTjEQtZJTKcF0E2UKTh+osDLsgNim9Q==", + "engines": { + "node": ">=8" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..c6ac8ed --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "dependencies": { + "@discordjs/voice": "^0.15.0", + "discord.js": "^14.8.0", + "getstream": "^7.2.10", + "node-fetch": "^2.6.9", + "nodemon": "^2.0.22", + "picomatch": "^2.3.0", + "update-notifier": "^5.1.0" + } +} diff --git a/text2img.json b/text2img.json new file mode 100644 index 0000000..3649d22 --- /dev/null +++ b/text2img.json @@ -0,0 +1,4 @@ +{ + "id": "a26eb46f-028f-4443-9e89-1522766571ce", + "output_url": "https://api.deepai.org/job-view-file/a26eb46f-028f-4443-9e89-1522766571ce/outputs/output.jpg" +} \ No newline at end of file